I have an multidimensional array and it contains 5 arrays and each of these 5 arrays contain different number of arrays. For example array at index # 0 contains 99 arrays of same length and array at index # 1 contain 300 arrays of same length. All of these arrays contain combination made from a single array who has 27 elements in it. Now I want to take a single combinations from all five array and get a single multidimensional array of length 5 who has the same number of elements as the original array of 27 elements.
I have tried using for loops but indexing through each of the combination at all 5 places to get an array of 5 arrays whose elements collectively are equal to the original arrays but the amount of iteration are way too much. Is there any better way of doing this.
2
Answers
This answer is based on the comment you made
[ [ [1,2][1,3],[4,9] ], [ [5,6,1], [3,1,2], [8,19,10]]]
and under the assumption that you want only distinct values only. In this case[[[4,9]],[[5,6],[8,19,10]]]
Note: that result subset provide by you does not include 5 and 6 values. Ideally it should be included since it is also distinct.
Refer the below code :
My answer is very similar to Seleka’s, but uses things like
reduce
to improve the space efficiency, and avoidsincludes
which adds another O(n) to each of those calls.Also, Seleka and I are interpreting "I want to get array single array from both of these arrays and the elements inside these arrays should be distinct" to mean, distinct in the entire result. But if you mean "distinct only among its own subArray" that would be a simple change.
Keep in mind that a subArray might not have a combination that has all distinct values, so I’m returning an empty array in that case.
This has an O(n) runtime and O(n) space due to the valueOccurences object.