DEV Community

Cover image for Advent of code - Day 12
Quentin Ménoret
Quentin Ménoret

Posted on

Advent of code - Day 12

Are you participating in the Advent of code this year?

If you don't know what the advent of code is, it's a website where you'll find a daily challenge (every day it gets harder). It's a really fun event, you should participate!

I try to solve the exercises using either JavaScript or TypeScript and will share my solutions daily (with one day delay so no one can cheat!). I only share the solution for the second part.

Fun exercise today! I panicked a bit with that "angle" thing, but then I realised it was always 90°, which made it pretty straightforward.

Here is my solution for day #12:

const Command = { North: 'N', South: 'S', East: 'E', West: 'W', Left: 'L', Right: 'R', Forward: 'F', } function addTo(state, command, value) { if (command === Command.East) return { ...state, wpx: state.wpx + value } if (command === Command.West) return { ...state, wpx: state.wpx - value } if (command === Command.North) return { ...state, wpy: state.wpy - value } if (command === Command.South) return { ...state, wpy: state.wpy + value } } function rotate(state, command, param) { if (param === 0) return state if (command === Command.Left) return rotate({ ...state, wpy: 0 - state.wpx, wpx: state.wpy }, command, param - 90) if (command === Command.Right) return rotate({ ...state, wpx: 0 - state.wpy, wpy: state.wpx }, command, param - 90) } function execute([command, param], state) { if (command === Command.Forward) return { ...state, x: state.x + param * state.wpx, y: state.y + param * state.wpy } if (command === Command.Right || command === Command.Left) return rotate(state, command, param) return addTo(state, command, param) } const resultState = input.reduce( (state, command) => { return execute(command, state) }, { x: 0, y: 0, wpx: 10, wpy: -1, }, ) 
Enter fullscreen mode Exit fullscreen mode

Feel free to share your solution in the comments!


Photo by Markus Spiske on Unsplash

Top comments (0)