Skip to content

Instantly share code, notes, and snippets.

@Nv7-GitHub
Created December 5, 2021 07:02
Show Gist options
  • Save Nv7-GitHub/d3762ed0286f3fc0257a89e607696e41 to your computer and use it in GitHub Desktop.
Save Nv7-GitHub/d3762ed0286f3fc0257a89e607696e41 to your computer and use it in GitHub Desktop.
Advent of Code 2021 Day 3
package main
import (
_ "embed"
"fmt"
"strconv"
"strings"
)
//go:embed input.txt
var input string
func main() {
lines := strings.Split(input, "\n")
trueCnts := make([]int, len(lines[0]))
falseCnts := make([]int, len(lines[0]))
for _, line := range lines {
for i, char := range line {
if char == '0' {
falseCnts[i]++
} else if char == '1' {
trueCnts[i]++
}
}
}
out1 := ""
out2 := ""
for i := 0; i < len(lines[0]); i++ {
if trueCnts[i] > falseCnts[i] {
out1 += "1"
out2 += "0"
} else {
out1 += "0"
out2 += "1"
}
}
num1, err := strconv.ParseInt(out1, 2, 64)
if err != nil {
panic(err)
}
num2, err := strconv.ParseInt(out2, 2, 64)
if err != nil {
panic(err)
}
fmt.Println(num1 * num2)
}
package main
import (
_ "embed"
"fmt"
"strconv"
"strings"
)
//go:embed input.txt
var input string
func main() {
vals := strings.Split(input, "\n")
var truecnts []int
var falsecnts []int
calcstats := func() {
truecnts = make([]int, len(vals[0]))
falsecnts = make([]int, len(vals[0]))
// Calculate stats
for _, val := range vals {
for i, char := range val {
if char == '0' {
falsecnts[i]++
} else if char == '1' {
truecnts[i]++
}
}
}
}
// Oxygen rating
for i := 0; i < len(vals[0]); i++ {
calcstats()
// Check
newVals := make([]string, 0)
var corrChar byte = ' '
if falsecnts[i] > truecnts[i] {
corrChar = '0'
} else {
corrChar = '1'
}
for _, val := range vals {
if val[i] == corrChar {
newVals = append(newVals, val)
}
}
vals = newVals
if len(vals) == 1 {
break
}
}
oxygenrating := vals[0]
// Co2 scrubber rating
vals = strings.Split(input, "\n")
for i := 0; i < len(vals[0]); i++ {
calcstats()
// Check
newVals := make([]string, 0)
var corrChar byte = ' '
if truecnts[i] < falsecnts[i] {
corrChar = '1'
} else {
corrChar = '0'
}
for _, val := range vals {
if val[i] == corrChar {
newVals = append(newVals, val)
}
}
vals = newVals
if len(vals) == 1 {
break
}
}
corating := vals[0]
orating, err := strconv.ParseInt(oxygenrating, 2, 64)
if err != nil {
panic(err)
}
crating, err := strconv.ParseInt(corating, 2, 64)
if err != nil {
panic(err)
}
fmt.Println(orating * crating)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment