From a1264d825b6a28a8620a1ee67564bfa0483594dc Mon Sep 17 00:00:00 2001 From: David Ashby Date: Fri, 3 Dec 2021 18:53:09 -0500 Subject: [PATCH] day 3 part 2 finally done, ugly though --- 03/main.go | 52 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 49 insertions(+), 3 deletions(-) diff --git a/03/main.go b/03/main.go index 92b328b..e183b42 100644 --- a/03/main.go +++ b/03/main.go @@ -3,7 +3,6 @@ package main import ( "bufio" "fmt" - "math/bits" "os" "strconv" "time" @@ -39,7 +38,7 @@ func partOne() { line := scanner.Text() lines++ n, _ := strconv.ParseInt(line, 2, 64) - for i := 0; i < bits.Len(uint(n)); i++ { + for i := 0; i < len(line); i++ { // check if the number in the i'th column is 1, then bit-shift back to the 1s place to add it if it is r[i] += (n & (1 << i)) >> i } @@ -60,7 +59,54 @@ func partOne() { func partTwo() { scanner := makeScanner(false) + var lines int + inputs := map[int]int64{} + var oxgen, co2scrub int64 + + var totalOnes, bitlen int64 for scanner.Scan() { - // line := scanner.Text() + line := scanner.Text() + n, _ := strconv.ParseInt(line, 2, 64) + inputs[lines] = n + bitlen = int64(len(line)) - 1 + totalOnes += n >> (bitlen) + lines++ } + // make initial check + if totalOnes >= int64(lines)/2 { + oxgen += (1 << bitlen) + } else { + co2scrub += (1 << bitlen) + } + + for i := bitlen; i > 0; i-- { + var oxOnes, oxZeroes, coOnes, coZeroes int64 + for _, n := range inputs { + if oxgen>>i == n>>i { + if oxgen>>(i-1)^n>>(i-1) == 1 { + oxOnes++ + } else { + oxZeroes++ + } + } + if co2scrub>>i == n>>i { + if co2scrub>>(i-1)^n>>(i-1) == 1 { + coOnes++ + } else { + coZeroes++ + } + } + } + if oxOnes >= oxZeroes { + oxgen += (1 << (i - 1)) + } + if coZeroes == 0 && coOnes != 0 { + co2scrub += (1 << (i - 1)) + } else if coZeroes != 0 && coOnes == 0 { + co2scrub += (0 << (i - 1)) + } else if coOnes < coZeroes { + co2scrub += (1 << (i - 1)) + } + } + fmt.Println(oxgen * co2scrub) }