Ruby is a wonderful programming language, and when I say wonderful I mean that basically it just makes you happy. As a Java programmer, there are so many things that I need to check and be careful about, and Ruby just makes it easier for you, taking care of you, and if I have one more glass of wine I might get carried away and say that it almost spoils you, makes you lazy – cause now when I have to implement an algorithm, I’d rather do it in Ruby rather than Java, or even PHP, which is still easier, but with all the ugly $-signs (yes, I am lazy when it comes to hold the shift key and press ‘4’, who’s the dumb-a$$ that came up with that stupid idea anyways, ha ?)
One of the things I first do when starting to learn a programming language is implementing a few basic stuff, for example, the famous Tower of Hanoi:
def hanoi(disc, src, hlp, dst) if disc > 0 hanoi(disc-1, src, dst, hlp) puts "moving disc #{disc} from #{src} to #{dst}" hanoi(disc-1, hlp, src, dst) end end hanoi(3, 'src', 'hlp', 'dst')
It’s so beautiful to define factorial in one line:
def fact(n) (1..n).inject{|r,i| r*i } end
And then I usually continue to merge-sort:
# sorting the array from _start index to the _end index # using merge sort def mergesort(arr) # stop condition return arr if arr.count == 0 || arr.count == 1 # split the range mid = arr.count/2 # sort recursively both parts arr1 = mergesort(arr[0, mid]) arr2 = mergesort(arr[mid, arr.count-mid]) # and merge merged = [] max_i, max_j = [arr1.count, arr2.count] i = j = 0 while i < max_i && j < max_j if arr1[i] <= arr2[j] merged << arr1[i] i += 1 else merged << arr2[j] j += 1 end end # continue copying the rest: while i < max_i merged << arr1[i] i += 1 end while j < max_j merged << arr2[j] j += 1 end # return merged end arr = [2,3,4,5,6,1,7] puts mergesort(arr)
and if we didn’t have enough, let’s implement quicksort as well:
def quick(arr) return [] if (arr.size == 0) pivot = arr.pop left = Array.new right = Array.new arr.each { |i| if i < pivot left << i else right << i end } return quick(left) + [pivot] + quick(right) end a = [5,3,9,8,7,2,4,1,6,5] p quick(a)
The downside of coding in an unfamiliar language is that your’e still captured in patterns that are perfect for other programming languages, only that in this one – you can do things in a more elegant & efficient way.
Until next time…ta-ta!