Quick actions

cmd+k|ctrl+k

Navigation

Languages

SEPA : Simple Efficient Permutation Algorithm

Snippet info

Language

JavaScript

Visibility

public

Author

horngyih

Created

2018-09-24T04:22:59Z

Updated

2018-09-24T04:22:59Z

/**
 * A Javascript implmentation of the Simple Efficient Permutation Algorithm (SEPA)
 * Source : [http://www.quickperm.org/soda_submit.php]
 **/

function swap( target, i, j ){
    if( target ){
        let temp = target[i];
        target[i] = target[j];
        target[j] = temp;
        return target;
    }
    return target;
}

function permute( target ){
    let length = target.length;
    let key = length-1;
    let newKey = length-1;
    
    while( key > 0 && target[key] <= target[key-1] ){
        key--;
    }
    
    key--;
    
    if( key < 0 ){
        return 0;
    }
    
    newKey = length-1;
    while( newKey > key && target[newKey] <= target[key] ){
        newKey--;
    }
    
    swap( target, key, newKey );
    
    length--;
    key++;
    
    while( length > key ){
        swap( target, length, key );
        key++;
        length--;
    }
    return 1;
}

let test = 'cac';

let target = test.split('');
let permutations = [];
do{
    permutations.push( target.join('') );
} while( permute(target) );

console.log( `Permuations : ${permutations.length}\n${permutations.join("\n")}` );

INFO