Pick n random elements from a list?

1,202 views
Skip to first unread message

DFectuoso

unread,
Jul 8, 2009, 2:03:27 AM7/8/09
to Lift
Hi!

I have a list, lets say its List.range(1,100) and i want to pick n
random elements from it.

Basicly I know that i can create n diferente randon numbers inside the
limits and pick each element, but that would look something like this

store List.range(1,100);
store randonNumbers generated by a function;
foreach(randonNumber){
get number from the list into a new list


So before I started coding that, i decided I need to stop thinking in
php and start thinking in scala, i want a code that looks like

List.range(1,100).shuffle take n

So i did some poking around in scala and found that scala 2.8 theres a
util.Random.shuffle so i could do

util.Random.shuffle(List.range(1,100)) take 3

Close enought... but... it doesnt work in lift using scala 2.7.5

So before spending more time I wanted to check if you guys had a quick
way to do this "the scala way"

Thanks!



Miles Sabin

unread,
Jul 8, 2009, 4:20:33 AM7/8/09
to lif...@googlegroups.com
On Wed, Jul 8, 2009 at 7:03 AM, DFectuoso<santia...@gmail.com> wrote:
> So i did some poking around in scala and found that scala 2.8 theres a
> util.Random.shuffle so i could do
>
> util.Random.shuffle(List.range(1,100)) take 3
>
> Close enought... but... it doesnt work in lift using scala 2.7.5
>
> So before spending more time I wanted to check if you guys had a quick
> way to do this "the scala way"

Isn't the source of object scala.util.Random from 2.8.0 good enough?

// Backported to collections < 2.8.0
def shuffle[T](seq: Seq[T]): Seq[T] = {
val buf: Array[T] = seq.toArray

def swap(i1: Int, i2: Int) {
val tmp = buf(i1)
buf(i1) = buf(i2)
buf(i2) = tmp
}

for (n <- buf.length to 2 by -1) {
val k = nextInt(n)
swap(n - 1, k)
}

buf.toSeq
}

Cheers,


Miles

--
Miles Sabin
tel: +44 (0)7813 944 528
skype: milessabin
http://www.chuusai.com/
http://twitter.com/milessabin

Reply all
Reply to author
Forward
0 new messages