[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: not enough real programmers?
On 9 Aug 1999 10:36:31 GMT, don@news.daedalus.co.nz (Don Stokes)
wrote:
>Everett M. Greene <mojaveg@ridgecrest.ca.us> wrote:
>>> 4. "Write a program to perform a "perfect shuffle" on an array of 52
>>> numbers."
>>Anybody with a good answer to question 4 doesn't need to be interviewing
>>for a job. There are any number of companies, academic institutions,
>>etc. who would like a definitive answer to that problem.
>Huh? Assuming "perfect" means "within the parameters of he system's
>random() function",
> void
> shuffle(int array[52]) {
> int tmparray[52], done[52];
> int i,j;
> for(i = 0; i < 52; i++) {
> tmparray[i] = array[i];
> done[i] = 0;
> }
> for(i = 0; i < 52; i++) {
> for(j = random() % 52; done[j];)
> if(++j == 52) j = 0;
> array[j] = tmparray[i];
> done[j] = 1;
> }
> }
>works for me. (It's much shorter if the routine is allowed to pick its
>own values -- if I know the values are 1..52, I can use the target array
>as my "done" array, and I don't need the temp array. That's what I get
>after five minutes of codiong, anyway.)
>(do I get the job?)
>-- don
Try:
/* shuffle n items -- swap end items with random selection */
/* for n items from end to start while more than one left */
for (lastp = data + n - 1, items = n;
items > 1;
--lastp, --items)
{
/* select random item from those remaining */
selectp = data + rand() % items;
/* swap selected item with last item */
temp = *selectp;
*selectp = *lastp;
*lastp = temp;
}
Thanks. Take care, Brian Inglis Calgary, Alberta, Canada
--
Brian_Inglis@CSi.com (Brian dot Inglis at SystematicSw dot ab dot ca)
use address above to reply