Skip to content

Commit

Permalink
feat(2021-day-05): support charting diagonal lines on vent map
Browse files Browse the repository at this point in the history
  • Loading branch information
amclin committed Dec 14, 2021
1 parent 50f064d commit 6adb95e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
13 changes: 12 additions & 1 deletion 2021/day-05/vents.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
* @param {*} y2 end of line vertical point
* @returns
*/
const chartLine = (data, x1, y1, x2, y2) => {
const chartLine = (data, x1, y1, x2, y2, allowDiaganol = false) => {
let x = x1
let y = y1
if (y1 === y2) {
Expand All @@ -28,6 +28,17 @@ const chartLine = (data, x1, y1, x2, y2) => {
y += yDir
}
data[y][x]++ // coordinates are inclusive
} else if (allowDiaganol) {
// chart diagonal line
console.debug(`Drawing diagonal line ${x1},${y1} to ${x2},${y2}`)
const xDir = (x2 > x1) ? 1 : -1
const yDir = (y2 > y1) ? 1 : -1
while (x !== x2 && y !== y2) {
data[y][x]++
x += xDir
y += yDir
}
data[y][x]++ // coordinates are inclusive
} else {
console.debug(`Skipping diagonal line ${x1},${y1} to ${x2},${y2}`)
}
Expand Down
26 changes: 26 additions & 0 deletions 2021/day-05/vents.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,17 @@ const sampleMap = `.......1..
..........
222111....`

const sampleDiagonalMap = `1.1....11.
.111...2..
..2.1.111.
...1.2.2..
.112313211
...1.2....
..1...1...
.1.....1..
1.......1.
222111....`

const parsedTestData = parseLines(testData)

describe('--- Day 5: Hydrothermal Venture ---', () => {
Expand Down Expand Up @@ -84,4 +95,19 @@ describe('--- Day 5: Hydrothermal Venture ---', () => {
})
})
})
describe('Part 2', () => {
describe('chartLine()', () => {
it('includes diagonal lines when specified', () => {
// 10x10 empty grid
let data = [...new Array(10)].map(() => {
return [...new Array(10)].map(() => 0)
})
// Map some lines
parsedTestData.forEach((row) => {
data = chartLine(data, ...row, true)
})
expect(render(data)).to.equal(sampleDiagonalMap)
})
})
})
})

0 comments on commit 6adb95e

Please sign in to comment.