Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Dec 2003
    Location
    Bahamas
    Posts
    20
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Need Permutation Script

    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

  • #2
    Regular Coder
    Join Date
    Aug 2002
    Location
    São Paulo, Brazil
    Posts
    367
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Try this:
    Code:
    <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.
    /Daniel


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •