3

Let's say i haven an array of let arr = [null, null, null, null, null, null, null, null, null] containing 9 items.

And i have 9 <button data-index> with each having an data-index=0 to data-index=9

If i click a button, let's say <button data-index=4>, then we assign 'Cookie' to the corresponding index of arr: arr[4] = 'Cookie'

arr becomes [null, null, null, null, 'Cookie', null, null, null, null]

How can i select a random element/index of arr which is null without it selecting arr[4] since it already contains Cookie?.

It's for the AI move of a tic-tac-toe game.

0

4 Answers 4

3

An ES6 solution with filter:

var arr = [null, null, null, null, 'Cookie', null, null, null, null];

var indexes = Array.from(Array(arr.length).keys());
var availableIndexes = indexes.filter((index) => arr[index] == null);
var selectedIndex = availableIndexes[Math.floor(Math.random()* availableIndexes.length)];

console.log(availableIndexes);
console.log(selectedIndex);

Sign up to request clarification or add additional context in comments.

Comments

2

Do a fisher-yates shuffle to get a random order of the indices of the array and then pick them one by one.

Idea is to set the random index to the buttons at the start. And not compute the random index on click.

Comments

2
var randomIndex = 0;
while ( arr[randomIndex] != null ) {
    randomIndex = Math.floor( Math.random() * (arr.length - 1) );
}

Let me know if this helps.

Comments

1

Another solution:

var arr = [null, null, null, null, 'Cookie', null, null, null, null];
var indexes = [];
for (var i =0; i<arr.length; i++){
    if(arr[i] == null)
        indexes.push(i);
}
var index = indexes[parseInt(Math.random() * (indexes.length - 1))];

alert(index);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.