# Thread: need help coding a while or for loop

1. Registered User
Join Date
Aug 2006
Posts
307

## need help coding a while or for loop

i've tried many approaches but none work well enough,
here is psuedocode of what i'm trying to do...

var intMax = 3;
var intStart = 0;
var intStop = 10;
var arrPicks = [];

for( var i = 0; i < 1000; i++ ){

//1. pick a random number from [intStart] to [intStop]
//2. add the random number to arrPicks but only if it is unique
//3. once i have intMax unique number between [intStart] and [intStop]
//4. use document.write() to write each of the numbers to the screen
//5. increase intStart and intStop by 10 each

}

if intMax = 5, then is should get 5 unique numbers between 0 and 10, then another 5 unique numbers between 10 and 20, etc

like this...

0
3
7
8
9
.
.
.
11
15
18
17
13
.
.
.
20
25
28
23
24

note: i should get exactly 5 unique number all the way up to 1000, they don't have to be in numerical order, but there must be 5 or whatever intMax numbers returned.

so if intMax is 3, i should get 3 x 100 = 300 unique numbers,
if intMax is 7 i should get 7 x 100 = 700 unique numbers

i'm thinking a while loop would be ideal since it could keep trying until it has found for example 3 unique for every block of 10 numbers, and it can document.write() to the screen after each unique number and discard duplicates.

i'll adjust the script to add leading zeros i.e. 005,023,etc as each number must be 3 digits.

my end goal is to pick x amount of numbers from every 10 numbers between 000 and 999.

can somebody please assist with the code, i can easily understand the code and modify it, but this one is eluding me,
and i need this code asap.

thanks for assisting!

2. Sounds like homework. I'll help you fix code, but I won't do your homework, no offense.

3. You can't use document write to write to the page for two reasons.

1. it replaces what is currently in place
2. can only be used while the page is loading, when the page load is completed, the situation regarding point 1. comes in to being.

Well here are some pointers, if you can i++ then you can i+= and the rest is up to you to figure out...

4. Registered User
Join Date
Aug 2006
Posts
307
Homework? seriously?

My profile says Join Date: Aug 2006, Posts: 293.

I've been coding for 10+ years in html, css, javascript, php and jquery, and some autohotkey macros.

javascript was my first language, long before people learned about unobtrusive coding and seperating html form css from javascript and responsive coding and all the rest, i'm just not big on while loops, much better at for loops, and docuemnt.write will work as long as the loop is running i.e. as the page is loading, otherwise i could store them in comma separated list or array.

i have decided on much more efficient approach though, i'll run from 1-1000 in a single loop pick [x] unique per block of 10 numbers and manually round the pointer up to the nearest 10. So i'll just keep adding a small random number probably between 1 and 3, and then roun dthe pointer up to the nearst tenth, i already know how to check for uniques and all that so i'm good, thanks guys. was just in a rush to get a quick solution.

5. Sorry, it just looked like homework. Don't take it personally.

This is how I might do it.

Code:
```var intMax = 5, intCur = 0;
var intStart = 0, intStop = 10, intInc = 10;
var maxIter = 50, curIter;
var arrPicks = [];
var tmpNum;

function getRand(min, max) {
// from min to max, inclusive
return Math.floor( Math.random() * (max - min) ) + min + Math.floor( Math.random() + 0.5 );
}

// sort function
function sub(a, b) {
return a - b;
}

for (curIter = 0; curIter < maxIter; curIter += intInc, intCur = 0, intStart += intInc, intStop += intInc) {
while (arrPicks.length < intMax) {
tmpNum = getRand(intStart, intStop);
if ( arrPicks.indexOf(tmpNum) === -1) {
arrPicks.push(tmpNum);
}
}
console.log( arrPicks.sort(sub).join(', ') );
arrPicks.length = 0;
}```
Last edited by tenfold; 09-30-2013 at 08:49 PM.

6. Registered User
Join Date
Aug 2006
Posts
307
I didn't, it's common for coders to not want to do homework for newbies, and it's the right thing to do. Thanks for your solution and give it a whirl and modify as needed, really appreciate your time.

7. Hi, here is my shot at it.

The randomization of the array members could probably be improved on, but at least everything is unique and within the correct ranges:

Code:
```var
intMax   = 5,
arrPicks = [9, 7, 5, 3, 1, 0, 2, 4, 6, 8],
i, j;

for (i = 0; i < 1000; i += 10) {
arrPicks.sort(function(){return Math.round(Math.random()) ? 1 : -1;});
if (i) {document.write('.<br />.<br />.<br />');}
for (j = 0; j < intMax; ++j) {
document.write((arrPicks[j] + i) + '<br />');
}
}```
Example output:

Code:
```2
3
9
7
6
.
.
.
13
10
12
19
17
.
.
.
29
27
23
22
20
.
.
.
32
31
39
37
33```
Last edited by bionoid; 10-01-2013 at 05:10 PM.

8. Registered User
Join Date
Aug 2006
Posts
307
Thanks again to tenfold, but your code didn't work for me, but i'm stuck using IE7 at work and will still try it when i get home, i commented out the console.log() and repalced it with document.write() to no avail, so i'll try it later in a modern browser with the console.log()

@bionoid your code works perfectly and is really compact and elegant, i just need to put in and if else to prepend leading zeros to make them all 3-digits, but i can handle that.

Question: Does javascript have a built in function to format numbers to include leading zeros?

I'll have a shot at commenting what's happening for others that may not be able to decode what's going on...

var intMax = 5,
arrPicks = [9, 7, 5, 3, 1, 0, 2, 4, 6, 8],
i, j;

//loop up to 1000 times, but we're counting in 10's, so 1000/10 means 100 actual loops,
//the inner loop prints 5(intMax) numbers to the screen on each pass of the outer loop

for (i = 0; i < 1000; i += 10) {

//sort/shuffle the array of single digit numbers on each pass,
//don't quite understand the custom sort function though
//i'm assuming it doesn't randomize the elements and maybe
//just randomly reverses the sort order on each pass

arrPicks.sort(function(){return Math.round(Math.random()) ? 1 : -1;});

//if 'i' is true/truthy i.e. not equal to zero or 1000 skip the 3 dots,
//otherwise print the 3 dots on each pass, noting that we are incrementing
//in tens i += 10 on each pass, this is why the dots don't get printed
//before the first group, but does appear between each group(cool technique)
//i'd have probably used if(i != 0 ), smiles

if (i) {document.write('.<br />.<br />.<br />');}

//inner loop prints the first 5 elements of the shuffled array
for (j = 0; j < intMax; ++j) {
//add 'i' to the respective element of arrPicks and print to screen
document.write((arrPicks[j] + i) + '<br />');
}
}

Many thanks again, perhaps you can elaborate on what's actually happening
in the custom sort portion, what's actually happening to the elements here?
i really wish javascript came with a .shuffle() method:

arrPicks.sort(function(){return Math.round(Math.random()) ? 1 : -1;});
Last edited by bsmbahamas; 10-01-2013 at 06:31 PM.

9. wow, don't tell anyone... but you have more comments in this 5 line snip of code than I have in my 1000 line code file :P

A slight adaptation to my first post, includes prototyping the functionality that you wished for:

Code:
```Array.prototype.shuffle = function()
{
this.sort(function()
{
return Math.round(Math.random()) ? 1 : -1;
});
};
{
return new Array((size + 1) - String(this).length).join(0) + this;
};

var
intMax   = 5,
arrPicks = [9, 7, 5, 3, 1, 0, 2, 4, 6, 8],
i, j;

for (i = 0; i < 1000; i += 10) {
arrPicks.shuffle();
if (i) {document.write('.<br />.<br />.<br />');}
for (j = 0; j < intMax; ++j) {
document.write((arrPicks[j] + i).leadZero(3) + '<br />');
}
}```
Example output:

Code:
```005
007
009
001
003
.
.
.
015
019
017
013
010
.
.
.
025
029
027
023
020
.
.
.
035
039
037
030
033```

10. Originally Posted by bsmbahamas
Thanks again to tenfold, but your code didn't work for me, but i'm stuck using IE7 at work and will still try it when i get home, i commented out the console.log() and repalced it with document.write() to no avail, so i'll try it later in a modern browser with the console.log()
Ah, IE. Yeah that's why it isn't working. IE7 doesn't have Array.prototype.indexOf
A local version can be used, though, replicating the functionality of it.

Try this: http://pastebin.com/mGghxqXw
It looks big, but the logic part of it is quite clear. That's what matters to me (readability), not just short code.
And, of course, switch console.log out for whatever else you need, if it isn't available in the browser.

11. Registered User
Join Date
Aug 2006
Posts
307
thanks for the update tenfold, figured it was IE7 not supporting something.

12. Registered User
Join Date
Aug 2006
Posts
307
lots of comments but only for the sake of clarity, wouldn't put all that into an actual script, just to help others that may not understand the code.

thanks for prototyping in the functionality, can you explain what is happening in the custom sort function? This part here:

sort(function(){
return Math.round(Math.random()) ? 1 : -1;
});

what's happening in plain english, is it if the result of Math.random() is rounded is truthy(not zero) then return 1 otherwise return 1?

and if so what does sort do when 1 or -1 is passed in, never could wrap my head around the custom sorting.

= )

13. Hope you don't mind me answering it like this:

The sort method sorts the Array object in place; no new Array object is created during execution.

If you supply a function in the sortFunction argument, it must return one of the following values:

* A negative value if the first argument passed is less than the second argument.
* Zero if the two arguments are equivalent.
* A positive value if the first argument is greater than the second argument.
Reference: http://msdn.microsoft.com/en-us/libr...=vs.94%29.aspx

I am asking for a random value that is rounded to give me either 0 or 1 (false/true), then using a ternary expression to shift array elements up or down.

Reference: http://msdn.microsoft.com/en-us/libr...(v=vs.94).aspx
Last edited by bionoid; 10-02-2013 at 01:50 PM.

14. Registered User
Join Date
Aug 2006
Posts
307
Thanks again bionoid that works just fine, somehow it seems easier to understand the way you just said it. Thanks for the links too, i'll be sure to read them over right now as that will come in handy.