Skip to content

Commit

Permalink
HW2 is completed
Browse files Browse the repository at this point in the history
  • Loading branch information
Vabogco committed Jul 2, 2024
1 parent a24ce3a commit 93158bf
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 8 deletions.
43 changes: 40 additions & 3 deletions hw02_unpack_string/unpack.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,48 @@ package hw02unpackstring

import (
"errors"
"strconv"
"strings"
)

var ErrInvalidString = errors.New("invalid string")

func Unpack(_ string) (string, error) {
// Place your code here.
return "", nil
func Unpack(s string) (string, error) {
var result strings.Builder
k := false

for i, j := 0, 1; i < len(s); i, j = i+1, j+1 {
if !k {
_, error := strconv.Atoi(string(s[i]))

Check warning on line 17 in hw02_unpack_string/unpack.go

View workflow job for this annotation

GitHub Actions / lint

redefines-builtin-id: redefinition of the built-in type error (revive)
if error == nil {
return "", ErrInvalidString
}
}

b := string(s[i])

if b == "\\" && !k {
k = true
continue
}

if j < len(s) {
num, err := strconv.Atoi(string(s[j]))

if err == nil {
repstr := strings.Repeat(b, num)
result.WriteString(repstr)
i++
j++
} else {
result.WriteString(string(s[i]))
}
} else {
result.WriteString(string(s[i]))
}

k = false
}

return result.String(), nil
}
14 changes: 9 additions & 5 deletions hw02_unpack_string/unpack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,15 @@ func TestUnpack(t *testing.T) {
{input: "abccd", expected: "abccd"},
{input: "", expected: ""},
{input: "aaa0b", expected: "aab"},
{input: "a0", expected: ""},
// uncomment if task with asterisk completed
// {input: `qwe\4\5`, expected: `qwe45`},
// {input: `qwe\45`, expected: `qwe44444`},
// {input: `qwe\\5`, expected: `qwe\\\\\`},
// {input: `qwe\\\3`, expected: `qwe\3`},
{input: `qwe\4\5`, expected: `qwe45`},
{input: `qwe\45`, expected: `qwe44444`},
{input: `qwe\\5`, expected: `qwe\\\\\`},
{input: `qwe\\\3`, expected: `qwe\3`},
{input: `a\00`, expected: `a`},
{input: `\0\\\`, expected: `0\`},
{input: `\0\\0`, expected: `0`},
}

for _, tc := range tests {
Expand All @@ -34,7 +38,7 @@ func TestUnpack(t *testing.T) {
}

func TestUnpackInvalidString(t *testing.T) {
invalidStrings := []string{"3abc", "45", "aaa10b"}
invalidStrings := []string{"3abc", "45", "aaa10b", "a0a0a01"}
for _, tc := range invalidStrings {
tc := tc
t.Run(tc, func(t *testing.T) {
Expand Down

0 comments on commit 93158bf

Please sign in to comment.