Archive

Archive for December, 2011

ColdFusion Permutation Generator

Here’s a simple starter script for generating permutations in ColdFusion. I couldn’t easily find one online so I created this one based on a javascript version found over on Scriptar.

Scriptar JS Permutation Generator

ColdFusion CFSCRIPT version:

<cfscript>
permArr = [];
usedChars = [];

function permute(input) {
  var i = 1;
  var ch = '';
  var chars = ListToArray(input);

  for (i = 1; i < ArrayLen(chars) + 1; i++) {

    /* get and remove character at index "i" from char array */    
    ch = chars[i];
    ArrayDeleteAt(chars,i);

    /* add removed character to the end of used characters */   
    ArrayAppend(usedChars,ch);

    /* when there are no more characters left in char array to add, add used chars to list of permutations */
    if (ArrayLen(chars) eq 0){
        ArrayAppend(permArr,ArrayToList(usedChars));
    }

    /* send characters (minus the removed one from above) from char array to be permuted */
    permute(ArrayToList(chars));

    /* add removed character back into char array in original position */
    if (ArrayLen(chars) lt i){
      ArrayAppend(chars,ch);
    }else{
      ArrayInsertAt(chars,i,ch);
    }

    /* remove the last character used off the end of used characters array */
    ArrayDeleteAt(usedChars,ArrayLen(usedChars));  
  }
}

mylist = 'A,B,C';
permute(mylist);

WriteDump(permArr);

</cfscript>

Example Output

array
1 A,B,C
2 A,C,B
3 B,A,C
4 B,C,A
5 C,A,B
6 C,B,A
Follow

Get every new post delivered to your Inbox.