Last active
December 5, 2023 19:46
-
-
Save faraazahmad/63dd848de0f096ae5f55069c0b41af35 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require 'parallel' | |
FILE = 'input.txt' | |
# FILE = 'sample.txt' | |
raw_input = File.read(FILE) | |
lines = raw_input.split("\n") | |
seed_num_pairs = [] | |
seed_nums = [] | |
location_nums = [] | |
conversion = {} | |
puts "Generating seed nums..." | |
seed_num_line = lines[0].split(':')[1].split(' ').map(&:to_i) | |
seed_num_line.each_slice(2) do |slice| | |
seed_num_pairs << slice | |
end | |
pp seed_num_pairs | |
def get_location_num(key, num, conversion) | |
return num if key == 'location' | |
source = key | |
dest = conversion[key]['dest'] | |
mapped_num = num | |
# Check if num is in source's source nums | |
source_map_has_num = false | |
conversion[key]['mappings'].each do |nums| | |
source_map_has_num ||= Range.new(nums[1], nums[1]+nums[2]-1).cover?(num) | |
if source_map_has_num | |
# get mapped num | |
diff = num-nums[1] | |
mapped_num = nums[0]+diff | |
break | |
end | |
end | |
get_location_num(dest, mapped_num, conversion) | |
end | |
puts "Generating conversion mappings..." | |
i = 2 | |
while lines[i] | |
if lines[i].include?('map') | |
keys = lines[i].split(' ')[0].split('-to-') | |
source = keys[0] | |
dest = keys[1] | |
i += 1 | |
while lines[i] && lines[i] != '' | |
conversion[source] = { 'mappings' => [] } unless conversion.key?(source) | |
conversion[source]['dest'] = dest | |
conversion[source]['mappings'] << lines[i].split(' ').map(&:to_i) | |
i += 1 | |
end | |
end | |
i += 1 | |
end | |
puts "Calculating minimum location..." | |
min_location = Parallel.map_with_index(seed_num_pairs, in_threads: 4) do |pair, index| | |
min_location = get_location_num('seed', pair[0], conversion) | |
j = 1 | |
while j < pair[1] | |
min_location = [min_location, get_location_num('seed', pair[0]+j, conversion)].min | |
j += 1 | |
puts "Pair #{index+1}; Progress: #{100*j/pair[1]}%" if j % 200_000 == 0 | |
end | |
min_location | |
end.min | |
puts min_location |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment