javascript - Generating all possible combinations of strings -
i trying generate possible combinations of string.
e.g. list below: a1q5z!h9, b1q5z!h9, c1q5z!h9, d1q5z!h9, a2q5z!h9 ... etc
rather create lots of nested loops, thought seek clever modulo ... nail wall.
this javascript have come - pointers how might go on?
var c = [ ['a', 'b', 'c', 'd'], ['1', '2', '3', '4'], ['q', 'w', 'e', 'r'], ['5', '6', '7', '8'], ['z', 'x', 'c', 'v'], ['!', '"', '£', '$'], ['h', 'j', 'k', 'l'], ['9', '8', '7', '6'], ]; var o = document.getelementbyid('output'); var pw = ""; var chars = c.length; for( var = 0; <20; i++) { pw = "" for(var j = 0; j < chars; j++ ) { pw += c[j][i%4]; } op(pw); } function op(s) { o.innerhtml = o.innerhtml + "<br>" + s; } this outputs first 20 in list, repeats ... have not quite. help or pointers appreciated.
quite easy write recursive function demo.
function permutate(abc, memo) { var options; memo = memo || abc.shift().slice(0); if(abc.length) { options = abc.shift(); homecoming permutate(abc, memo.reduce(function(all, item){ homecoming all.concat(options.map(function(option){ homecoming item + option; })) }, [])); } homecoming memo; }; console.log(permutate(c).length); //65536 items or more imperative approach
function permutate2(abc) { var options, i, len, tmp, j, optionslen, memo = abc.pop().slice(0); //copy first lastly array while(options = abc.pop()) { //replace recursion tmp = []; optionslen = options.length; for(i = 0, len = memo.length; < len; i++) { //for every element in memo for(j = 0; j < optionslen; j++) { //do cartesian product options tmp.push(options[j] + memo[i]); } } memo = tmp; } homecoming memo; } javascript cartesian
No comments:
Post a Comment