The Turing Omnibus

I started reading The New Turing Omnibus. I am not sure what blog post pointed me at the book, but I read that it is a great tour of computer science, which sounded interesting so I thought I would jump right in.

The first chapter is on Algorithms, which made me think of the first time I asked a non-programmer to read Programming Pearls. They laughed at the chapter "Aha Algorithms," well at the title anyway. But that is a different story. Mr. Dewdney provides a nice introduction to what an algorithm is by comparing it to a recipe. Which I think is a great idea. Moreover, he uses the idea of sauteeing as an anology to a loop, which is awesome.

The chapter also contained an algorithm in Pascal for drawing a little random "wallpaper", and I got motivated to reproduce the algorithm for myself. So here is the wallpaper algorithm in JavaScript. I added the ability to scale the canvas I draw on, and am leveraging my JS drawing code for this blog described here.

function wallpaper(corna, cornb, side, scale)
{
    var x, y, c;
    var i,j;

    for(i=0;i<100;i++)
    {
        for(j=0;j<100;j++)
        {
            x = corna + ((i*side)/100);
            y = cornb + ((j*side)/100);
            c = Math.floor(x*x + y*y);

            if(c % 2 === 0)
            {
                drawing.fillRect(i*scale,j*scale,scale,scale);
            }
        }
    }
}

wallpaper(0,0,334,4);

One of the biggest things I realized from the example is that the values you pass in for the corners and side greatly effect the resulting wallpaper. Here are a few other examples.

wallpaper(0,0,10,1);
wallpaper(0,0,33,1);
wallpaper(11,0,47,1);

At the end of the chapter are some exercises. One is to write a recipe as an program. I skipped that one, but the second exercise was to draw the wallpaper with 3 colors. The hint given is that you don't have to just test if a number is even or odd. I implemented a multi-color solution, shown here, by passing in an array of colors and using mod to pick a color in the array. I sort of cheat, in that I don't draw white pixels. But otherwise, I hope this is what Mr Dewdney had in mind.

function multiColorWallpaper(corna, cornb, side, scale, colors)
{
    var x, y, c;
    var i,j;

    for(i=0;i<100;i++)
    {
        for(j=0;j<100;j++)
        {
            x = corna + ((i*side)/100);
            y = cornb + ((j*side)/100);
            c = Math.floor(x*x + y*y);

            c = c % colors.length;

            if(c > 0)
            {
                drawing.fillStyle = colors[c];
                drawing.fillRect(i*scale,j*scale,scale,scale);
            }
        }
    }
}

var colors = ['white','#FFCCCC','#CCFFCC','#CCCCFF'];
multiColorWallpaper(0,0,334,4,colors);

On to chapter two...

omnibus javascript programming algorithms