-
Notifications
You must be signed in to change notification settings - Fork 1
/
day_2.lua
101 lines (84 loc) · 2.41 KB
/
day_2.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
local eio = require "libs.eio"
local profile = require "libs.profile"
local sequence = require "libs.sequence"
local input = eio.lines()
local printf = eio.printf
local match = string.match
local dual = sequence.dual
profile.start()
local Shape = {
Rock = 1,
Paper = 2,
Scissors = 3
}
local shapeFromOpponentChar = {
["A"] = Shape.Rock,
["B"] = Shape.Paper,
["C"] = Shape.Scissors
}
local shapeFromPlayerChar = {
["X"] = Shape.Rock,
["Y"] = Shape.Paper,
["Z"] = Shape.Scissors
}
local Outcome = {
Loss = 1,
Draw = 2,
Win = 3
}
local scoreFromShape = {
[Shape.Rock] = 1,
[Shape.Paper] = 2,
[Shape.Scissors] = 3,
}
local scoreFromOutcome = {
[Outcome.Loss] = 0,
[Outcome.Draw] = 3,
[Outcome.Win] = 6
}
local losingShapeAgainst = {
[Shape.Rock] = Shape.Scissors,
[Shape.Paper] = Shape.Rock,
[Shape.Scissors] = Shape.Paper,
}
local function roundOutcome (opponentShape, playerShape)
if opponentShape == playerShape then
return Outcome.Draw
elseif losingShapeAgainst[opponentShape] == playerShape then
return Outcome.Loss
else
return Outcome.Win
end
end
local function score (opponentShape, playerShape)
return scoreFromShape[playerShape] + scoreFromOutcome[roundOutcome(opponentShape, playerShape)]
end
local desiredOutcomeFromChar = {
["X"] = Outcome.Loss,
["Y"] = Outcome.Draw,
["Z"] = Outcome.Win
}
local winningShapeAgainst = dual(losingShapeAgainst)
local function shapeForOutcome (opponentShape, desiredOutcome)
if desiredOutcome == Outcome.Draw then
return opponentShape
elseif desiredOutcome == Outcome.Loss then
return losingShapeAgainst[opponentShape]
else
return winningShapeAgainst[opponentShape]
end
end
local totalScore = 0
local correctTotalScore = 0
for i = 1, #input do
local opponentChar, char = match(input[i], "(%u) (%u)")
local opponentShape = shapeFromOpponentChar[opponentChar]
local playerShape = shapeFromPlayerChar[char]
local desiredOutcome = desiredOutcomeFromChar[char]
local correctPlayerShape = shapeForOutcome(opponentShape, desiredOutcome)
totalScore = totalScore + score(opponentShape, playerShape)
correctTotalScore = correctTotalScore + score(opponentShape, correctPlayerShape)
end
printf("Part 1: %i\n", totalScore)
printf("Part 2: %i\n", correctTotalScore)
return totalScore, correctTotalScore, profile.finish()