Skip to content

Instantly share code, notes, and snippets.

@wefarrell
Last active June 21, 2016 00:37
Show Gist options
  • Save wefarrell/1bb1c1e39dd6e704811ad2a3cceadf87 to your computer and use it in GitHub Desktop.
Save wefarrell/1bb1c1e39dd6e704811ad2a3cceadf87 to your computer and use it in GitHub Desktop.
expect = require('chai').expect
_ = require('lodash')
housesDeliveredGrid = (commands) ->
grid = {0:{0:1}}
currentX = 0
currentY = 0
for command in commands
switch
when command is '>'
currentX += 1
when command is '^'
currentY += 1
when command is '<'
currentX -= 1
when command is 'v'
currentY -= 1
grid[currentY.toString()] ||= {}
grid[currentY.toString()][currentX.toString()] = 1
return grid
gridCount = (grid) ->
_(grid).values().flatten().values().map(_.values).flatten().sum()
housesDeliveredGridCount = (commands) ->
gridCount(housesDeliveredGrid(commands))
combineGrids = (grid1, grid2) ->
for yPos, rows of grid1
grid2[yPos] ||= {}
for xPos, v of rows
grid2[yPos][xPos] = 1
return grid2
cyborgHousesDelivered = (input) ->
isOdd = (v, n) -> n %2 is 0
isEven = (v, n) -> n %2 is 1
santaCommands = _.filter(input, isOdd)
roboCommands = _.filter(input, isEven)
santaGrid = housesDeliveredGrid(santaCommands)
roboGrid = housesDeliveredGrid(roboCommands)
compositeGrid = combineGrids(santaGrid, roboGrid)
gridCount(compositeGrid)
case1 = '>'
case2 = '^>v<'
case3 = '^v^v^v^v^v'
describe 'housesDeliveredGridCount()', ->
it 'case1 succeeds', ->
expect(housesDeliveredGridCount(case1)).to.eq(2)
it 'case2 succeeds', ->
expect(housesDeliveredGridCount(case2)).to.eq(4)
it 'case3 succeeds', ->
expect(housesDeliveredGridCount(case3)).to.eq(2)
case4 = '^v'
case5 = '^>v<'
case6 = '^v^v^v^v^v'
input = require('fs').readFileSync('input.txt').toString()
describe 'cyborgHousesDelivered()', ->
it 'case4 succeeds', ->
expect(cyborgHousesDelivered(case4)).to.eq(3)
it 'case5 succeeds', ->
expect(cyborgHousesDelivered(case5)).to.eq(3)
it 'case6 succeeds', ->
expect(cyborgHousesDelivered(case6)).to.eq(11)
#
console.log 'solution:', cyborgHousesDelivered(input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment