1 Replies - 1664 Views - Last Post: 29 December 2011 - 05:20 PM

#1 erik.price   User is offline

  • D.I.C Lover
  • member icon

Reputation: 486
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Randomly Shuffle an Array

Posted 24 November 2009 - 04:22 PM

Description: Simple returns a shuffled variation of the array that is passed to it. Could be useful for testing sorting algorithms (because you don't want to randomly arrange of 200 elements by hand
def shuffle(arr)
  for i in arr
    rand = rand(arr.length)
    tmp = arr[i]
    arr[i] = arr[rand]
    arr[rand] = tmp
    #this loops through the array and sets every index to another random one
  end
  return arr
end


#Example usage

array = 0..10
array = array.to_a

puts 'Before Shuffling: '
for k in array
  print "#{array[k]} "
end

array = shuffle(array)

puts "nAfter Shuffling: "
for j in array
  print "#{array[j]} "
end

#Output (yours will be different)

#Before Shuffling: 
#0 1 2 3 4 5 6 7 8 9 10 
#After Shuffling: 
#5 3 0 4 10 8 6 2 7 1 9


Is This A Good Question/Topic? 0
  • +

Replies To: Randomly Shuffle an Array

#2 Karel-Lodewijk   User is offline

  • D.I.C Addict
  • member icon

Reputation: 454
  • View blog
  • Posts: 864
  • Joined: 17-March 11

Re: Randomly Shuffle an Array

Posted 29 December 2011 - 05:20 PM

Ruby Array class at least as of 1.9 has shuffle and shuffle! member functions.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1