Sha256: 11cb1e3b7dae5c7e7cd8c3eea4878a7f64c47da509066b80f05d4d610aea759a

Contents?: true

Size: 721 Bytes

Versions: 16

Compression:

Stored size: 721 Bytes

Contents

=begin rdoc
  Permute the order of items in x.  Does not copy x -- shuffles the
  items in place.  Works for strings, arrays, any container that responds to
  length, [], and []=
=end

# :begin :permute! :random
  def permute!(x)
    for i in 0..x.length-2
      r = random(i, x.length-1)
      x[i], x[r] = x[r], x[i]
    end
    return x
  end
# :end :permute!

=begin rdoc
  A "helper method" for permute! that makes it easier to see which two
  locations are being swapped.  A call to random(i,j) returns a random
  integer in the range i..j.  See also PRNG::random
=end

# :begin :random
  def random(min, max)
    return nil if max < min
    range = max - min + 1
    return rand(range) + min
  end
# :end :random

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
rubylabs-1.0.2 lib/permute.rb
rubylabs-1.0.1 lib/permute.rb
rubylabs-1.0.0 lib/permute.rb
rubylabs-0.9.8 lib/permute.rb
rubylabs-0.9.7 lib/permute.rb
rubylabs-0.9.6 lib/permute.rb
rubylabs-0.9.5 lib/permute.rb
rubylabs-0.9.4 lib/permute.rb
rubylabs-0.9.3 lib/permute.rb
rubylabs-0.9.2 lib/permute.rb
rubylabs-0.9.1 lib/permute.rb
rubylabs-0.9.0 lib/permute.rb
rubylabs-0.8.3 lib/permute.rb
rubylabs-0.8.2 lib/permute.rb
rubylabs-0.8.1 lib/permute.rb
rubylabs-0.8.0 lib/permute.rb