shuffle関数

30分プログラム、その117。配列をシャッフルする関数。
久しぶりにシンプルな課題。こういうのを考えるのは結構好きなのです。

使い方

$ ruby shuffle.rb 1 2 3 4 5 6 7
[4, 1, 3, 5, 7, 2, 6]

ソースコード

先頭から順にみていき、それを後続のどれかと入れかえる戦略で。

#! /opt/local/bin/ruby -w
# -*- mode:ruby; coding:utf-8 -*-
#
# shuffle.rb -
#
# Copyright(C) 2007 by mzp
# Author: MIZUNO Hiroki <hiroki1124@gmail.com> 
# http://mzp.sakura.ne.jp/
#
# Timestamp: 2007/08/27 22:51:07
#
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Ruby itself.
#

def rand_range(min,max)
  rand(max-min+1)+min
end

module Enumerable
  def shuffle
    size = self.to_a.size
    a = self.to_a.dup
    self.each_with_index{|_,i|
      j = rand_range i,size-1
      a[i],a[j] = a[j],a[i]
    }
    a
  end
end

p ARGV.shuffle.map{|x| x.to_i}