From 1b319c61c9db35bb65c0aed61e373cd826fe9de8 Mon Sep 17 00:00:00 2001 From: Sandeep Kalra Date: Tue, 30 May 2017 22:35:32 -0500 Subject: [PATCH 1/2] Create shortUrl.go Added Go Impl. --- Go/shortUrl.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Go/shortUrl.go diff --git a/Go/shortUrl.go b/Go/shortUrl.go new file mode 100644 index 0000000..df577d9 --- /dev/null +++ b/Go/shortUrl.go @@ -0,0 +1,54 @@ +/** + * ShortURL: Bijective conversion between natural numbers (IDs) and short strings + * Licensed under the MIT License (https://opensource.org/licenses/MIT) + * + * ShortURL::encode() takes an ID and turns it into a short string + * ShortURL::decode() takes a short string and turns it into an ID + * + * Features: + * + large alphabet (51 chars) and thus very short resulting strings + * + proof against offensive words (removed 'a', 'e', 'i', 'o' and 'u') + * + unambiguous (removed 'I', 'l', '1', 'O' and '0') + **/ +package ShortUrl + +import ( + "fmt" + "strings" +) + +const ( + Alphabets = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ-_" + Base = len(Alphabets) +) + +type Codec struct{} + +func (c *Codec) Encode(n int) string { + var s string + for n > 0 { + c := string(Alphabets[n%Base]) + fmt.Println(c) + s = c + s + n /= Base + } + return s +} + +func (c *Codec) Decode(path string) (int, error) { + n := 0 + for _, c := range path { + i := strings.Index(Alphabets, string(c)) + if i < 0 { + return 0, fmt.Errorf("Invalid input %s", path) + } else { + n = n*Base + i + } + + } + return n, nil +} +func InitShortingCodec() *Codec { + codec := Codec{} + return &codec +} From db8b1e37b73b352452d72c8e0e0b20cfa926116c Mon Sep 17 00:00:00 2001 From: Deepshikha Kalra Date: Wed, 31 May 2017 18:15:49 -0500 Subject: [PATCH 2/2] fixed typos, and made error more clearer --- Go/shortUrl.go | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/Go/shortUrl.go b/Go/shortUrl.go index df577d9..38366ff 100644 --- a/Go/shortUrl.go +++ b/Go/shortUrl.go @@ -10,7 +10,7 @@ * + proof against offensive words (removed 'a', 'e', 'i', 'o' and 'u') * + unambiguous (removed 'I', 'l', '1', 'O' and '0') **/ -package ShortUrl +package ShortURL import ( "fmt" @@ -27,9 +27,7 @@ type Codec struct{} func (c *Codec) Encode(n int) string { var s string for n > 0 { - c := string(Alphabets[n%Base]) - fmt.Println(c) - s = c + s + s = string(Alphabets[n%Base]) + s n /= Base } return s @@ -40,7 +38,7 @@ func (c *Codec) Decode(path string) (int, error) { for _, c := range path { i := strings.Index(Alphabets, string(c)) if i < 0 { - return 0, fmt.Errorf("Invalid input %s", path) + return 0, fmt.Errorf("Invalid character %s in input %s", string(c), path) } else { n = n*Base + i } @@ -48,7 +46,8 @@ func (c *Codec) Decode(path string) (int, error) { } return n, nil } -func InitShortingCodec() *Codec { + +func InitShorteningCodec() *Codec { codec := Codec{} return &codec }