Mercurial > repos > other > adventofcode2023
comparison day7.rb @ 9:9ec95ff0d33d
Add Day 7 solutions with string sorting
Each hand gets a score based on the ranking, then concats the
card values to get a sortable string for ranking
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Thu, 07 Dec 2023 21:06:48 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
8:51e5f26dc81e | 9:9ec95ff0d33d |
---|---|
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 | |
13 Hand = Struct.new(:cards, :score, :bid) | |
14 | |
15 $card_scoring = ("1".."9").to_a.concat(["T", "J", "Q", "K", "A"]) | |
16 | |
17 FULL_HOUSE = Set.new([2,3]) | |
18 TWO_PAIR = {2 => 2, 1 => 1} | |
19 | |
20 def score_hand(cards) | |
21 card_vals = cards.each_char.map {|c| $card_scoring.index(c)} | |
22 card_counts = card_vals.group_by{|v| v}.map {|k, v| v.length} | |
23 card_count_counts = card_counts.group_by{|v| v}.map{|k,v| [k, v.length]}.to_h | |
24 of_a_kind = card_counts.max | |
25 rank = of_a_kind * 2 # 5, 4 or 3 of a kind or a pair => 10, 8, 6 and 4 | |
26 if Set.new(card_counts) == FULL_HOUSE | |
27 rank = 7 | |
28 elsif card_count_counts == TWO_PAIR | |
29 rank = 5 | |
30 end | |
31 card_vals.reduce("#{rank-1}") {|str, v| "#{str}.#{(v+1).to_s.rjust(2, '0')}"} | |
32 end | |
33 | |
34 hands = File.open(file, "r").each_line(chomp: true).map {|line| cards, bid = line.split(" "); Hand.new(cards, score_hand(cards), bid.to_i)} | |
35 | |
36 puts hands.sort {|a, b| a.score <=> b.score}.map.with_index(1) {|val, i| i * val.bid}.sum | |
37 # Rest of algorithm here |