trsands
01-07-2004, 03:33 PM
Does anyone know where I can find a script that generates all permutations for a 3 or 4 digit number. The script should also remove any duplicate numbers
|
||||
Need Permutation Scripttrsands 01-07-2004, 03:33 PM Does anyone know where I can find a script that generates all permutations for a 3 or 4 digit number. The script should also remove any duplicate numbers Danne 01-07-2004, 07:37 PM Try this: <html> <head> <title> Permutations </title> </head> <script> Array.prototype.swap=function(a,b) { this.splice(b,0,this.splice(a,1)); } function showPermutations(str) { function getPermutations(arr) { function sameAsOrig() { for (var i=0;i<orig.length;i++) { if (orig[i]!=arr[i]) { return false; } } return true; } function p(moveIdx) { var len=a.push([]); var idx=len-1; var i=0; for (var i=0;i<arr.length;i++) { a[idx][i]=arr[i]; } if (moveIdx+1==arr.length) { moveIdx=0; } arr.swap(moveIdx,moveIdx+1); if (!sameAsOrig()) { p(moveIdx+1); } } arr.sort(function(a,b) { if (a>b)return 1; if (a<b)return -1; return 0; }); var a=[]; var orig=[]; for (var i=0;i<arr.length;i++) { orig[i]=arr[i]; } if (arr.length > 0) { p(0); } return a; } var arr=new String(str).split(""); var result = getPermutations(arr); for(var i=0; i<result.length; i++) document.write(result[i].join("")+"<br>"); } </script> <body onload="showPermutations(1423);"> </body> </html> There is no check for duplicate numbers, but it shouldn't be too complicated to removed them afterwards. |
| |||
EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum