Skip to content

Instantly share code, notes, and snippets.

@lilactown
Created December 2, 2017 21:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lilactown/c0b7ffbd7c843adb52b64e77efd7e650 to your computer and use it in GitHub Desktop.
Save lilactown/c0b7ffbd7c843adb52b64e77efd7e650 to your computer and use it in GitHub Desktop.
Advent of Code, 2017, Day Two
let splitLines = (input) => Js.String.split("\n", input) |> Array.to_list;
let splitDigits = (line) =>
Js.String.split("\t", line) |> Array.map(int_of_string) |> Array.to_list;
let debug = (input) => {
Js.log(input);
input
};
let minMax = ((x: int, y: int), z) =>
switch (z > x, z < y) {
| (true, _) => (z, y)
| (_, true) => (x, z)
| _ => (x, y)
};
let lineMinMax = (line) =>
switch line {
| [] => raise(Failure("Empty line"))
| [hd, ...tail] => List.fold_left(minMax, (hd, hd), tail)
};
let part1 = (input) =>
List.(
splitLines(input)
|> map(splitDigits)
|> map(lineMinMax)
|> fold_left((total, (x, y)) => total + x - y, 0)
);
let rec hasDivisor = (n, digits) =>
switch digits {
| [] => None
| [m, ...rest] =>
switch (n mod m == 0, m mod n == 0) {
| (true, _) => Some((n, m))
| (_, true) => Some((m, n))
| _ => hasDivisor(n, rest)
}
};
let rec divisors = (digits) =>
switch digits {
| [] => raise(Failure("No divisors found"))
| [n, ...rest] =>
switch (hasDivisor(n, rest)) {
| Some(x) => x
| None => divisors(rest)
}
};
let part2 = (input) =>
List.(
splitLines(input)
|> map(splitDigits)
|> map(divisors)
|> fold_left((total, (n, m)) => total + n / m, 0)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment