[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

NArray shuffle

Patrick Hurley

9/6/2006 6:07:00 PM

Has anyone ever needed to "shuffle" an NArray? I can certainly convert
it to an array and do the sort_by {rand} idiom, and then convert it
back. I currently:

na.size.times do
p1,p2 = rand(na.size),rand(na.size)
na[p1],na[p2] = na[p2],na[p1]
end

which works, but I wondering if anyone knew a better way.
Thanks
pth

3 Answers

Ara.T.Howard

9/6/2006 8:29:00 PM

0

Daniel Martin

9/6/2006 9:05:00 PM

0

"Patrick Hurley" <phurley@gmail.com> writes:

> Has anyone ever needed to "shuffle" an NArray? I can certainly convert
> it to an array and do the sort_by {rand} idiom, and then convert it
> back. I currently:

What about:

shuffled = orig[NArray.float(*orig.shape).random!.sort_index]

--
s=%q( Daniel Martin -- martin@snowplow.org
puts "s=%q(#{s})",s.map{|i|i}[1] )
puts "s=%q(#{s})",s.map{|i|i}[1]

Patrick Hurley

9/6/2006 10:25:00 PM

0

On 9/6/06, Daniel Martin <martin@snowplow.org> wrote:
> "Patrick Hurley" <phurley@gmail.com> writes:
>
> > Has anyone ever needed to "shuffle" an NArray? I can certainly convert
> > it to an array and do the sort_by {rand} idiom, and then convert it
> > back. I currently:
>
> What about:
>
> shuffled = orig[NArray.float(*orig.shape).random!.sort_index]
>
> --
> s=%q( Daniel Martin -- martin@snowplow.org
> puts "s=%q(#{s})",s.map{|i|i}[1] )
> puts "s=%q(#{s})",s.map{|i|i}[1]
>
>

Thanks Daniel, that is perfect -- I did not know you could index an NA
with an Array that way -- its perfect for my needs (plus it keeps the
type of the Array).

pth