DEV Community

Linuxander
Linuxander

Posted on

Fisher-Yates shuffle algorithm with Ruby

The simplest shuffle algorithm, Fisher-Yates, is widely used and easy to implement. I personally used it to create a card game in Sinatra:

# Fisher-Yates Shuffle Algorithm

module FisherYates

  def self.shuffle(numbers)
    n = numbers.length
    while n > 0 
      x = rand(n-=1)
      numbers[x], numbers[n] = numbers[n], numbers[x]
    end
    return numbers
  end

end
Enter fullscreen mode Exit fullscreen mode

So let's imagine you want to use it in your Rails app, you could do something like this:

  def initialize(numbers)
    shuffle = FisherYates.shuffle(numbers)
    return shuffle.inspect
  end
Enter fullscreen mode Exit fullscreen mode

If you want to test this script from shell, add this after FisherYates, and save as shuffle.rb. Add numbers as arguments, or just execute script to shuffle defined numbers from array:

  @numbers = [1,2,3,4,5,6,7,8,9,10,12,13,14]

  if ARGV.empty?
    puts FisherYates.shuffle(@numbers).inspect
  else
    puts FisherYates.shuffle(ARGV).inspect
  end
Enter fullscreen mode Exit fullscreen mode

Without inspect you would get each number in separated line, but with inspect we receive array of numbers printed in terminal.

Top comments (0)