summaryrefslogtreecommitdiff
path: root/go/run-length-encoding/run_length_encoding.go
diff options
context:
space:
mode:
Diffstat (limited to 'go/run-length-encoding/run_length_encoding.go')
-rw-r--r--go/run-length-encoding/run_length_encoding.go60
1 files changed, 60 insertions, 0 deletions
diff --git a/go/run-length-encoding/run_length_encoding.go b/go/run-length-encoding/run_length_encoding.go
new file mode 100644
index 0000000..07fdcd9
--- /dev/null
+++ b/go/run-length-encoding/run_length_encoding.go
@@ -0,0 +1,60 @@
+package encode
+
+import (
+ "fmt"
+ "strings"
+)
+
+func encodeLength(s string) (n int) {
+ var last rune
+ for _, c := range s {
+ if last == 0 {
+ last = c
+ }
+ if c != last {
+ break
+ }
+ n++
+ }
+ return n
+}
+
+func RunLengthEncode(input string) string {
+ var s strings.Builder
+ for len(input) != 0 {
+ n := encodeLength(input)
+ if n == 1 {
+ fmt.Fprintf(&s, "%c", input[0])
+ } else {
+ fmt.Fprintf(&s, "%d%c", n, input[0])
+ }
+ input = input[n:]
+ }
+ return s.String()
+}
+
+func decodeLength(s string) (number, count int) {
+ for _, c := range s {
+ if c >= '0' && c <= '9' {
+ number *= 10
+ number += int(c) - '0'
+ count++
+ } else {
+ break
+ }
+ }
+ if number == 0 {
+ number = 1
+ }
+ return number, count
+}
+
+func RunLengthDecode(input string) string {
+ var s strings.Builder
+ for len(input) > 0 {
+ n, c := decodeLength(input)
+ s.WriteString(strings.Repeat(string(input[c]), n))
+ input = input[c+1:]
+ }
+ return s.String()
+}