in Code

javascript: Get N random elements from a List

[javascript]
/**
* Walks linearly through the list to find an element.
* returns true if it’s found.
*/
function elementIn(collection, element) {
for (var i=0; i < collection.length; i++) {
if (collection[i]==element) {
return true;
}
}
return false;
}

/**
* Returns a new list of n random elements taken out of myList.
*/
function getNElementsAtRandom(myList, n) {
var toGo = n;
var result = [];
var indexesUsed = [];

while (toGo > 0) {
index=-1;

do {
index = Math.floor(Math.random()*(myList.length));
console.log(index);
} while (elementIn(indexesUsed, index));

indexesUsed.push(index);
result.push(myList[index]);
toGo–;
}

return result;
}
[/javascript]

Write a Comment

Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.