Code for Variations with repetition (combinatorics) using javascript?
-
09-06-2021 - |
Question
Does anyone have Javascript code for generating all variations with repetition?
Example of variations with repetition:
(size=3, input=A,B)
AAA, AAB, ABA, BAA, ABB, BAB, BBA, BBB
What I need is to do something similar for numbers from 0-9 as the input and 6 digits length as size (according to my example).
Just to know, I got this working with a code in Java and also in .NET based on this project (check the link). All variations with repetition for what I need generates 1000000 values.
http://www.codeproject.com/KB/recipes/Combinatorics.aspx
Is it possible to do it in Javascript?
Thanks in advance.
Solution
you have chosen the simplest case from combinatorics...
var i, n = 1000000;
for (i = 0; i < n; i++)
console.log(('' + (i + n)).substring(1));
will give you all the combinations of 0-9 in 6 spots (1000000 === Math.pow(10, 6)
).
OTHER TIPS
I've just wrote it right now, it needs probably more tests and optimizations but this should get you started:
var input = "ABCD";
var size = 3;
var results = [];
function solve(i, elt) {
if(elt.length == size) {
results.push(elt);
return;
}
for(var j = 0; j < input.length; j++) {
solve(j, elt+input[j]);
}
}
solve(0, "");
console.log(results);