niaoy
niaoy

Reputation: 101

How to not repeat a result from a random function

I have this function to randomly generate a country name for a quiz that I've been making, but I don't want the same name appearing more than once. How could I do that? Here is the code that I'm using.

<div style="float:left">
<h1> <span id="questionnum"></span>. Can you locate <span id="countryquestion"></span> on the map?</h1>
</div>


<script type="text/javascript">   

generateCountry();

function generateCountry(){

    filenames = [ "Albania", "Andorra", "Armenia", "Austria", "Azerbaijan", "Belarus", "Belgium", "Bosnia and Herzegovina", "Bulgaria", "Croatia", "Cyprus", "Czech Republic", "Denmark", "Estonia", "Finland", "France", "Georgia", "Germany", "Greece", "Hungary", "Iceland", "Ireland", "Italy", "Latvia", "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Malta", "Moldova", "Monaco", "Montenegro", "The Netherlands", "Norway", "Poland", "Portugal", "Romania", "Russia", "San Marino", "Serbia", "Slovakia", "Slovenia", "Spain", "Sweden", "Switzerland", "Ukraine", "United Kingdom" ];

    filename = filenames[Math.floor(Math.random()*filenames.length)];

    document.getElementById('countryquestion').textContent = filename;
    }

</script>

Upvotes: 0

Views: 250

Answers (2)

Eric
Eric

Reputation: 2116

filename = filenames.splice(Math.floor(Math.random()*filenames.length), 1);

document.getElementById('countryquestion').textContent = filename[0];

Array splice will add or remove items from an array. The first argument is the index to work with. The second argument is how many elements from that index on to remove (0 if only adding to the array). Any additional arguments are items to add to the array at that location. In this case we specify a random index and remove one item. The return value is an array of elements removed, which in this case is an array with the one element that was removed from filenames.

Upvotes: 2

ankil Sanghvi
ankil Sanghvi

Reputation: 1

Do you want them to be truly random and truly unique? You can only possiblity.

you have to store every one in a database to ensure there are no duplicates. If you generate a duplicate, you'll need to regenerate or just increment the number and try again. If this is what you're looking for, it might be good to try just incrementing the value starting at one.

Upvotes: 0

Related Questions