Ruby selection sort.

The general idea behind selection sort is, finding the least element in an array and exchanging it with the item in the first position of that given array.  Two loops are used. The outer one  shows where we are in the array and the second finds the smallest element between the current array item and the last item. Any time the smallest element is found its exchanged with the outer loops current variable. By the end every execution of an inner loop the items to the left are sorted in order leaving the right side unsorted.

1  a = [ 5,2,1,7,4,3]

2  (a.size-1).times do |i| #produces the indexes of the array elements
3    min = i  #the current item is concidered or assumed to be the smallest
4      (i+1).upto(a.size-1) do |j|  #scan from a[j+1 ... size-1]
5        if a[j] < a[min]
6          min = j        #update new minimum value
7        end
8      end
9    temp = a[i]       #the code below is to swap the
10    a[i] = a[min]     #elements.
11    a[min] = temp
12  end

13  puts a

challenge #6 display a chess board

I do not know but i know dear reader that you have seen a programming problem like this one ;

***        ***

***

***        ***

The program displays something in the form of a chess board where the * are the black boxes and the spaces are the white boxes.

To solve this using Ruby, we need two loops. One for the outer loop and other loop for the inner loop. Horizontally, number the boxes as number in increasing order. We achieve that by adding the variables of the two loops. If the result of the addition divided by 2 gives us 0 then the loop we print spaces to represent a white space else we print *.

In the code, the second loop is used duplicate the print out. Remove it and see how it work.

1  outer = ARGV[0].to_i
2  inner = ARGV[1].to_i

3  outer.times do |j|
4    3.times do
5       1.upto(inner) do |i|
6          if (j+i)%2 == 0
7               print “    “
8          else
9               print “****”
10          end
11       end
12      puts
13    end
14  end

My First C program

I remember almost five years back, i met a group of programmer friends who dared not to write any C code because they considered it some sort of black art reserved for only brainy and guru programmers. But through a series of enlightenment now i have put all those thoughts behind me. I have started programming in C and this is my first program. I am not saying the road is going to be smooth, that i know, but i am just saying, i do not see myself relenting in my efforts to program the best of C and Ruby that i can.

1  /* This is an hello world program */
2  #include <stdio.h>

3  int main(void)
4    {
5      printf(”Hello World\n”);
6      return 0;
7    }
To compile the code, cc -c

To make it executable, cc -o hello hello.c

To run it ,  ./hello

Ruby String.chomp Remix

While i was sitting down playing with regular expressions, i decided to write a small application String  chomp method my way. If perhaps you wanted to remove all whitespaces within and around a string you would have to do it using strip and squeeze methods but the same effect can be achieved by using regular expressions. It even works with n or t etc.

First, we scan for words with w+ and join them with a single space.

1  #Building my own chomp

2  class String
3    def bchomp
4      self.scan(/w+/).join(’ ‘)
5    end
6  end

Ruby color console output

There seems to be a growing demand on ways to do console output with color. That is fine by me. I just discoverd about ncurses and from what i see it looks promising. I am going out to try it.

Accra.rb

Ruby, and nice,modern and interesting language to program in has caught the attention of some programmers in Ghana. Thus the formation of Accra.rb(Accra is the capital city of Ghana.) We intended to form this programming group to share knowledge about Ruby and also spread the good news about ruby. Currently we are just a handful of members and we just had our first meeting on the 16th of Feb,2008. I hope and know this group will have a long way to gooooooooo.

challenge #5 Ruby Bubble Sort

Today, i sat up to write a bubble sort in ruby. This is how it goes. First things first. We device a way to find the largest number by comparing the each element with the next. Then we swap them if they are not in ascending order. After the first iteration the biggest number will be the last in the array. Bring another loop (outer) will help us sort it but the problem is that, we will still go through the array even if the array is already sorted. Therefore, before the beginning of the program we assume there is swaping to be done. Swap therefore is true. If there is a swap then swap, then there is probably some more things unsorted in the array. But if it happens that there were no swap the (break).

1  a = [1,1,1,1,1]

2  (a.size).times do
3    swap = true
4      (a.size-1).times do |i|
5        if a[i] > a[i+1]
6          temp = a[i]
7          a[i] = a[i+1]
8          a[i+1] = temp
9          swap = true
10        end
11       break if swap == false
12    end
13  end

14  puts a

As its said, the best way to understand this is to sometimes follow it with paper and pen. It really does help. I hope to hear comments from you so as to shape my writing styles.

Recursive Linear Search #2

So, the code for the first search was OK, but will curtainly not help an non ruby programmer. So i have decided to modify it a bit. This time, instead of using the begin…..rescue…….end statement we maintain a state of our position with respect to the last position.

1  a = [1,2,3,4,5,4]

2  def find(array,position,key)
3    if position >array.size
4      puts  “#{key} not found”
5    elsif key == array[position]
6     puts “Found #{key}”
7    else
8      find(array,position+1,key)
9    end
10  end

11  find(a,0,4)

Hope this is better. I am thinking of writing on a ruby bubble sort.

Don’t be hard on yourself

    Beginning programming is fun to say the least but sometimes, it can become very frustrating. One may come accross a programming challenge that he/she may like to solve but just can’t solve it. Its not because you are dumb, nor is it that you can not think well or that programming was not meant for you. Its just because like a child you are in your formative years of programming and as such there will be times you will fall. I normally go through this phase from time to time and i even sometimes feel depressed but i have come to realise that it is not that i do not have the brains to solve the question at hand but just that i do not know enough to dice and slice the programming problem. The remedy, i do more research, get to know the problem well enough in order to define it well and sometimes i just leave the problem alone. After sometime i come back to it with a new mindset.

It works for me i do not know if it will for you.

challenge #4, listing files recursively with Ruby

After almost a couple of months i have been now able to write a program to lists the files in a directory recursively. I was disappointed at first that i could write a program to do that but now i can. I have also picked up a few useful things on the way to solving the challenge that i would not have understood if i left the challenge or problem. The program is just about ten lines of code in ruby.
1  def list(file_name)
2    Dir.new(”#{file_name}”).each do |file|
3       next if file.match(/^\.+/)
4       path = “#{file_name}/#{file}”
5       if  FileTest.directory?(”#{path}”)
6         list(”#{path}”)
7       else
8          puts path
9        end
10     end
11  end

12  list(”/home/foo”)

On line #3, if the directory contains the .. and . directorys move to the next item in loop