0

I have some JavaScript that gets a random element from an array. When I press a button, it selects another random element. How can I prevent the same element from being selected twice in a row?

Here is the random element code:

var arr= ["cat1.jpg", "cat2.jpg", "cat3.jpg", "cat4.jpg", "cat5.jpg", "cat6.jpg", "cat7.jpg", "cat8.jpg", "cat9.jpg","cube1.jpg", "cube2.jpg", "cube3.jpg", "cube4.jpg", "cube5.jpg", "cube6.jpg", "cube7.jpg", "cube8.jpg"];
let randomElement = arr[Math.floor(Math.random() * arr.length)];
console.log(randomElement);
image.src=(randomElement);

And here the code of the button:

catbutton.onclick=function(){catfunction()};
function catfunction(){
    if (randomElement=="cat1.jpg" || randomElement=="cat2.jpg" || randomElement=="cat3.jpg" || randomElement=="cat4.jpg" || randomElement=="cat5.jpg" || randomElement=="cat6.jpg" || randomElement=="cat7.jpg" || randomElement=="cat8.jpg" || randomElement=="cat9.jpg"){
        x++;
        randomElement = arr[Math.floor(Math.random() * arr.length)];
        console.log(randomElement);
        console.log(randomElement);
        image.src=(randomElement);
    }
    else{
        pantplay.style="display: none";
        puntuator.style="display: ";
        puntuation.innerHTML=x;
        closepunt.onclick=function(){closepuntuation()};
    }
}
DBS
  • 9,110
  • 4
  • 35
  • 53
  • 4
    Please include your code so far, and try to make the problem as clear as possible (I'm afraid I don't understand "get a random element, without beign the last one" ) – DBS Jun 04 '20 at 14:58
  • 1
    @DBS I edited the question, and I belive now you will understand. By the way, the question is cloed, what I can do? –  Jun 04 '20 at 15:04
  • 2
    So just a little more clarification: You are trying to get a random item from an array, but you want to avoid getting the same item twice in a row? (As for the question being closed, edit it until you think it is in a good state, and then people will vote to reopen it if they believe it's now a valid question) – DBS Jun 04 '20 at 15:11
  • 1
    @DBS yes, this is what I want to do. And by the way, I edited the question, I think is good now –  Jun 04 '20 at 15:12
  • I would just shuffle the array to start and pop off the list https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array unless you do want dupes to come up, than it is just checking to see if the last matches. – epascarello Jun 04 '20 at 15:56

2 Answers2

0

You could store the index of last element selected as a variable and use a do-while loop to ensure that the next random number is not equal to that variable.

pseudocode:

do {
    randIndex = Math.floor(Math.random() * arr.length);
}
while(randIndex == lastIndex);

randomElement = arr[randIndex];
lastIndex = randIndex;
Brett L
  • 105
  • 1
  • 11
  • Do you mean like ```var lastElement=randomElement```? –  Jun 04 '20 at 16:46
  • I changed a few things to make the code cleaner and more clear. You are right that you will need to reassign your lastElement (which I switched to lastIndex) variable each time you pick a new index. – Brett L Jun 04 '20 at 17:12
0

One option is to set aside the items that are temporary unavailable. Move them back when you want to make them available again.

function createPseudorandomGenerator(collection, turnsUnavailable) {
  const available = Array.from(collection);
  const unavailable = [];
  
  return function () {
    console.log("available:", ...available);
    console.log("unavailable:", ...unavailable);
  
    const index = Math.floor(Math.random() * available.length);
    const items = available.splice(index, 1);
    unavailable.unshift(...items);
    available.push(...unavailable.splice(turnsUnavailable, 1));

    console.log("taken:", items[0]);
    return items[0];
  };
}

var arr = ["cat1.jpg", "cat2.jpg", "cat3.jpg", "cat4.jpg", "cat5.jpg", "cat6.jpg", "cat7.jpg", "cat8.jpg", "cat9.jpg","cube1.jpg", "cube2.jpg", "cube3.jpg", "cube4.jpg", "cube5.jpg", "cube6.jpg", "cube7.jpg", "cube8.jpg"];
const takeBtn = document.getElementById("take-btn");
const getRandom = createPseudorandomGenerator(arr, 3);

takeBtn.addEventListener("click", getRandom);
<button id="take-btn">Take</button>
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
  • But then in ´´´image.src()´´´ What should I write? –  Jun 04 '20 at 17:04
  • 1
    `image.src = getRandom()` don't forget to change the `3` in `createPseudorandomGenerator(arr, 3)` to a `1` if you want items to only be unavailable the next "turn". The `3` is only for demonstration purposes and will make a generated item unavailable for 3 "turns" after generation. – 3limin4t0r Jun 04 '20 at 17:06
  • But it don't load any image –  Jun 04 '20 at 17:11
  • Did the images load correctly before? `console.log` the `image` and check if the source is set correctly. You might not have the assets available. Remember that `src="cat1.jpg"` is a relative path and will navigate from the current page (for example if you're on `/foo/bar` then it will try to look for `/foo/bar/cat1.jpg`). If you want the path to be absolute you have to add a slash `src="/cat1.jpg"` – 3limin4t0r Jun 04 '20 at 17:17