On Day 6 we are working with columns of text. We have a bunch of strings in the input file and we need to calculate the most common character in each column. Each character is considered as a separate column.
Here is the solution:
data = File.readlines("6.txt", chomp: true)
columns = []
data[0].size.times { columns.push({ "max" => 0, "char" => nil }) }
data.each do |row|
row.chars.each_with_index do |char, column|
columns[column][char] ||= 0
columns[column][char] += 1
if columns[column][char] > columns[column]["max"]
columns[column]["max"] = columns[column][char]
columns[column]["char"] = char
end
end
end
message = columns.map { |column| column["char"] }.join
puts message
Second part is the least common character in each column:
data = File.readlines("6.txt", chomp: true)
columns = []
data[0].size.times { columns.push({}) }
data.each do |row|
row.chars.each_with_index do |char, column|
columns[column][char] ||= 0
columns[column][char] += 1
end
end
message = columns.map do |column|
min = Float::INFINITY
final_char = nil
column.each do |char, value|
if value < min
min = value
final_char = char
end
end
final_char
end
puts message.join