Skip to content

Instantly share code, notes, and snippets.

@gevann
Created June 7, 2022 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gevann/686fecc219e8401010f34595e0e89a03 to your computer and use it in GitHub Desktop.
Save gevann/686fecc219e8401010f34595e0e89a03 to your computer and use it in GitHub Desktop.
func Reduce[T any, R any](arr []T, fn func(acc R, val T) R) R {
var acc R
for _, v := range arr {
acc = fn(acc, v)
}
return acc
}
type Tuple struct {
count int
char byte
}
func (t *Tuple) ToString() string {
return fmt.Sprintf("{ count: %d, char: %c }", t.count, t.char)
}
func Compress(str []byte) string {
compressed := Reduce(str, func(acc []Tuple, val byte) []Tuple {
var last *Tuple
if len(acc) == 0 {
last = &Tuple{}
} else {
last = &acc[len(acc)-1]
}
if last.char == val {
last.count++
} else {
acc = append(acc, Tuple{1, val})
}
return acc
})
if len(compressed) > len(str) {
return string(str)
}
return Reduce(compressed, func(acc string, t Tuple) string {
acc += fmt.Sprintf("%c%d", t.char, t.count)
return acc
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment