RosettaCodeData/Task/Move-to-front-algorithm/Go/move-to-front-algorithm.go

45 lines
788 B
Go
Raw Permalink Normal View History

2015-02-20 09:02:09 -05:00
package main
import (
2016-12-05 22:15:40 +01:00
"bytes"
"fmt"
2015-02-20 09:02:09 -05:00
)
2016-12-05 22:15:40 +01:00
type symbolTable string
2015-02-20 09:02:09 -05:00
2016-12-05 22:15:40 +01:00
func (symbols symbolTable) encode(s string) []byte {
seq := make([]byte, len(s))
pad := []byte(symbols)
2018-06-22 20:57:24 +00:00
for i, c := range []byte(s) {
x := bytes.IndexByte(pad, c)
seq[i] = byte(x)
2016-12-05 22:15:40 +01:00
copy(pad[1:], pad[:x])
pad[0] = c
}
return seq
2015-02-20 09:02:09 -05:00
}
2016-12-05 22:15:40 +01:00
func (symbols symbolTable) decode(seq []byte) string {
chars := make([]byte, len(seq))
pad := []byte(symbols)
for i, x := range seq {
c := pad[x]
chars[i] = c
copy(pad[1:], pad[:x])
pad[0] = c
}
return string(chars)
2015-02-20 09:02:09 -05:00
}
func main() {
2016-12-05 22:15:40 +01:00
m := symbolTable("abcdefghijklmnopqrstuvwxyz")
for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} {
enc := m.encode(s)
dec := m.decode(enc)
fmt.Println(s, enc, dec)
if dec != s {
panic("Whoops!")
}
}
2015-02-20 09:02:09 -05:00
}