-
-
Save Mellen/5135944aeb1bfd01f311f576d14f374f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function boatp1() | |
{ | |
let input = document.querySelector('pre').innerHTML.trim().split('\n'); | |
let facing = 'E'; | |
function turn(dir, face, deg) | |
{ | |
let directions = ['E', 'S', 'W', 'N']; | |
let change = deg / 90; | |
let curi = directions.indexOf(face); | |
if(dir == 'L') | |
{ | |
change = change * -1; | |
} | |
curi += change; | |
if(curi < 0) | |
{ | |
curi = directions.length + curi; | |
} | |
else if(curi >= directions.length) | |
{ | |
curi = curi - directions.length; | |
} | |
return directions[curi]; | |
} | |
let [e, n] = input.reduce((out, ins) => | |
{ | |
let [E, N] = out; | |
let [_, dir, amt] = ins.match(/(\w)(\d+)/); | |
if(dir == 'R' || dir == 'L') | |
{ | |
facing = turn(dir, facing, amt); | |
} | |
else | |
{ | |
if(dir == 'F') | |
{ | |
dir = facing; | |
} | |
switch(dir) | |
{ | |
case 'E': | |
E += parseInt(amt, 10); | |
break; | |
case 'W': | |
E -= parseInt(amt, 10); | |
break; | |
case 'N': | |
N += parseInt(amt, 10); | |
break; | |
case 'S': | |
N -= parseInt(amt, 10); | |
break; | |
} | |
} | |
return [E, N]; | |
}, [0,0]); | |
return Math.abs(e) + Math.abs(n); | |
} | |
function boatp2() | |
{ | |
let input = document.querySelector('pre').innerHTML.trim().split('\n'); | |
function turn(wE, wN, dir, amt) | |
{ | |
let times = amt/90; | |
for(let i = 0; i < times; i++) | |
{ | |
if(dir == 'R') | |
{ | |
[wE, wN] = [wN, -1*wE]; | |
} | |
else | |
{ | |
[wE, wN] = [-1*wN, wE]; | |
} | |
} | |
return [wE, wN]; | |
} | |
let [e, n, we, wn] = input.reduce((out, ins) => | |
{ | |
let [E, N, wE, wN] = out; | |
let [_, dir, amt] = ins.match(/(\w)(\d+)/); | |
amt = parseInt(amt, 10); | |
if(dir == 'R' || dir == 'L') | |
{ | |
[wE, wN] = turn(wE, wN, dir, amt); | |
} | |
if(dir == 'F') | |
{ | |
N += wN*amt; | |
E += wE*amt; | |
} | |
else | |
{ | |
switch(dir) | |
{ | |
case 'E': | |
wE += amt; | |
break; | |
case 'S': | |
wN -= amt; | |
break; | |
case 'W': | |
wE -= amt; | |
break; | |
case 'N': | |
wN += amt; | |
break; | |
} | |
} | |
return [E, N, wE, wN]; | |
}, [0,0,10,1]); | |
return Math.abs(e) + Math.abs(n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment