Last active
September 6, 2024 14:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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