הי,
קישור לחידה המקורית:
https://adventofcode.com/2018/day/2
פיתרון שלי בשפת רובי:
class String
def count
Hash.new(0).tap { |h| self.each_char { |word| h[word] += 1 } }
end
def icount
counts = self.count
each_char.group_by {|c| counts[c]}
end
def common(other)
return 0 if other == self
return length if other.length != self.length
self.each_char.each_with_index.map {|char, index| char == other[index] ? char : '' }.join
end
end
## Part 1
twos = 0
threes = 0
ARGF.each_line.map(&:strip).map(&:icount).each do |counts|
twos += 1 if counts.key?(2)
threes += 1 if counts.key?(3)
end
puts twos, threes, twos * threes
## Part 2
puts ARGF
.each_line
.map(&:strip)
.to_a
.combination(2)
.map {|pair| pair[0].common(pair[1])}
.select {|word| word.length == 25}
.first