Thursday, April 2, 2009

More about Ruby - Briefly

Ok, I'm also training some gifted students at UWF to be competitive programmers, that means that I need to find some nice problems to solve, solve them myself and see how it goes.

Let's try something fancy - The Problem of having two jugs with different integer capacities and a target volume that has to be reached by filling/emptying jugs or pouring the content of one jug into the other - with the minimum number of operations, of course!

It's important to know how to do that, in case you have to prevent a bomb from exploding!

In principle it's clear how to do it with Jugs with an arbitrary capacity (> 0) and an arbitrary target value: Exhaustive search (breadth-first) through all the states and hope for the best.

The actual implementation is a bit nasty, because you need to "ariadne-thread" all the states together to their immediate predecessors before placing them in the queue, so let's come up with a Queue class first.

Ok! There actually is one, but it's always nice to check how you would do that in your host language - let's base it on arrays then:
class Queue
def initialize
@a = []
end

def enqueue(x)
@a << x
end

def dequeue
@a.delete_at(0)
end

def empty?
@a.empty?
end
end
Looks quite simple! These Ruby arrays are pretty flexible. If I could only remember to place this pesky ampersand in front of my instance variables! How may run-time errors did I get by omitting that.

I'm not really crazy about static typing, so I think most errors are not really type-related in reality (well, maybe one or two a year).

I love how Smalltalk lets you deal with identifiers: you have to declare them and there's no way I can sneak in a variable by misspelling the name! In Ruby I find such a problem at run-time, but I guess that's how you're supposed to learn it...

No comments:

Post a Comment