0

I am working on a random generator made using javascript for a html page I am working on, and I have been able to make a function that uses math.random to generate random value from an array of values (in my case pokemon names, and i am generating random pokemon that have been added into this array.) This is linked to a button, and every time the button is pressed the function runs and a new pokemon name is generated.

However, I am struggling to make it so that the function generates a completely different name each time, and sometimes i click the button more than once and it just shows the same pokemon, and i feel it is not a good look as it feels broken sometimes. I was wondering if someone can look at my code and help me out.

var pokemonNames = ["charmander", "squirtle", "bulbasaur"];

function generateRandomPoke() {
    var randPoke = pokemonNames[Math.floor(Math.random() * (pokemonNames.length))];
    return randPoke;
}

$("#randomizebutton").click( function() {
    $("#pokemonname").html(generateRandomPoke);
});
gudabya1
  • 3
  • 1

3 Answers3

0

As @jabaa said, you could remove the elements of the array, or another alternative is to have a global variable that stores the names already returned. In case the value to be returned is on the global variable, a new name must be selected.

0

Get the index and remove the element from the array:

function generateRandomPoke() {
    var index = Math.floor(Math.random() * (pokemonNames.length))
    var randPoke = pokemonNames[index];
    pokemonNames.splice(index, 1);
    return randPoke;
}
gbalduzzi
  • 9,356
  • 28
  • 58
  • thanks a lot gbalduzzi! This was just what i was looking for, i even added an if statement at the start of the statement to tell me when the array was empty. – gudabya1 Jun 01 '21 at 14:51
0

You have to generate the index until its not match the previous one see the following code

var index = 0;
 do{
Index = Math.floor(Math.random() * (pokemonNames.length));
} while(previous_index==index) 
    previous_index = index;
    var randPoke = pokemonNames[index];
    return randPoke;
}
Munawar Hussian
  • 287
  • 1
  • 4
  • 12