From c7f01066164817bbf624f2e7a63c6ac0aeea5f61 Mon Sep 17 00:00:00 2001 From: Oscar Najera Date: Thu, 26 Jan 2023 22:09:57 +0100 Subject: Learning some julia --- AoC2022/02/solver.jl | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 AoC2022/02/solver.jl (limited to 'AoC2022/02/solver.jl') 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 -- cgit v1.2.3