I have a 2D array and want to generate a 3D array that will show the most efficient groupings for all sets. Example:
[[1, 2],
[1, 2, 3, 4],
[3, 4],
[1, 2, 5]]
Result:
[[[1, 2]],
[[1, 2], [3, 4]],
[[3, 4]],
[[1, 2], [5]]]
I think I would need to do a nested loop and determine the intersection and differences to generate the 3D array. However, inject(&:&) seems like it might solve it more elegantly, though I'm a bit new to inject and unsure how to implement it for this problem. This is to be done in Ruby.
Any help is appreciated. Thanks!
--Update--
By efficient groupings I mean find the best combination that generates the least amount开发者_JS百科 of total sets in the result by finding the largest duplicate sets.Another example:
[[1, 2, 3, 4],
[1, 4],
[1, 3, 4],
[1, 2, 3, 4, 5],
[2, 5]]
Possible Result (8 total sets):
[[[1, 3, 4], [2]],
[[1, 4]],
[[1, 4], [3]],
[[1, 3, 4], [2, 5]],
[[2, 5]]]
This is a good result, but the first set could be optimized.
Better Result (7 total sets):
[[[1, 2, 3, 4]],
[[1, 4]],
[[1, 4], [3]],
[[1, 2, 3, 4], [5]],
[[2, 5]]]
Both results contain a total of 5 unique sets. The sets in the better result are (1, 2, 3, 4), (1, 4), (3), (5), and (2, 5). The total number of sets in the better result is 7 as opposed to 8 in the possible result. We want the least amount of sets.
You definitely should explain what "the most efficient grouping" means. In the meantime, if you just need to split arrays into 2-element chunks, just combine map
and each_slice
:
arr.map{|a| a.each_slice(2).to_a}
# => [[[1, 2]], [[1, 2], [3, 4]], [[3, 4]], [[1, 2], [5]]]
First you should figure out the algorithm in pseudocode for what you want to do (its not the Ruby that's keeping you back right now). Then go use these ruby primatives to make it happen
http://ruby-doc.org/core/classes/Enumerable.html
http://www.ruby-doc.org/core/classes/Array.html
http://corelib.rubyonrails.org/classes/Set.html
精彩评论