Improved commong code

This commit is contained in:
2021-12-04 20:51:14 +01:00
parent ebcee1aa14
commit 625eaf5f73
3 changed files with 54 additions and 101 deletions

View File

@@ -7,11 +7,6 @@ import (
"strconv"
)
func main() {
part1()
part2()
}
func count(entries []string, width int) [2][]int {
counts := [2][]int{make([]int, width), make([]int, width)}
@@ -58,7 +53,7 @@ func process(input *bufio.Scanner) ([]string, int) {
return numbers, width
}
func part1() {
func main() {
aoc := aoc.New(2021, 3)
aoc.Test(`
@@ -74,9 +69,9 @@ func part1() {
11001
00010
01010
`, 198)
`, []int{198, 230})
aoc.Solution(func (input *bufio.Scanner) int {
aoc.Solution(1, func (input *bufio.Scanner) int {
entries, width := process(input)
counts := count(entries, width)
@@ -92,27 +87,8 @@ func part1() {
return gamma * epsilon
})
}
func part2() {
aoc := aoc.New(2021, 3)
aoc.Test(`
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
`, 230)
aoc.Solution(func (input *bufio.Scanner) int {
aoc.Solution(2, func (input *bufio.Scanner) int {
oxygen, width := process(input)
oxygenCounts := count(oxygen, width)

View File

@@ -6,67 +6,6 @@ import (
"strconv"
)
func main() {
part1()
part2()
}
func part1() {
aoc := aoc.New(2021, 3)
aoc.Test(`
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
`, 198)
aoc.Solution(func (input *bufio.Scanner) int {
length := 0
var entries []int
for input.Scan() {
line := input.Text()
if len(line) > length {
length = len(line)
}
num, err := strconv.ParseInt(line, 2, 64)
if err != nil {
panic(err)
}
entries = append(entries, int(num))
}
gamma := 0
epsilon := 0
for j := 0; j < length; j++ {
var count int
for _, num := range entries {
count += num >> j & 1
}
if float64(count)/float64(len(entries)) >= 0.5 {
gamma += 1 << j
} else {
epsilon += 1 << j
}
}
return gamma*epsilon
})
}
func filter(entries []int, length int, findCommon bool) int {
e := make([]int, len(entries))
copy(e, entries)
@@ -105,7 +44,7 @@ func filter(entries []int, length int, findCommon bool) int {
return e[0]
}
func part2() {
func main() {
aoc := aoc.New(2021, 3)
aoc.Test(`
@@ -121,9 +60,46 @@ func part2() {
11001
00010
01010
`, 230)
`, []int{198, 230})
aoc.Solution(func (input *bufio.Scanner) int {
aoc.Solution(1, func (input *bufio.Scanner) int {
length := 0
var entries []int
for input.Scan() {
line := input.Text()
if len(line) > length {
length = len(line)
}
num, err := strconv.ParseInt(line, 2, 64)
if err != nil {
panic(err)
}
entries = append(entries, int(num))
}
gamma := 0
epsilon := 0
for j := 0; j < length; j++ {
var count int
for _, num := range entries {
count += num >> j & 1
}
if float64(count)/float64(len(entries)) >= 0.5 {
gamma += 1 << j
} else {
epsilon += 1 << j
}
}
return gamma*epsilon
})
aoc.Solution(2, func (input *bufio.Scanner) int {
length := 0
var entries []int