-3

I have this code and i need to display numbers into aleatory order. i.e
[3,45,20,10,8......]. Can you help me? Thank you.

   $(function () {
        var $select = $(".left");
        for (i = 1; i <= 100; i++) {
            $select.append($('<input type="button"></input>').val(i).html(i));
        }
    });
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
Simona
  • 1
  • 1
    Can you clarify what the desired output is? Are you asking to build an array of random numbers? Or are you creating 100 buttons and want them displayed in a random order? – Adam Konieska Mar 28 '16 at 14:47
  • 3
    Put the values in an array and [shuffle it](http://stackoverflow.com/q/2450954/218196). – Felix Kling Mar 28 '16 at 14:47
  • A) And why do you need 100 buttons ? B) your questio say: "i need to display numbers into aleatory order". So, where do you want to put the output. – christian Mar 28 '16 at 14:51
  • I want to display 100 boxes numbered from 1 to 100 in a random order. – Simona Mar 28 '16 at 15:00

1 Answers1

0

To display 100 buttons randomly, you'd need to first generate a list of unique numbers, then order them randomly. @Felix King has a great suggestion about shuffling, and something like this would work:

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}


var values = [];

$(function () {
    var $select = $(".left");
  for (i = 1; i <= 100; i++) {
    values.push(i);
  }
  shuffle(values);
  for(var i = 0; i < values.length; i++) {
    $select.append($('<input type="button"></input>').val(values[i]).html(values[i]));
  }
});

You can see it working here: https://jsfiddle.net/igor_9000/hxuy531q/

Hope that helps.

Adam Konieska
  • 2,805
  • 3
  • 14
  • 27