Created
April 26, 2013 09:52
-
-
Save myy/5466168 to your computer and use it in GitHub Desktop.
1からNまでの整数をランダムに並び替える
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
# -*- encoding: utf-8 -*- | |
# 2012/11/01 | |
# 1からNまでの整数をランダムに並び替える | |
# 上限値Nを入力してもらう | |
puts "並び替えたい数の上限値を入力してください" | |
max = gets.to_i | |
# 並び替え前の数字が入る配列と並び替え後の配列を用意する | |
before = Array.new(max) | |
after = Array.new(max) | |
# 1からmaxを配列beforeに入れる | |
for i in 1..max do | |
before[i-1] = i | |
end | |
# 1からNの数字をランダムな順序に並び替える | |
j = 0 | |
while before.length > 0 do | |
r = rand(before.length) | |
after[j] = before[r] | |
before.delete_at(r) | |
j += 1 | |
end | |
# 並び替えた数字を出力する | |
puts "並び替えました" | |
after.each_index { |i| | |
puts after[i] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment