Javascript Random on Array Without Repeat

How to efficiently randomly select array item without repeats?

Whenever an item is selected, move it to the back of the array and randomly select from a slice of the original array array.slice(0, -5).

var a = ["Roger", "Russell", "Clyde", "Egbert", "Clare", "Bobbie", "Simon", "Elizabeth", "Ted", "Caroline"];

var chooseName = function () {
var unique = true;
num = Math.floor(Math.random() * a.length - 5);
name = a.splice(num,1);
a.push(name);
}


window.addEventListener("keypress", function (e) {
var keycode = e.keyCode;
if (keycode == 13) {
chooseName();
}
}, false);

EDIT: This also has the side-effect of not giving whichever variables happen to tail the list the unfair disadvantage that they won't be considered in the first N calls. If that's a problem for you, maybe try hold a static variable somewhere to keep track of the size of the slice to use and max it out at B (in this case, 5).
e.g.

var a = ["Roger", "Russell", "Clyde", "Egbert", "Clare", "Bobbie", "Simon", "Elizabeth", "Ted", "Caroline"];
B = 5; //max size of 'cache'
N = 0;

var chooseName = function () {
var unique = true;
num = Math.floor(Math.random() * a.length - N);
N = Math.min(N + 1, B);
name = a.splice(num,1);
a.push(name);
}

Random item from the array without repeating elements in Javascript

You can use splice to remove the item from the array after displaying it.

If you don't want to alter the array, then you can create a copy before altering it.

let id = Math.floor(Math.random() * Qu.length);
let p = Qu[id];
Qu.splice(id, 1);
text += "This is " + p + "<br>";

Working code:

function Gen() {  let Qu = ["Yazeed", "Ammar", "Marwan", "Othman", "Sameh", "Amro", "Ibraheem"];  let p1 = document.getElementById("demo1");  let text = " ";  for (let i = 0; i < 4; i++) { //Qu.length = 7    let id = Math.floor(Math.random() * Qu.length);    let p = Qu[id];    Qu.splice(id, 1);    text += "This is " + p + "<br>";  }  p1.innerHTML = text;}
<div id="demo1"></div><button type="button" onclick="Gen()">Generate</button>

Javascript random on array without repeat

You can use a array for storing question that have been asked
Check array every time during randomization and then select question

var track=new Array();

while(true)//loop until Unique number
{
var randomQuiz=Math.floor(Math.random()*quiz.length);

if(track.indexOf(randomQuiz)==-1)//if you have got your unique random number
{
track.push(random);
break;
}
}

Edit: as Stephen P pointed out it may lead to performance issue, removing element from array is more logical thing to do as suggested by Brent Waggoner.

Generate random number array without duplicates next to each other in Javascript?

Keep the last value, and repeat the loop if you get the same value:

var last_val = null;
do {
var val = Math.floor(Math.random() * 9);
if(val == last_val) continue;
initArray.push(val);
i++;
last_val = val;
} while(i < level.dots)


Related Topics



Leave a reply



Submit