AoC-2022-Nix/2/solution.nix
2022-12-03 23:52:29 -07:00

35 lines
946 B
Nix

with import ../util.nix;
let
# read file
input = readFile ./input;
matches = map (line: convertMvId (splitString " " line)) (splitString "\n" input);
# convert moves to numbers for opponent and player
# Rock -> 0, Paper -> 1, Scissors 2
mvId = c: m: (charToInt m) - (charToInt c);
convertMvId = split (a: b: [(mvId "A" a) (mvId "X" b)] );
# scoring matches
isWin = a: b: (mod (a+1) 3) == b;
isTie = a: b: a == b;
getScore = a: b:
b + 1 + # add score for the move itself
(if isWin a b then 6
else if isTie a b then 3
else 0); # loss
totalScore = m: sum (map (split getScore) m);
# part 2
mkDraw = a: a;
mkWin = a: (mod (a+1) 3);
mkLoss = a: (mod (a+2) 3);
bestMove = a: b:
if b == 0 then mkLoss a
else if b == 1 then mkDraw a
else mkWin a;
makeBestMoves = map (split (a: b: [a (bestMove a b)] ));
in {
part1 = totalScore matches;
part2 = totalScore (makeBestMoves matches);
}