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

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