Skip to content

Instantly share code, notes, and snippets.

@ezy023
Created February 11, 2021 03:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ezy023/e607bfe5e2814cc02c8f5f9a3034e2c1 to your computer and use it in GitHub Desktop.
Save ezy023/e607bfe5e2814cc02c8f5f9a3034e2c1 to your computer and use it in GitHub Desktop.
package main
func packetDescrambler(seq []int, fragmentData []string, n int) string {
maxSeqIdx := func(numSlice []int) int {
max := numSlice[0]
for _, n := range numSlice[1:] {
if n > max {
max = n
}
}
return max
}(seq)
idxToChars := make(map[int]map[string]int, maxSeqIdx+1) // +1 since we found the max "index"
for idx, char := range fragmentData {
if entry, ok := idxToChars[seq[idx]]; !ok {
m := make(map[string]int, 0)
m[char] = 1
idxToChars[seq[idx]] = m
} else {
if _, ok := entry[char]; !ok {
entry[char] = 1
} else {
entry[char]++
}
}
}
if len(idxToChars) < maxSeqIdx+1 {
return ""
}
output := make([]byte, maxSeqIdx+1)
for seqIdx, charMap := range idxToChars {
if charMap == nil {
return ""
}
for char, count := range charMap {
if count > n/2 {
if seqIdx == maxSeqIdx && char != "#" {
return ""
} else if seqIdx < maxSeqIdx && char == "#" {
return ""
} else {
output[seqIdx] = []byte(char)[0]
}
}
}
if output[seqIdx] == 0 {
return ""
}
}
return string(output)
}
package main
import "testing"
func TestPacketDescrambler(t *testing.T) {
cases := []struct {
name string
seq []int
data []string
n int
expected string
}{
{
name: "problem example",
seq: []int{1, 1, 0, 0, 0, 2, 2, 2},
data: []string{"+", "+", "A", "A", "B", "#", "#", "#"},
n: 3,
expected: "A+#",
},
{
name: "test one",
seq: []int{1, 1, 0, 0, 0, 2, 2, 2},
data: []string{"+", "+", "A", "A", "B", "#", "#", "#"},
n: 4,
expected: "",
},
{
name: "test two",
seq: []int{1, 1, 2, 2, 2, 0, 0, 0},
data: []string{"+", "+", "A", "A", "B", "#", "#", "#"},
n: 3,
expected: "",
},
{
name: "test three",
seq: []int{0, 0},
data: []string{"#", "#"},
n: 3,
expected: "#",
},
{
name: "test four",
seq: []int{1, 1, 2, 2, 2, 0, 0, 0, 4, 4},
data: []string{"+",
"+",
"A",
"A",
"B",
"#",
"#",
"#",
"#",
"#"},
n: 3,
expected: "",
},
{
name: "test six",
seq: []int{1, 1, 2, 2, 2, 4, 4},
data: []string{"+",
"+",
"A",
"A",
"B",
"#",
"#"},
n: 3,
expected: "",
},
{
name: "test nine",
seq: []int{0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3},
data: []string{"#",
"?",
"?",
"?",
"?",
"?",
"?",
"?",
"#",
"?",
"#",
"#"},
n: 3,
expected: "???#",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
result := packetDescrambler(tc.seq, tc.data, tc.n)
if tc.expected != result {
t.Errorf("Wanted %v, got %v", tc.expected, result)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment