klog

logging out my thoughts views experiments

Permutation using ruby
Tuesday January 04, 2011
Kunal Modi
Since high school, I found the problems involving permutation and combination very interesting. The ones involving sequence are of real great interest to me. Today I tried to put down a small ruby script that can permute through an array of letters and return back all possible permutation without repetition of letters. For example, 'a', 'b', 'c' would give out abc, acb, bca, bac, cba, cab.
I have used recursion to solve the problem. You can find the complete script at github
The crux of the script is the else part which initiates recursion
def permute available,used
	if available.size == 1
		puts used.join + available.pop
	else
		available.each{|char|
			temp_used = Array.new(used)
			temp_used.push char
			new_available = @global - temp_used
			permute new_available,temp_used
		}
	end
end

At each call to the permute method, the else part iterates over the available chars and proceeds with only the one which are not used. before in the string.
I was excited to see how elegantly ruby code can solve such a small problem and at the same time make it human readable.

This is a test post
Monday January 03, 2011
Kunal Modi
Matter coming soon