Mercurial > repos > other > adventofcode2023
comparison day4b.rb @ 3:9da7a71b313d
Implement scratchcard counting for Day 4
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Mon, 04 Dec 2023 20:36:42 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
2:0f4991eca11a | 3:9da7a71b313d |
---|---|
1 #! /usr/bin/env ruby | |
2 | |
3 require 'set' | |
4 | |
5 if ARGV.length != 1 | |
6 abort("Incorrect arguments - needs input file") | |
7 elsif not File.exist? (ARGV[0]) | |
8 abort("File #{ARGV[0]} did not exist") | |
9 end | |
10 | |
11 file = ARGV[0] | |
12 # Ruby arrays auto-magically grow when you set any index! | |
13 card_counts = Array.new | |
14 | |
15 def add(array, index, value) | |
16 array[index].nil? ? value : array[index] + value | |
17 end | |
18 | |
19 sum = 0 | |
20 File.open(file, "r").each_line(chomp: true).with_index do |line, index| | |
21 card_counts[index] = add(card_counts, index, 1) | |
22 card_count = card_counts[index] | |
23 winning_number_str, our_number_str = line.split(":")[1].split("|").map(&:chomp) | |
24 winning_numbers = Set.new(winning_number_str.split(" ").map(&:to_i)) | |
25 our_numbers = Set.new(our_number_str.split(" ").map(&:to_i)) | |
26 our_winning_numbers = winning_numbers & our_numbers | |
27 if our_winning_numbers.length > 0 | |
28 # puts "Increase #{index + 1} to #{index + our_winning_numbers.length} by #{card_count}" | |
29 # puts (1..our_winning_numbers.length) | |
30 (1..our_winning_numbers.length).each {|v| card_counts[index + v] = add(card_counts, index + v, card_count)} | |
31 end | |
32 end | |
33 | |
34 #puts card_counts | |
35 puts card_counts.sum | |
36 puts sum |