Suppose I have a JavaScript array as follows:
var arr = [1,2,3,4,5,6,7,8,9]
I want to get all the possible sets using three numbers from the above array. For example
var possibilities = [[1,1,1], ..., [1,2,3], [1,2,4], ......, [4,2,1], [4,2,2], [9,9,9]]
I hope I am able to explain this question to you.
CodePudding user response:
Try this, but please, make sure this is what you want, because generate 729 items in result array
var arr = [1,2,3,4,5,6,7,8,9]
let result = [];
for(let i = 0; i < arr.length; i ) {
for (let j = 0; j < arr.length; j ) {
for (let k = 0; k < arr.length; k ) {
result.push([arr[i], arr[j], arr[k]])
}
}
}
console.log(result)
CodePudding user response:
Time and Space complexities are n^3. It is the minimum we can do, by the way.
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let possibilities = [];
arr.forEach(first => {
arr.forEach(second => {
arr.forEach(third => {
possibilities.push([first, second, third]);
})
})
})
console.log(possibilities);