Last active
September 15, 2024 00:52
-
-
Save kirkegaard/8d72fd90ee4f29abfc41c690b905e63c to your computer and use it in GitHub Desktop.
Go RLE encoder/decoder
This file contains 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 ( | |
"errors" | |
"fmt" | |
"strconv" | |
) | |
func rleEncode(input string) (string, error) { | |
if len(input) == 0 { | |
return "", errors.New("Input is empty") | |
} | |
result := "" | |
count := 1 | |
for i := 1; i < len(input); i++ { | |
if input[i] == input[i-1] { | |
count++ | |
} else { | |
result += strconv.Itoa(count) + string(input[i-1]) | |
count = 1 | |
} | |
} | |
result += strconv.Itoa(count) + string(input[len(input)-1]) | |
return result, nil | |
} | |
func rleDecode(input string) (string, error) { | |
if len(input) == 0 { | |
return "", errors.New("Input is empty") | |
} | |
result := "" | |
count := 0 | |
for i := 0; i < len(input); i++ { | |
if input[i] >= '0' && input[i] <= '9' { | |
count = count*10 + int(input[i]-'0') | |
} else { | |
for j := 0; j < count; j++ { | |
result += string(input[i]) | |
} | |
count = 0 | |
} | |
} | |
return result, nil | |
} | |
func main() { | |
input := "aaaaaaabbbbccc" | |
encoded, err := rleEncode(input) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Println(encoded) | |
decoded, err := rleDecode(encoded) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Println(decoded) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment