Ruby · ruby excercise

Permutation – Ruby

Permutation:

This class has a dual purpose: It can be used to create permutations of a given size and to do some simple computations with/on permutations.

The instances of this class don’t require much memory because they don’t include the permutation as a data structure. They only save the information necessary to create the permutation if asked to do so.

STEP1: In case you are using Ruby 1.8.6 and previous versions then

Installation:

The library can be installed via rubygems:

c:\gem install permutation

Sample code:

require ‘Permutation’
perm = Permutation.new(3)
perm.map { |p| p p.value }
colors = [:r, :g, :b]
perm.map { |p| p p.project(colors) }
string = “abc”
perm.map { |p| p p.project(string) }

Output:

[0, 1, 2]
[0, 2, 1]
[1, 0, 2]
[1, 2, 0]
[2, 0, 1]
[2, 1, 0]
[:r, :g, :b]
[:r, :b, :g]
[:g, :r, :b]
[:g, :b, :r]
[:b, :r, :g]
[:b, :g, :r]
“abc”
“acb”
“bac”
“bca”
“cab”
“cba”

STEP 2:

If you are using Ruby 1.8.7 and above then no need to install the gem.

CODE:

[1,2,3].permutation(3){|x| p x}

Output:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]