javascript return all combination of a number -


i trying combination of number. example, input "123" should return ["123", "231", "213", "312", "321", "132"].

here function:

function swapdigits(input) {     (var = 0; i++; < input.length - 1) {         var output = [];         var inter = input.slice(i, + 1);         var left = (input.slice(0, i) + input.slice(i + 1, input)).split("");         (var j = 0; j++; j <= left.length) {             var result = left.splice(j, 0, inter).join("");             output.push(result);          }     }     console.log(output);     return output; } 

however function returns undefined, tell me what's going wrong?

the errors for loop , scope have been mentioned. besides that, splice method change string operates on. means inner loop never terminate because left keeps on growing, j never reaches left.length.

if new language, suggest starting implementation close algorithm want implement. then, once comfortable it, use more advanced language constructs.

see this fiddle example. algorithm code:

function getpermutations(input) {         if(input.length <= 1)     {         return [input];     }     var character = input[0];     var returnarray = [];     var subpermutes = getpermutations(input.slice(1));     debugoutput('returned array: ' + subpermutes);     for(var subpermuteindex = 0; subpermuteindex < subpermutes.length; subpermuteindex++ )     {        var subpermute = subpermutes[subpermuteindex];        for(var charindex = 0; charindex <= subpermute.length; charindex++)        {                                     var pre = subpermute.slice( 0, charindex );            var post = subpermute.slice( charindex );                         returnarray.push(pre+character+post);                       debugoutput(pre + '_' + character + '_' + post );        }     }     return returnarray; } 

basically, walk end of string , work way constructing permutations of sub-strings. easiest see debug output 1234. note 'returned array' refers array created permutations of sub-string. note current character placed in every position in array. current character shown between _ such 1 in 432_1_.

returned array: 4 _3_4 4_3_ returned array: 34,43 _2_34 3_2_4 34_2_ _2_43 4_2_3 43_2_ returned array: 234,324,342,243,423,432 _1_234 2_1_34 23_1_4 234_1_ _1_324 3_1_24 32_1_4 324_1_ _1_342 3_1_42 34_1_2 342_1_ _1_243 2_1_43 24_1_3 243_1_ _1_423 4_1_23 42_1_3 423_1_ _1_432 4_1_32 43_1_2 432_1_ 

this algorithm doesn't enforce uniqueness. so, if have string 22 2 results - 22,22. also, algorithm uses recursion think quite intuitive in case, there pure iterative implementations if them.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -