Hi,
I want to find the combination of array elements
like for example
a = [1,2,3,4]
the combinations are
[1,2,3,4]
[1,3,4,2]
[1,2,3]
etc…
If anybody knows plz reply me
Hi,
I want to find the combination of array elements
like for example
a = [1,2,3,4]
the combinations are
[1,2,3,4]
[1,3,4,2]
[1,2,3]
etc…
If anybody knows plz reply me
Do you want to know the number of possible combinations or the
combinations themselves?
On Jul 6, 11:57 pm, “Pragash Mr.” [email protected]
Pragash Mr. wrote:
Hi,
I want to find the combination of array elementslike for example
a = [1,2,3,4]
the combinations are
[1,2,3,4]
[1,3,4,2]
[1,2,3]
etc…If anybody knows plz reply me
Think this works,
def combinations(array)
return [] if array == []
return [array, []] if array.length == 1
left, right = array[0…0], array[1…-1]
rtn = []
combinations(right).each do |r_array|
rtn << r_array
rtn << left + r_array
end
return rtn
end
combinations([1])
=> [[1]]
combinations([1])
=> [[1], []]
combinations([1,2])
=> [[2], [1, 2], [], [1]]
combinations([1,2,3])
=> [[3], [1, 3], [2, 3], [1, 2, 3], [], [1], [2], [1, 2]]
enjoy.
http://www.workingwithrails.com/person/12394-matthew-rudy-jacobs
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs