Search code examples
rubyhammingweight

How to create a sub array of given array of binary numbers based on number of 1's in Ruby?


Example:

Here is binary numbers array:

a = [001, 010, 100, 011, 101, 110, 111, 1000, 1001, 1010]

I want output like below:

[ [ 001, 010, 100, 1000 ], [ 011, 101, 110, 1001, 1010 ], [ 111 ] ]

Can anybody help me how to achieve it in ruby?


Solution

  • I'm going to assume you're working with strings ("001") and not decimal/octal literals (001). If that's not the case, I strongly suggest casting to strings to make things easier on you.

    We can count the number of ones in a string x with x.count('1'). Then we can take a list of strings and organize it by this value with a.group_by(...). This gives a hash, so if you just want the values (as your suggested output suggests), then you simply take the values of it.

    a.group_by { |x| x.count('1') }.values