0

I have an array of 100 random numbers between 1 and 49.

I would like to print out the array in rows of twelve elements, instead of printing the array in a single line.

Here is the code I have

<script type ="text/javascript">
 var arr = [];
 for (var i = 0, l = 100; i < l; i++) {
     arr.push(Math.round(Math.random() * 49)+1)
 }
 document.write(arr);
 document.write("\n");
</script>

I need to print the array in rows with 12 elements per row and also need to find the smallest element in the array.

2
  • 2
    Did you try something ? Like having a counter for example ? Commented Sep 1, 2013 at 14:07
  • 1
    Just change \n to <br />. But you should really avoid using document.write() and use proper DOM manipulation instead. Commented Sep 1, 2013 at 14:30

2 Answers 2

1

You could try using splice:

while (arr.length > 0) {
    document.write(arr.splice(0, 12))
}

However, after running that code the array will be []. If you don't want to modify the array, use slice instead:

for (var i = 0; i < arr.length; i += 12) {
    document.write(arr.slice(i, i + 12))
}
Sign up to request clarification or add additional context in comments.

Comments

0

This would be the conventional way of doing it. The array is reset however. Let us know more detail on your requirements.

 var arr = [];

function getRandom( num ){
    return Math.round(Math.random() * num)+1;
}

var counter = 0;

 for (var i = 0; i < 100; i++) {
     arr.push(getRandom( 49 ));
     counter++;

     if( counter >= 12 ){
         document.write(arr);
         document.write("<br/>");
         arr = [];
         counter = 0;
     }

 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.