ikarutsi ikarutsi - 1 month ago 11
Javascript Question

How to create 100 random numbers between 1 and 9999 with 4 digits, and place numbers in 10 rows of 10 numbers?

Having an issue figuring out how to get this solved, and I've searched and looked for answers, but they don't resemble what I'm looking for.
This is beginner stuff, I realize but any help would be highly appreciated.

The code below was given by my teacher and it works for creating one random number. For the life of me I can't figure out how to make this create 100 random numbers and make a 10 x 10 square of them.

eg. 5468 2367 1587 2587 2310 9802 0154 8753 4965 2571
3249 3248 2158 4659 1321 1278 9871 0123 4654 4587
etc. for 10 rows.

<div id="answer"></div>

<script type="text/javascript">
function giveValues() {
var length, zeroes;
var number = Math.round((Math.random() * 9999));

// toString()-method and lenght to set amount of digts
zeroes = 4 - number.toString().length;

for (var j = 1; j <= zeroes; j++) {
number = "0" + number;
}
return number;
}
document.getElementById("answer").innerHTML = giveValues();


I also know that there is if (j % nameofvar == 0) { for making a new line, but am unable to make that work.

zee zee
Answer

Considering that you haven't learned arrays yet, try the following as I think it's best inline with what you're looking for. Here is a Plunker as well http://plnkr.co/edit/LltYPtSfR9Ndo46kYmVN?p=preview.

<div id="answer"></div>

<script>
  function giveValues() {
    var length, zeroes;
    var number = Math.round((Math.random() * 9999));

    // toString()-method and lenght to set amount of digts
    zeroes = 4 - number.toString().length;

    for (var j = 1; j <= zeroes; j++) {
      number = "0" + number;
    }
    return number;
  }

  var columns = 10;
  var total = 100;
  var bigString = "";

  for (var i=0; i<total; i++) {
    if (i != 0 && i % columns == 0) {
      bigString += "<br/>";
    }
    bigString += giveValues(i).toString() + " ";
  }

  var answer = document.getElementById("answer");
  answer.innerHTML = bigString;
</script>