day 16 part 1

This commit is contained in:
RussellChamp committed 2021-12-16 15:54:05 -05:00
1 parent 4737afa383
commit 0c277a8404
11 files changed
+463 -1

No files matched your search

+65
View File
@@ -1,5 +1,7 @@
package bits
import "fmt"
func GetBitCount(val int) int {
count := 0
for val != 0 {
@@ -52,3 +54,66 @@ func BitwiseAndA(a ...int) int {
func ByBitCount(size int) func(int) bool {
return func(val int) bool { return GetBitCount(val) == size }
}
func ToInt(bits []bool) int {
intVal := 0
for idx := 0; idx < len(bits); idx++ {
intVal = intVal << 1
if bits[idx] {
intVal += 1
}
}
return intVal
}
func ToStr(bits []bool) string {
str := ""
for idx := 0; idx < len(bits); idx++ {
if bits[idx] {
str += "1"
} else {
str += "0"
}
}
return str
}
func HexByteToBits(b byte) ([]bool, error) {
// just do this manually because i can't be arsed
switch b {
case byte('0'):
return []bool{false, false, false, false}, nil
case byte('1'):
return []bool{false, false, false, true}, nil
case byte('2'):
return []bool{false, false, true, false}, nil
case byte('3'):
return []bool{false, false, true, true}, nil
case byte('4'):
return []bool{false, true, false, false}, nil
case byte('5'):
return []bool{false, true, false, true}, nil
case byte('6'):
return []bool{false, true, true, false}, nil
case byte('7'):
return []bool{false, true, true, true}, nil
case byte('8'):
return []bool{true, false, false, false}, nil
case byte('9'):
return []bool{true, false, false, true}, nil
case byte('A'):
return []bool{true, false, true, false}, nil
case byte('B'):
return []bool{true, false, true, true}, nil
case byte('C'):
return []bool{true, true, false, false}, nil
case byte('D'):
return []bool{true, true, false, true}, nil
case byte('E'):
return []bool{true, true, true, false}, nil
case byte('F'):
return []bool{true, true, true, true}, nil
default:
return []bool{}, fmt.Errorf("read invalid byte")
}
}
+34
View File
@@ -26,3 +26,37 @@ func TestByBitCount(t *testing.T) {
twoBitFilter := ByBitCount(2)
assert.IsTrue(t, twoBitFilter(17 /*10001*/), "should count bits")
}
func TestHexByteToBits(t *testing.T) {
cases := []struct {
input rune
output string
}{
{'0', "0000"},
{'1', "0001"},
{'2', "0010"},
{'3', "0011"},
{'4', "0100"},
{'5', "0101"},
{'6', "0110"},
{'7', "0111"},
{'8', "1000"},
{'9', "1001"},
{'A', "1010"},
{'B', "1011"},
{'C', "1100"},
{'D', "1101"},
{'E', "1110"},
{'F', "1111"},
}
for _, c := range cases {
bits, err := HexByteToBits(byte(c.input))
if err != nil {
t.Logf("Got error from HexByteToBits: %s", err.Error())
t.Fail()
}
bitStr := ToStr(bits)
assert.EqualsStr(t, bitStr, c.output, "incorrect value")
}
}