Created
January 29, 2021 00:12
-
-
Save ezy023/b8ea2464fe61a3af2bf2d9eb2ea6e4b4 to your computer and use it in GitHub Desktop.
Solution to lossless-compression problem
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
func losslessDataCompression(inputString string, width int) string { | |
result := "" | |
var i int = 0 | |
for i < len(inputString) { | |
end := i + 1 | |
var begin int | |
if i < width { | |
begin = 0 | |
} else { | |
begin = i - width | |
} | |
window := inputString[begin:end] | |
var length int | |
outer: | |
for length = len(window); length > 0; length-- { | |
for j := 0; j < len(window)-length; j++ { | |
if i+length <= len(inputString) && inputString[i:i+length] == window[j:j+length] { | |
startIndex := i - len(window) + j + 1 | |
pair := fmt.Sprintf("(%d,%d)", startIndex, length) | |
i += length | |
result += pair | |
break outer | |
} | |
} | |
} | |
if length == 0 { | |
result += string(inputString[i]) | |
i++ | |
} | |
} | |
return result | |
} |
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 ( | |
"testing" | |
) | |
func TestLosslessComp(t *testing.T) { | |
cases := []struct { | |
input, expected string | |
width int | |
}{ | |
{ | |
input: "abacabadabacaba", | |
expected: "ab(0,1)c(0,3)d(4,3)c(8,3)", | |
width: 7, | |
}, | |
{ | |
input: "abacabadabacaba", | |
expected: "ab(0,1)c(0,3)d(0,7)", | |
width: 8, | |
}, | |
{ | |
input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaa", | |
expected: "a(0,1)(0,2)(0,4)(0,8)(4,12)", | |
width: 12, | |
}, | |
} | |
for _, tc := range cases { | |
t.Run("", func(t *testing.T) { | |
got := losslessDataCompression(tc.input, tc.width) | |
if tc.expected != got { | |
t.Errorf("Expected %s, got %s", tc.expected, got) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment