aboutsummaryrefslogtreecommitdiff
path: root/2022/day2.rb
blob: bc4ade59ab18f528e4bc3053a84a3bc5fe18fd65 (plain)
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
TEST_S = <<-EOF
A Y
B X
C Z
EOF

def score(picked_item, outcome)
  fail "Wrong picked item '#{picked_item}'" unless picked_item
  outcome_score = case outcome
                  when :win
                    6
                  when :draw
                    3
                  when :lose
                    0
                  end
  picked_score = case picked_item
                 when /A|X/
                   1
                 when /B|Y/
                   2
                 when /C|Z/
                   3
                 end
  #puts "#{outcome_score} + #{picked_score}"
  return outcome_score + picked_score
end

def guessed_strategy(line)
  outcome_map = {
    'A X' => :draw,
    'A Y' => :win,
    'A Z' => :lose,
    'B X' => :lose,
    'B Y' => :draw,
    'B Z' => :win,
    'C X' => :win,
    'C Y' => :lose,
    'C Z' => :draw
  }
  return outcome_map[line]
end

def correct_strategy(item1, item2)
  return :win if item2 == 'Z'
  return :draw if item2 == 'Y'
  return :lose if item2 == 'X'
end

def what_to_choose(oponent_shape, outcome)
  case outcome
  when :draw
    return oponent_shape
  when :win
    case oponent_shape
    when 'A'
      return 'B'
    when 'B'
      return 'C'
    when 'C'
      return 'A'
    else
      fail "Don't know this shape '#{oponent_shape}'"
    end
  when :lose
    case oponent_shape
    when 'A'
      return 'C'
    when 'B'
      return 'A'
    when 'C'
      return 'B'
    else
      fail "Don't know this shape '#{oponent_shape}'"
    end
  else
    fail "Don't know this outcome '#{outcome}'"
  end
end

def part1(filename)
  score = 0
  File.open(filename) do |f|
    scores = f.readlines.map do |line|
      item1, item2 = line.chomp.split()
      outcome = guessed_strategy(line.chomp)
      score(item2, outcome)
    end

    score = scores.sum
  end
  score
end

def part2(filename)
  score = 0
  File.open(filename) do |f|
    scores = f.readlines.map do |line|
      item1, item2 = line.chomp.split()
      outcome = correct_strategy(item1, item2)
      shape = what_to_choose(item1, outcome)
      score(shape, outcome)
    end

    score = scores.sum
  end
  score
end

#puts part1('./day2-test.txt')
#puts part1('./day2.txt')


puts 'Part2'
puts part2('./day2-test.txt')
puts part2('./day2.txt')