DEV Community

Discussion on: Daily Challenge #259 - Duplicate Encoder

Collapse
 
aminnairi profile image
Amin • Edited

Go

$ mkdir -p $GOPATH/src/encoder
$ cd $GOPATH/src/encoder
$ touch encoder.go
// Set of utilities to encode a string into different formats.
package encoder

import (
    "unicode"
    "strings"
)

// Encode a given string into a format comprised of left and right parens. If one character is present multiple times in the string, the left parens will be used to encode this character, otherwise, the right parens will be used.
func EncodeDuplicateParens(input string) string {
    encoded := strings.Builder{}
    occurrences := make(map[rune]int)

    for _, character := range input {
        occurrences[unicode.ToLower(character)]++
    }

    for _, character := range input {
        if occurrences[unicode.ToLower(character)] > 1 {
            encoded.WriteRune(')')
        } else {
            encoded.WriteRune('(')
        }
    }

    return encoded.String()
}
$ touch encoder_test.go
package encoder_test

import (
    "encoder"
    "fmt"
    "testing"
)

func TestWithMultipleStrings(t *testing.T) {
    valuesExpectations := map[string]string{
        "(( @": "))((",
        "Success": ")())())",
        "din": "(((",
        "recede": "()()()",
    }

    for value, expectation := range valuesExpectations {
        result := encoder.EncodeDuplicateParens(value)

        if expectation != result {
            t.Errorf("Expected encode.EncodeDuplicateParens(%q) to equal %q but got %q.", value, expectation, result)
        }
    }
}

func BenchmarkEncodeDuplicateParens(b *testing.B) {
    for index := 0; index < b.N; index++ {
        encoder.EncodeDuplicateParens("Success")
    }
}

func ExampleEncodeDuplicateParens() {
    values := []string{
        "(( @",
        "Success",
        "din",
        "recede",
    }

    for _, value := range values {
        fmt.Println(encoder.EncodeDuplicateParens(value));
    }

    // Output: ))((
    // )())())
    // (((
    // ()()()
}

$ go test -cover -bench .
goos: linux
goarch: amd64
pkg: encoder
BenchmarkEncodeDuplicateParens-4         4961448               256 ns/op
PASS
coverage: 100.0% of statements
ok      encoder 1.516s