javascript: Get N random elements from a List

/**
 * 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;
}
Did this help you? Tip $1 Tip $2 Tip $5

Leave a Reply