Permutations in ruby where order doesn't matter
(Thursday, May 12, 2011, at 12:32 PM)
Right now, I’m working on some code to pull out the similar users following the following accounts on twitter: [“justinbieber”, “nytimes”, “scobleizer”, “theeconomist”]
Basically, I want to know the similar users following each of these users, which means I would need to have combinations of all the accounts – which could probably be a function rather than me hardcoding all the unions of these accounts. I don’t want to see the ones where its just length one (I don’t care about the nytimes’ users alone, I just care about nytime’s and justinbieber’s similar followers, basically creating a huge four-way venn diagram). So, I wrote up a simple method for it – a programmer just knows when they hit an age-old COMPUTER SCIENCE type function that they need to right – deceptively hard. So, here you go so no one else has this question:
def all_combinations(array)
permutations = []
array.length.downto(2) do |length|
array.permutation(length).each do |perm|
permutations << perm.sort if !permutations.include?(perm.sort)
end
end
return permutations
end
This produces the following set of arrays:
[
["justinbieber", "nytimes", "scobleizer", "theeconomist"],
["nytimes", "scobleizer", "theeconomist"],
["justinbieber", "scobleizer", "theeconomist"],
["justinbieber", "nytimes", "scobleizer"],
["justinbieber", "nytimes", "theeconomist"],
["scobleizer", "theeconomist"],
["nytimes", "scobleizer"],
["justinbieber", "scobleizer"],
["nytimes", "theeconomist"],
["justinbieber", "theeconomist"],
["justinbieber", "nytimes"]
]