🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.programming.contests
Article #4

Re: Random Numbers

#4
From: A. van Kessel
Date: Wed, 01 Nov 1995 10:45
54 lines
2504 bytes
chrisw@leland.stanford.edu (Chris Wilkins) wrote:
>In article <4745p3$62h@umbc9.umbc.edu> schlein@umbc.edu (Jonas J. Schlein) writes:
>
>>>> I have 13 array locations. Let's call them: n[0], n[1], n[2],....,
>>>> n[12]. I want to RANDOMLY fill those locations with integers
>>>> from 0 to 12. 
>
>>> Why not do something like this:
>>> 
>>> for(i = 0; i < 13; i++)
>>>    n[i] = i;
>>> 
>>> for(i = 0; i < 13; i++) {
>>>    s = random_number_from_0_to_12();
>>>    swap(n, i, s);
>>> }
>
>>Actually if you go strictly by what my Algorithms Professor says is a
>>better way (he's a crypto man so I won't argue with him on that) for a
>>random distribution would be to replace your random_number_from_0_to_12()
>>with random_number_from_0_to_i(). Also you can then start the second
>>for loop at 1 to avoid the unnecessary initial sway of n[0] with itself.
>
>This sounds seriously wrong. I think what you meant is that you count DOWN 
>through the array swapping each element with one of the remaining elements or 
>itself (with equal probabilities). All this was covered in the shuffling 
>algorithm thread a couple of days ago.
>
>Chris
All too dangerous: just fill an extra array with N random numbers, and sort.
A bit decadent to sort on random, but very robust.
like :
*/
typedef struct iter_ {
	int num;
	int val;
	} ITER;
ITER array[N};
for(i=0; i <N; i++)	{
	array[i].num = i; /* or i+1 if you want ;-) */
	array[i].val = some_random();
	}
int iter_cmp(ITER *l, ITER *r)
{ if (l->val == r->val) return 0;
else return l->val - r->val; /* or the other way around */
}
qsort( array, N , sizeof array[0] , iter_cmp ); /* too lazy to cast ... */

for(i=0;i< N; i++)
	printf("%d : %d\n", i, array[i].num );

/*
Yours randomly,
Adriaan van kessel
Technical Details
Message-ID: <DHD1w9.JC4@rivm.nl>
Path: arc1-ca.pugleaf.net!EU.net!sun4nl!rivm!news
References: <46qte7$hbv@btmpjg.god.bel.alcatel.be> <46r395$2tp@fido.asd.sgi.com> <4745p3$62h@umbc9.umbc.edu> <chrisw.282.0017FC83@leland.stanford.edu>

Show Full Headers
Complete Article Headers
Newsgroups: comp.programming.contests,comp.lang.c
Path: arc1-ca.pugleaf.net!EU.net!sun4nl!rivm!news
From: "A. van Kessel" <imaavk>
Subject: Re: Random Numbers
Content-Type: text/plain; charset=us-ascii
Message-ID: <DHD1w9.JC4@rivm.nl>
To: chrisw@leland.stanford.edu
Sender: news@rivm.nl
Content-Transfer-Encoding: 7bit
Organization: Rijksinstituut voor Volksgezondheid en Milieuhygiene, Bilthoven, NL
References: <46qte7$hbv@btmpjg.god.bel.alcatel.be> <46r395$2tp@fido.asd.sgi.com> <4745p3$62h@umbc9.umbc.edu> <chrisw.282.0017FC83@leland.stanford.edu>
Mime-Version: 1.0
Date: Wed, 1 Nov 1995 10:45:44 GMT
X-Mailer: Mozilla 1.1N (X11; I; OSF1 V3.0 alpha)
X-Url: news:chrisw.282.0017FC83@leland.stanford.edu