Re: A82: Random routine


[Prev][Next][Index][Thread]

Re: A82: Random routine




Hello,
I think rather than using a routine which picks cards out of an array by
generating a random sequence of indices, you should perhaps step through
the array and make random swaps between cards. This kinda mimicks the
physical shuffling procedure. More importantly it's guaranteed to finish
in O(n) time (where n is the number of cards). That is, it will take time
directly proportional to the number of cards you're sorting.
Picking random numbers and then checking to see that they're valid could
take O(n^2) time (assuming that your random number generator has perfectly
even distribution, if not the search may possibly never stop).
Assuming the card types are uniquely identified by a single byte and that
they're in a 20 byte array which starts at "cards", I might write
something along the lines of the following:

	ld a,r
	ld e,a
	ld hl,cards
	ld b,20
loop:
	ld a,b
	ld d,0
	ld e,(de)	; this must be a relatively random value [0,255]
	ex de,hl
	add hl,hl
	add hl,hl
	ld b,h \ ld c,l
	add hl,hl
	add hl,hl
	add hl,bc
	ld l,h
	ld h,0		; hl is between 0 and 19
	ld bc,cards
	add hl,bc
	ld b,a
	ld c,(hl)	;
	ld a,(de)	;
	ld (hl),a	; the swap
	ld a,c		;
	ld (de),a	;
	ex de,hl
	inc hl
	djnz loop

I'm making this up on the spot so there's bound to be something wrong with
it. The concept should be okay though. You should leave the cards in the
order that they appeared in the previous game. Also, I'm not sure about
the values on page 0 of memory. Pick a different page if they turn out to
be no good.

-Jeremy

On Sun, 5 Dec 1999, Doug Torrance wrote:

> 
> Hi!  My next game, Concentration (the memory game where you flip over cards, 
> trying to remember where each of them is to form pairs) is almost done.  One 
> final thing I need to do is shuffle the cards at the beginning, so they're 
> in nice random order.  There's 10 different kinds of cards, and 2 of each, 
> so I need a routine that will output 20 numbers, from 1 to 10, each occuring 
> exactly twice.  Any suggestions?
> 
> Thanks!
> Doug
> 
> ______________________________________________________
> Get Your Private, Free Email at http://www.hotmail.com
> 



Follow-Ups: References: