Create a Random List in ColdFusion

March 26, 2008

This is a way to randomise (or randomize if you're American!) a list in ColdFusion. I haven't benchmarked it but it works.


function ListRandomise(lstToRandomise) {
    var local = StructNew();
    
    // by default the function will randomise all elements in the list unless a second parameter is passed...
    if (ArrayLen(Arguments) gte 2) {
        local.iElements = Arguments[2];
    }
    else {
        local.iElements = ListLen(arguments.lstToRandomise);
    }

    local.lstRandom = "";
    local.lstToRandomise = ListSort(arguments.lstToRandomise, "text");
    
    // convert to an array for speed
    local.aryToRandomise = ListToArray(local.lstToRandomise);
    
    for (local.i=1; local.i lte local.iElements; local.i = local.i+1) {
        if (ArrayLen(local.aryToRandomise) neq 0) {
            local.iRandom = RandRange(1, ArrayLen(local.aryToRandomise));
            local.lstRandom = ListAppend(local.lstRandom, local.aryToRandomise[local.iRandom]);
            ArrayDeleteAt(local.aryToRandomise, local.iRandom);
        }
        else {
            // run out of list elements...
            break;        
        }
    }
    return local.lstRandom;
}

No comments

Leave a comment

If you found this post useful, interesting or just plain wrong, let me know - I like feedback :)

Please note: If you haven't commented before, then your comments will be moderated before they are displayed.