k random elements from array

Benchmark created by Tibos on


Description

Tests methods of extracting k unique random values from an array.

Shuffling - shuffles the array then retrieves the first k

Splicing - extracts k elements one by one, splicing the array at each step

Checking - extracts k elements one by one, checking if the current one has been previously extracted

Preparation HTML

<script>
function splicer(items, count) {
items = items.slice(0);
var newItems = [];

for(var i = 0; i < count; i++) {
    var idx = Math.floor(Math.random() * items.length);
    newItems.push(items[idx]);
    items.splice(idx, 1);
}
return newItems;
}

function shuffler(items, count) {
  function shuffle(array) {
    var counter = array.length, temp, index;

    // While there are elements in the array
    while (counter--) {
        // Pick a random index
        index = (Math.random() * counter) | 0;

        // And swap the last element with it
        temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}


var randoms = shuffle(items.slice(0));
randoms.length = 4;
return randoms;
}

function checker(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);
    if (n > len)
        throw new RangeError("getRandom: more elements taken than available");
    while (n--) {
        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len;
    }
    return result;
}
</script>

<script>
var input = [];
for (var i=0; i<1000; i++){
  input.push(i);
}
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Shuffling
for (var i=1; i<9; i++) shuffler(input, 100 * i);
ready
Splicing
for (var i=1; i<9; i++) splicer(input, 100 * i);
ready
Checking
for (var i=1; i<9; i++) checker(input, 100 * i);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.