Perfect Randomizer

72 Views Asked by At

I am trying to make an array, shuffle it, then go through it in order. However, when I shuffle it (START) more than once, it messes up! Also When you get to the last number in the randomized array, it messes up also! please help and thank you!

JS

var minnum = 1;
var maxnum = 104;

function start() {
  var nums = [];

  while(minnum < maxnum+1){
    nums.push(minnum++);
  }

  function shuffle(o) {
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
  }

  var randomnum = shuffle(nums);
  document.getElementById('txt').innerHTML = randomnum;
  localStorage["nums"] = JSON.stringify(randomnum);
  localStorage.setItem("current", 0);

}

function Link() {
  if (localStorage.getItem("current") === null || localStorage.getItem("nums") === null) {
    start();
  }

  var current = localStorage.getItem("current");
  var nums = JSON.parse(localStorage["nums"]);
  document.getElementById('txt').innerHTML = nums;
  document.getElementById('txt1').innerHTML = nums[current];
  current++;

  if(current > 103) {
    location.reload();
    start();
    current = 0;
  }
  localStorage.setItem("current", current);
}

HTML

<body>
  <input type="button" onclick="start()" value="Start" />
  <span id="txt"></span>
  <input type="button" onclick="Link()" value="Next" />
  <span id="txt1"></span>
</body>
1

There are 1 best solutions below

0
On

The error seems to be that minnum AND maxnum are declared outside of the start() function and never initialized to 1 and 104 anymore, hence whenever you hit start the second time the first while will not push anything to nums array because minnum is 103 (from the previous cycle) and maxnum 104.

Fiddle:

http://jsfiddle.net/1pd18eun/1/

Code (just moved minnum and maxnum inside):

function start()
{
var minnum = 1;
var maxnum = 104;

var nums = [];
    while(minnum < maxnum+1){
        nums.push(minnum++);
    }
    var randomnum = shuffle(nums);
    document.getElementById('txt').innerHTML = randomnum;
    localStorage["nums"] = JSON.stringify(randomnum);
    localStorage.setItem("current", 0);
}

function shuffle(o) {
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
}

function Link()
{
    if (localStorage.getItem("current") === null || localStorage.getItem("nums") === null) {
        start();
    }
    var current = localStorage.getItem("current");
    var nums = JSON.parse(localStorage["nums"]);
    document.getElementById('txt').innerHTML = nums;
    document.getElementById('txt1').innerHTML = nums[current];
    current++;
    if(current > 103)
    {
        location.reload();
        start();
        current = 0;
    }
localStorage.setItem("current", current);
}

Besides, for the sake of readers and good people, start to indent your code, it was very hard to properly understand what you were doing.