Last active
December 1, 2017 22:01
-
-
Save lilactown/e3bd750f7149981a42574efaf9f4413d to your computer and use it in GitHub Desktop.
Advent of Code, 2017 Day 1 (2/2)
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
let explode = (input) => | |
Js.String.split("", input) | |
|> Array.map(int_of_string) | |
|> Array.to_list; | |
let solve = (input) => { | |
let len = String.length(input); | |
let step = len / 2; | |
let listInput = explode(input); | |
let nth = List.nth(listInput); | |
let rec solver = (currentPos, total) => { | |
let current = nth(currentPos); | |
let halfwayPos = (currentPos + step) mod len; | |
let halfway = nth(halfwayPos); | |
switch (current == halfway, currentPos == len - 1) { | |
| (false, true) => total /* current doesn't equal halfway, end of list */ | |
| (true, true) => total + current /* current does equal halfway */ | |
| (false, false) => solver(currentPos + 1, total) /* doesn't equal halfway, and not the end */ | |
| (true, false) => solver(currentPos + 1, total + current) /* does equal halfway, not the end */ | |
} | |
}; | |
solver(0, 0) | |
}; | |
/* | |
// Solution re-written in JS; won't work for big numbers D: | |
const explode = | |
(input) => input.split("").map((s) => parseInt(s, 10)); | |
const solve = (input) { | |
const len = input.length; | |
const step = len / 2; | |
const listInput = explode(input); | |
const nth = (n) => listInput[n]; | |
const solver = (currentPos, total) => { | |
let current = nth(currentPos); | |
let halfwayPos = (currentPos + step) % len; | |
let halfway = nth(halfwayPos); | |
if (current === halfway && currentPos === len - 1) { | |
return total + current; | |
} else if(currentPos === len - 1) { | |
return total; | |
} else if(current === halfway) { | |
return solver(current + 1, total + current); | |
} else { | |
return solver(current + 1, total); | |
} | |
}; | |
solver(0, 0); | |
}; | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment