Random number kata

I am a big fan of the idea of improvement kata. I’ve practiced kata at work several times: establish where you want to go, establish where you are now, regularly do small things to improve where you are until you get where you want to go.

I consider myself a self-taught programmer. My learning was all to get something working rather than doing it the good way. Well, I’d like to get better at doing things the good way and improvement kata is the way I want to do it.

Enter Jon Bentley’s Programming Pearls, a book about solving computer problems effectively. The book has been on my self and then my kindle library for years. I’ve never really gotten past the first chapter. I definitely haven’t taken on the exercises – I felt I was too dumb.

This weekend I decided to have a go at one or two problems in Chapter One. Over the course of some early mornings before the rest of the family got up, and a little bit on Sunday afternoon, I wrote a script that generates random numbers and a program that sorts them.

The generator was written in Ruby, my go-to language. I implemented the Fisher-Yates shuffle algorithm and employed a favourite ruby trick, the ability to set or return more than one value. It made me feel quite the clever clogs.

a.each_with_index do |item, index|
    random_index = rand(index..(a.size-1))
    a[index], a[random_index] = a[random_index], a[index]
end

The problem in chapter one called for a bitvector, basically an array of bits. I had it in my head that that was something that would be easy to do in C. So I broke out WSL2 and installed gcc.

Before I even got to implementing the bitvector I had to teach myself the basics of C programming: writing output, reading and writing a file, pointers, memory allocation, compiler flags. It was super fun.

Then it came to the bitvector implementation and I realised that C deals with bytes, not bits, and I was going to have to do some work to get to the bits. It would have been the same in Ruby. I had a look at some documentation for getting down to the bit level and declared it too much for a single kata.

I found a gist that looked like it created the thing I needed, typed the three functions I’d need (I seem to learn better by doing that) and implemented the sort algorithm. After some faffing around with the order of compiler flags had a working program. Good enough for one weekend.

I learned a few useful things in this kata. I think the biggest benefit was just getting back into the programming headspace. I’m going to persist with this practice and continue using Programming Pearls as a source of ideas.

This kata highlighted by ignorance of bitwise operations. It’s something I’ve never got, something I’ve never really had to deal with. It does seem like something that I should at least understand when I come across it, though. My next kata may dive into that.