Mercurial > repos > other > adventofcode2023
view day5b.rb @ 21:46fb65f2cb94
Add Day 14 part 1 implementation
If you look at columns and see "how far can this go" then the
weight is just the sum of the partial triangle numbers of
highest_weight to highest_weight minus number of rocks that
can roll up to there.
Part 2 seems to involve actually moving the rocks, though!
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Sat, 16 Dec 2023 10:29:36 +0000 |
parents | 5c8d2d181b94 |
children |
line wrap: on
line source
#! /usr/bin/env ruby require 'set' if ARGV.length != 1 abort("Incorrect arguments - needs input file") elsif not File.exist? (ARGV[0]) abort("File #{ARGV[0]} did not exist") end file = ARGV[0] maps = Hash.new lines = File.open(file, "r").each_line(chomp: true) seeds = lines.first.split(":")[1].split(" ").map(&:to_i).each_slice(2).map {|v| v[0]...(v[0]+v[1])} RawMapping = Struct.new(:from, :to, :ranges) MappingRange = Struct.new(:source_range, :offset) mappings = Array.new mappings_array = [] lines.drop(1).reduce(mappings_array) do |mappings, val| if m = /([a-z]+)-to-([a-z]+) map:/.match(val) then mappings << RawMapping.new(m[1], m[2], []) elsif val != "" then dest_start, source_start, range_length = val.split(" ").map(&:to_i) mappings[-1].ranges << MappingRange.new((source_start...(source_start + range_length)), dest_start - source_start) end mappings end mappings = mappings_array.map {|mapping| [mapping.from, mapping]}.to_h def map_with_override(mappings, inputs) inputs.flat_map do |input| processed = [] reduced_unprocessed = mappings.ranges.reduce(input) do |input_range, mapping| if input_range.nil? nil elsif mapping.source_range.end <= input_range.begin or input_range.end <= mapping.source_range.begin # Input is entirely outside the mapped range input_range elsif mapping.source_range.cover?(input_range) # Input is inside the mapped range processed << ((input_range.begin+mapping.offset)...(input_range.end+mapping.offset)) nil elsif input_range.begin < mapping.source_range.begin # Input straddles the start processed << ((mapping.source_range.begin+mapping.offset)...(input_range.end+mapping.offset)) (input_range.begin)...(mapping.source_range.begin) else # Must straddle the end processed << ((input_range.begin+mapping.offset)...(mapping.source_range.end+mapping.offset)) (mapping.source_range.end)...(input_range.end) end end if ! reduced_unprocessed.nil? processed << reduced_unprocessed end processed end end steps = ["seed", "soil", "fertilizer", "water", "light", "temperature", "humidity"] # FIXME: Some negative values and 0s, and the final `min()` gets a nill value converted_ranges = steps.reduce(seeds) {|vals, map_name| map_with_override(mappings[map_name], vals)} puts converted_ranges.map{|v| v.min}.min