El nino
El nino

Reputation: 239

Checking through Array subset

I have a challenge, im trying to write a method that takes in an array and returns the subset and permutation of twos, including the initial array. How do I check for particular patterns in the array. For example, given this array:

[a,b,c]

subset return will be:

[a,b,c,], [a,b], [b,c], [c,a]

and I also need to check if each subset contains a particular letter. Here's my code:

def conflict_free?(a)
  return a.permutation(2).to_a
end

Upvotes: 0

Views: 251

Answers (2)

Kassym Dorsel
Kassym Dorsel

Reputation: 4843

Here is a very compact and fast solution :

def conflict(a)
  a.combination(2).to_a << a
end

>> [["a", "b"], ["a", "c"], ["b", "c"], ["a", "b", "c"]]

If you did want the initial array at the beginning you sacrificing a fair bit of speed. Nevertheless the best way to do it :

def conflict(a)
  temp = [a]
  a.combination(2).each { |com| temp << com}
  temp
end

>> [["a", "b", "c"], ["a", "b"], ["a", "c"], ["b", "c"]]

If the input is not 3 then this will work :

def conflict(a)
  temp = []
  2.upto(a.size-1) {|i| temp += a.combination(i).to_a}
  temp << a
end

The initial array can be added at the beginning or end. Above it's at the end.

Upvotes: 0

Mark Thomas
Mark Thomas

Reputation: 37517

Here's how to get the subsets you're looking for:

def subsets(a)
  2.upto(a.length).flat_map {|n| a.combination(n).to_a}
end

irb(main):023:0> subsets(["a", "b", "c"])
=> [["a", "b"], ["a", "c"], ["b", "c"], ["a", "b", "c"]]

Anything else you want, you'll have to edit your question and provide more detail.

Upvotes: 2

Related Questions