So this was a pain. I also ended up with a double loop (O(n2)) and couldn't think of anything better.
One thing I discovered during part two was that Crystal has Levenshtein distance as part of the standard library. It might have been a bit heavy going for what I needed, but it did the trick!
require"levenshtein"classFabricBoxgetterid@letter_map:Hash(String,Int32)definitialize(@id:String)@letter_map=@id.split("").reduce(Hash(String,Int32).new(default_value: 0))do|acc,letter|acc[letter]=acc[letter]+1accendenddefhas_exactly?(letters:Int32):Bool@letter_map.values.any?{|count|count==letters}endendclassFabricBoxCollectiongetterboxes@boxes:Array(FabricBox)definitialize(ids:Array(String))@boxes=ids.map{|id|FabricBox.new(id)}enddefchecksum@boxes.count{|box|box.has_exactly?2}*@boxes.count{|box|box.has_exactly?3}enddeffind_close_id@boxes.eachdo|box_i|@boxes.eachdo|box_j|ifLevenshtein.distance(box_i.id,box_j.id)==1characters_i=box_i.id.split("")characters_j=box_j.id.split("")char_pairs=characters_i.zip(characters_j)returnchar_pairs.reduce("")do|acc,(char_i,char_j)|acc+=char_iifchar_i==char_jaccendendendendendendputs"--- Day 2: Inventory Management System ---"input=File.read_lines("./02/input.txt")collection=FabricBoxCollection.new(input)puts"Checksum: #{collection.checksum}"puts"Common letters: #{collection.find_close_id}"
Ryan is an engineer in the Sacramento Area with a focus in Python, Ruby, and Rust. Bash/Python Exercism mentor. Coding, physics, calculus, music, woodworking. Looking for work!
So this was a pain. I also ended up with a double loop (O(n2)) and couldn't think of anything better.
One thing I discovered during part two was that Crystal has Levenshtein distance as part of the standard library. It might have been a bit heavy going for what I needed, but it did the trick!
Bring on day 3!
High five for a beefy standard library! Thatβs awesome π