3.rb 706 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. require 'set'
  2. @input = File.read("3.input").split("\n")
  3. def prio(char)
  4. if char.ord >= 'a'.ord then
  5. return char.ord - 'a'.ord + 1
  6. else
  7. return char.ord - 'A'.ord + 27
  8. end
  9. end
  10. def part1()
  11. score = 0
  12. for sack in @input do
  13. left, right = sack.slice(0, sack.length / 2), sack.slice(sack.length / 2, sack.length)
  14. right.each_char do |char|
  15. if left.include? char then
  16. score += prio(char)
  17. break
  18. end
  19. end
  20. end
  21. puts score
  22. end
  23. def part2()
  24. score = 0
  25. @input.each_slice(3) do |group|
  26. sets = group.map {|sack| Set.new(sack.chars)}
  27. result = sets[0] & sets[1] & sets[2]
  28. score += prio(result.to_a[0])
  29. end
  30. puts score
  31. end
  32. part1()
  33. part2()