Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Using random array

I’ve been playing with random array arrangements and was wondering if there is a way to pull word from the array only once. So every time you click on the changeWorld button then it will randomly draw from the array list until all the words where used only once?

Learning JavaScript so I don't need anyone to write me the code, just want get pushed in the right direction and know if it is possable. There isn't anything I can find that address the concept.

<body>

<button id="change-world-btn">Change World</button>

Hello <span class="world-name">World!</span><br />



<script type="text/javascript">

var worlds = new Array ("Pluto", "Mars", "Saturn", "Jupiter", "Uranus");

function newWorld() {
    return worlds[Math.floor(Math.random() * worlds.length)];
}

elements = document.getElementsByTagName('span');

document.getElementById('change-world-btn').onclick = function() {
    world = newWorld();
    for(var i = 0, el; el = elements[i++];) {
        if(el.className == 'world-name') {
            el.innerHTML = world;
        }
    }
};
</script>       
</body>
like image 218
Jeff Avatar asked Feb 17 '26 01:02

Jeff


2 Answers

Remove the words that you have used from the array:

function newWorld() {
  var index = Math.floor(Math.random() * worlds.length);
  var world = worlds[index];
  worlds.splice(index, 1);
  return world;
}

You might also want to check if the array is empty first.

like image 146
Guffa Avatar answered Feb 18 '26 13:02

Guffa


This sounds like a job for a stack or a queue. You can take your array, shuffle to get your "randomness", push each element from your array into a stack or queue, then pop off an element everytime the user clicks your button. Edit: Here is a small example of a stack.

var stack=new Array();
stack.push("A");
stack.push("B");
stack.push("C");
alert(stack.pop());
alert(stack.pop());
alert(stack.pop());
like image 33
mittmemo Avatar answered Feb 18 '26 13:02

mittmemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!