Collection atRandom:

Lex Spoon lex at cc.gatech.edu
Fri Nov 21 20:45:28 UTC 2003


"Frank Shearar" <frank.shearar at rnid.org.uk> wrote:
> Date: Fri, 21 Nov 2003 13:09:01 -0000
> From: "Frank Shearar" <frank.shearar at rnid.org.uk>
> Subject: Collection atRandom:
> To: <squeak-dev at lists.squeakfoundation.org>
> reply-to: The general-purpose Squeak developers list <squeak-dev at lists.squeakfoundation.org>
> 
> Why is it that Collection>>random (is this the correct syntax?) calls
> #atRandom: yet Collection doesn't implement this message?
> 
> I would have thought you'd want to do something like
> 
> Collection atRandom: aGenerator
> 	^ self subclassResponsibility
> 

Well, why not this:

	^self asArray atRandom: aGenerator



This has O(n) complexity, unfortunately, but at least it will obviously
give correct results for any kind of collection.

I wish I could think of a better way to support this generically.  But
how?  The best I can think of is something like this:

	self emptyCheck.
	^self nthElement: (aGenerator nextInt: self size)

nthElement: uses #at: in subclasses that support it, and uses #do:
otherwise.  Since SequenceableCollection can use #at:, this approach has
a bonus that you could discard the method
SequenceableCollection>>atRandom: .


By the way, the atRandom: in Set does not look like it will give
uniformly distributed results.  It gives favor to entries in the
underlying hash table that have an empty entry immediately preceding
them.  This may well be useful, but it seems like it should have a
different name.  Maybe it could be called sloppyAtRandom: instead of
atRandom: ?

BTW who uses this method?!


-Lex



More information about the Squeak-dev mailing list