# NArray shuffle

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

if your na is not huge you might use:

harp:~ > cat a.rb
require 'narray'

na = NArray.int(3,2).indgen!

p na

idx = NArray.to_na Array.new(na.size){|i| i}.sort_by{ rand }

na[] = na[idx].reshape *na.shape

p na

harp:~ > ruby a.rb
NArray.int(3,2):
[ [ 0, 1, 2 ],
[ 3, 4, 5 ] ]
NArray.int(3,2):
[ [ 0, 3, 1 ],
[ 2, 4, 5 ] ]

which at least does it in one hit at the cost of space.

-a

···

On Thu, 7 Sep 2006, Patrick Hurley wrote:

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

--
what science finds to be nonexistent, we must accept as nonexistent; but what
science merely does not find is a completely different matter... it is quite
clear that there are many, many mysterious things.
- h.h. the 14th dalai lama

"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:

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

···

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: