NArray shuffle

P

Patrick Hurley

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
 
A

ara.t.howard

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,431
Messages
2,571,679
Members
48,796
Latest member
Greg L.

Latest Threads

Top