Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions day3/day3.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,60 @@ function mostCommon(arr, bitIndex) {
return -1
}

function reduceTargetBit(data, index, targetBit) {
return data.reduce((matchingVals, current) => {
if (Number.parseInt(current[index]) === targetBit) {
matchingVals.push(current)
}
return matchingVals
}, [])
}

function flipAbit(bit) {
return bit === 0 ? 1 : 0
}

function oxygenGeneratorRating(data, index = 0) {
const result = mostCommon(data, index)
const commonBit = result === -1 ? 1 : result

if (data.length === 1) {
return binaryStringToBase10(data[0])
}

const arr = reduceTargetBit(data, index, commonBit)

return oxygenGeneratorRating(arr, ++index)
}

function co2scrubberRating(data, index = 0) {
const result = mostCommon(data, index)
const leastCommonBit = result === -1 ? 0 : flipAbit(result)

if (data.length === 1) {
return binaryStringToBase10(data[0])
}

const arr = reduceTargetBit(data, index, leastCommonBit)

return co2scrubberRating(arr, ++index)
}

function part2solution() {
const data = parse(diagnostics)
const oxyRating = oxygenGeneratorRating(data)
const co2Rating = co2scrubberRating(data)
return oxyRating * co2Rating
}

export {
parse,
calcGammaBits,
flipBits,
binaryStringToBase10,
part1solution,
mostCommon,
oxygenGeneratorRating,
co2scrubberRating,
part2solution,
}
45 changes: 45 additions & 0 deletions day3/day3.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import {
binaryStringToBase10,
part1solution,
mostCommon,
oxygenGeneratorRating,
co2scrubberRating,
part2solution,
} from './day3.js'

describe('parse data', () => {
Expand Down Expand Up @@ -129,3 +132,45 @@ describe('Part 2 - mostCommon', () => {
expect(mostCommon(parse(exampleData), 0)).toEqual(0)
})
})

describe('Part 2 - oxygenGeneratorRating', () => {
test('with example data', () => {
const exampleData = `00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010`
expect(oxygenGeneratorRating(parse(exampleData))).toEqual(23)
})
})

describe('Part 2 - co2scrubberRating', () => {
test('with example data', () => {
const exampleData = `00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010`
expect(co2scrubberRating(parse(exampleData))).toEqual(10)
})
})

describe('Part 2 - final solution', () => {
test('with solution data', () => {
expect(part2solution()).toEqual(6677951)
})
})