aboutsummaryrefslogtreecommitdiffstats
path: root/AoC2022/02/solver.jl
diff options
context:
space:
mode:
authorOscar Najera <hi@oscarnajera.com>2023-01-26 22:09:57 +0100
committerOscar Najera <hi@oscarnajera.com>2023-01-26 22:09:57 +0100
commitc7f01066164817bbf624f2e7a63c6ac0aeea5f61 (patch)
tree8dec4fd44655094ae59ca101672e9ee3ed339f7b /AoC2022/02/solver.jl
parent31aa0839953395f5998c7ec4350760cfebae6506 (diff)
downloadscratch-c7f01066164817bbf624f2e7a63c6ac0aeea5f61.tar.gz
scratch-c7f01066164817bbf624f2e7a63c6ac0aeea5f61.tar.bz2
scratch-c7f01066164817bbf624f2e7a63c6ac0aeea5f61.zip
Learning some julia
Diffstat (limited to 'AoC2022/02/solver.jl')
-rw-r--r--AoC2022/02/solver.jl69
1 files changed, 69 insertions, 0 deletions
diff --git a/AoC2022/02/solver.jl b/AoC2022/02/solver.jl
new file mode 100644
index 0000000..b93a88f
--- /dev/null
+++ b/AoC2022/02/solver.jl
@@ -0,0 +1,69 @@
+using Match
+using Test
+
+plays = open("input") do f
+ split.(eachsplit(read(f, String),"\n", keepempty=false))
+end
+
+translate(play) = @match play begin
+ "A" || "X" => :rock
+ "B" || "Y" => :paper
+ "C" || "Z" => :scissors
+end
+
+weigth(play)= @match play begin
+ :rock => 1
+ :paper => 2
+ :scissors => 3
+end
+
+function trumps(play)
+ @match play begin
+ :rock => :scissors
+ :scissors => :paper
+ :paper => :rock
+ _ => error("Invalid play")
+ end
+end
+
+function looses(play)
+ @match play begin
+ :rock => :paper
+ :scissors => :rock
+ :paper => :scissors
+ _ => error("Invalid play")
+ end
+end
+
+function points(my, other)
+ if trumps(my) == other
+ return 6
+ elseif my == other
+ return 3
+ else
+ return 0
+ end
+end
+
+function fixed_play(oponent, my)
+ oponent_hand = translate(oponent)
+ my_hand = translate(my)
+ points(my_hand, oponent_hand) + weigth(my_hand)
+end
+
+function reactive_play(oponent, my)
+ oponent_hand = translate(oponent)
+ my_hand = @match my begin
+ "X" => trumps(oponent_hand) # I loose
+ "Y" => oponent_hand
+ "Z" => looses(oponent_hand) # I win
+ _ => error("Invalid input")
+ end
+ points(my_hand, oponent_hand) + weigth(my_hand)
+end
+
+
+@testset "solutions" begin
+ @test map(((op, my),) -> fixed_play(op,my), plays) |> sum == 12535
+ @test map(((op, my),) -> reactive_play(op,my), plays) |> sum == 15457
+end