Skip to content

Instantly share code, notes, and snippets.

@gukandrew
Last active September 6, 2024 14:55
Show Gist options
  • Save gukandrew/5d9659f72487540e3c793a5febbb0714 to your computer and use it in GitHub Desktop.
Save gukandrew/5d9659f72487540e3c793a5febbb0714 to your computer and use it in GitHub Desktop.
This Ruby code implements a custom shuffle function using the Fisher-Yates like algorithm
# Custom Shuffle Function in Ruby (Without Using shuffle)
# Description:
# This function takes an integer `n` as input and returns an array of numbers from 1 to `n`
# in a randomized order using the analog of Fisher-Yates algorithm (that runs forward, not backward as Fisher-Yates algorithm).
# The implementation avoids using Ruby's built-in `shuffle` method, ensuring a custom
# randomization approach that produces different sequences with no recognizable pattern.
def random_shuffle(n)
arr = (1..n).to_a
(0..n-1).each do |i|
j = rand(i..n-1)
arr[i], arr[j] = arr[j], arr[i]
end
arr
end
puts random_shuffle(5).inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment