Jese Leos

Finding Duplicate Charactes in Multiple Arrays with Ruby

We needed to find duplicate characters in multiple arrays for Saturday's Advent of Code.

In the first part of the problem, it was among two arrays, so I did something quick like this:

first_array.select { |char| second_array.include?(char) }

This worked as expected, but in part 2, you needed to perform a similar search across three arrays.

I could have chained a second select or duplicated the line entirely, but I figured there was a more straightforward way...and of course, in Ruby, there is almost always a more straightforward way.

~~I do not have a traditional comp sci background, so my mind rarely jumps to Bitwise operators, but in this case, this is the Bitwise & operator is exactly what we needed.~~

@scott pointed this is not Bitwise when dealing with strings:

It is the unary and operator. On arrays, #& is a method that returns the set union of two arrays. On integers, it is indeed implemented as a bitwise and.

a = "vJrwpWtwJgWrhcsFMMfFFhFp".chars
b = "jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL".chars
c = "PmmdzqPrVvPwwTWBwg".chars

duplicates = a & b & c

Even better, this easily scales across N arrays.