So I am writing a program to calculate the possible combination(s) of an input array.
The code you see is just the part of a bigger program, but I narrowed the problem down to this function. I call my array a string because a previous function would turn the string into an array of numbers so I can work with duplicate characters.
Now the function is 40 lines, so I suggest checking out the repl.it.
I wrote comments to best show how it is working
function combinationGen(string, fact, state, max) {
let backup = [...string]
let combination = [];
let combinations = [];
while (combinations.length < fact) {
// While my current combination amount is less then possible
let i = string.length
while (combination.length < max) {
let randomIndex = Math.floor(Math.random() * i)
combination.push(string[randomIndex])
// Get a random chacater from the string, add to combination
if (state === "no-repeat") {
string = string.splice(randomIndex, 1)
// remove it so we do not pick it again
}
}
if (combinations.indexOf(combination) === -1) {
combinations.push(combination)
// Is the combination already present?
}
combination = []
// reset my combination
string = [...backup]
// reset my string
i = string.length
// reset the value of i
}
return JSON.stringify(combinations.sort)
}
My issue is that my combinations come out still with repeats even if i specify ‘no-repeats’ as my state. I also just get ‘null’ in my combinations.
[[0,null,null],[0,0,null],[0,0,0],[1,null,null],[1,null,null],[2,null,null]]
Any ideas?