Created
June 14, 2022 10:00
-
-
Save ptflp/f1ec0b2a541fbdd1c2f5c7c2330955ef to your computer and use it in GitHub Desktop.
RLE Golang implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strconv" | |
"strings" | |
) | |
func main() { | |
str := "aaaaaabbbbacccccaaabbbbbc" | |
encoded := Encode(str) | |
fmt.Println(encoded) | |
decoded := Decode(encoded) | |
fmt.Println(decoded) | |
fmt.Println(str) | |
} | |
func Encode(raw string) string { | |
var prev int32 | |
var res string | |
var count int | |
_ = prev | |
for idx, chr := range raw { | |
if idx == 0 { | |
prev = chr | |
res += fmt.Sprintf("%s", string(chr)) | |
} | |
if prev != chr { | |
res += fmt.Sprintf("%d%s", count, string(chr)) | |
count = 1 | |
prev = chr | |
} else { | |
count++ | |
} | |
if idx == len(raw)-1 { | |
res += fmt.Sprintf("%d", count) | |
} | |
} | |
return res | |
} | |
var numeric = map[string]struct{}{ | |
"0": {}, | |
"1": {}, | |
"2": {}, | |
"3": {}, | |
"4": {}, | |
"5": {}, | |
"6": {}, | |
"7": {}, | |
"8": {}, | |
"9": {}, | |
} | |
func Decode(encoded string) string { | |
var count string | |
var res string | |
var prev string | |
for _, chr := range encoded { | |
char := string(chr) | |
if _, isNumeric := numeric[char]; isNumeric { | |
count += char | |
} else { | |
n, _ := strconv.Atoi(count) | |
res += strings.Repeat(prev, n) | |
count = "" | |
prev = char | |
} | |
} | |
n, _ := strconv.Atoi(count) | |
res += strings.Repeat(prev, n) | |
return res | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment