|
From: Per W. <pw...@ia...> - 2003-06-19 07:09:07
|
No, your code would not work.
However, notice that you don't need 1000 random numbers. You want the
numbers 1-1000 with a random permutation.
Fill an array with the numbers 1-1000
Permutate the order of the elements.
for (i =3D 0; i < 1000; i++)
array[i] =3D i+1;
for (i =3D 0; i < 999; i++) {
// Swap ith element with a random element from the unsorted part.
n =3D rand()%(1000-n);
swap(array[i],array[i+n]);
}
Now the elements with be swapped a round but you are still guaranteed that
each element contains an unique value in the range 1-1000.
/Per W
On Thu, 19 Jun 2003, [iso-8859-1] Andr=E9 Mac=E1rio Barros wrote:
> Dear users,
>
> Regardless the intresting observations of bad randomness of the functi=
on
> rand(), I have a doubt too.
>
> Please consider the following piece of code:
> 1 -...
> 2- #include <iostream>
> 3 -#include <ctime>
> 4 -#include <cstdlib>
> 5 -...
> 6 -int main()
> 7 -{
> 8 - int a;
> 9 -
> 10 - srand(time(0));
> 11- for(int i=3D0; i<1000; i++)
> 12- {
> 13- cout << rand()%1000+1 << endl;
> 14- }
> 15- ...
> 16-}
>
> A)I use the argument of line 10 calling srand to make sure that the curre=
nt
> time
> gives me a safe different seed for srand;
> B)So, my command in line 13 will print 1000 numbers between 1 and 1000;
>
> My doubt:
> Will my cout on line 13 print 1000 ***DIFFERENT*** numbers? I don=B4t thi=
nk
> so!
>
> This is C++ code
>
> Regards
> Andre
>
>
>
>
> -------------------------------------------------------
> This SF.Net email is sponsored by: INetU
> Attention Web Developers & Consultants: Become An INetU Hosting Partner.
> Refer Dedicated Servers. We Manage Them. You Get 10% Monthly Commission!
> INetU Dedicated Managed Hosting http://www.inetu.net/partner/index.php
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www.noicys.cjb.net/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|