From 93158bf5243f3aa8ef966148c1297fd443b7962a Mon Sep 17 00:00:00 2001 From: bavog81 Date: Wed, 3 Jul 2024 01:03:54 +0200 Subject: [PATCH] HW2 is completed --- hw02_unpack_string/unpack.go | 43 ++++++++++++++++++++++++++++--- hw02_unpack_string/unpack_test.go | 14 ++++++---- 2 files changed, 49 insertions(+), 8 deletions(-) diff --git a/hw02_unpack_string/unpack.go b/hw02_unpack_string/unpack.go index 41f003d..6f4b90a 100644 --- a/hw02_unpack_string/unpack.go +++ b/hw02_unpack_string/unpack.go @@ -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])) + 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 } diff --git a/hw02_unpack_string/unpack_test.go b/hw02_unpack_string/unpack_test.go index 9799e18..c34e3b4 100644 --- a/hw02_unpack_string/unpack_test.go +++ b/hw02_unpack_string/unpack_test.go @@ -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 { @@ -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) {