The Towers of Hanoi in Erlang

18 August, 2009 (22:34) | Programming, Erlang | 0 comments

I’m just playing with Erlang, below is my attempt at solving the Towers of Hanoi puzzle using it. Call it using hanoi:hanoi([1,2,3,4,5,6],[],[]) (a valid starting position is assumed).

-module(hanoi).
-export([hanoi/3]).

hanoi(A,B,C) ->
	Disk=lists:max(A),
	move(Disk,A,B,C).

move(Disk,[Disk|Source],Dest,Temp)->
	[Source,[Disk|Dest],Temp];

move(Disk, Source, Dest, Temp) ->
	[S1,T1,D1]=move(Disk-1,Source,Temp,Dest),
	[S2,D2,T2]=move(Disk,S1,D1,T1),
	[T3,D3,S3]=move(Disk-1,T2,D2,S2),
	[S3,D3,T3].

Solving the Towers of Hanoi puzzle in C#

4 August, 2009 (18:45) | .Net, Programming, C#, Computer Science | 0 comments

I thought this would be a fun little exercise to try. This puzzle is generally used to teach recursion in CS classes, but I have never actually tried to implement it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TowersOfHanoiCs
{
    class Program
    {
        static List peg1;
        static List peg2;
        static List peg3;

        static void Main(string[] args)
        {
            peg1 = new List();
            peg2 = new List();
            peg3 = new List();

            for (int i = 1; i < 8; i++)
            {
                peg1.Add(i);
            }

            Display();
            MoveDisk(7, peg1, peg2, peg3);
            Console.ReadLine();
        }

        static void MoveDisk(int disk, List source, List destination, List temp)
        {
            int position = source.IndexOf(disk);

            if (position == 0)
            {
                source.Remove(disk);
                destination.Insert(0, disk);
                Display();
            }
            else
            {
                int nextDisk = source[position - 1];
                MoveDisk(nextDisk, source, temp, destination);
                MoveDisk(disk, source, destination, temp);
                MoveDisk(nextDisk, temp, destination, source);
            }
        }

        static void Display()
        {
            DisplayPeg(peg1);
            DisplayPeg(peg2);
            DisplayPeg(peg3);
            Console.WriteLine(”———-”);
        }

        static void DisplayPeg(List peg)
        {
            foreach (int x in peg)
            {
                Console.Write(x + ” “);
            }
            Console.WriteLine();
        }
    }
}

Sending an email with syntax hightlighting for your source code

2 August, 2009 (22:53) | Programming | 1 comment

I resisted the switch to HTML e-mail for as long as I could, I know there are some who have managed to succeed in not switching to an HTML enabled email reader. But I just couldn’t hold out due to the fact that there were so many non-computer savvy people I communicated with who used it, and their e-mails were impossible to read without it, and I had to make the switch many years ago.

Since we’re all so used to reading code that has syntax highlighting in it, I like to have the source code contained in e-mails highlighted. Unfortunately, most syntax highlighters made for the web use CSS to style the code. And when you copy and paste the code into an email, the <style class=’…’> tags are copied, but not the actual style from the CSS, and what comes out on the other end is just text in the standard font. So the only way to get syntax highlighting in your email is to use a utility that embeds the styles into the HTML, rather than a CSS. I also wanted a utility that didn’t require me to save the source code and output as a file on my computer, creating a lot of unnecessary temp files that I’d probably never delete. So far, the only thing that actually fits the bill is this web based utility: http://tools.devshed.com/webmaster-tools/syntax-highlighting/

Basically, just paste your source code into the tiny little window, select the language, type the captcha, then cut and paste the result into your e-mail. It doesn’t have many options, and there’s lots of room for improvement, but it’s the best thing I’ve found so far.

Turbo Pascal 5.5 is available for download for free

2 August, 2009 (22:23) | History, Programming | 1 comment

Firing up ole’ TP7 for the last post put me in a nostalgic mood, and I went looking to see where Turbo Pascal stands today. It doesn’t look like you can still buy it, and the only version available is Turbo Pascal 5.5 which you can download for free from: http://edn.embarcadero.com/article/20803

I believe my first experience with Pascal was at Indiana University when I started my first CSCI class in 1990. I believe we were using version 5. I also remember the first time I fired up version 7 and saw that certain keywords where highlighted in different colors. I was so amazed I almost wanted to do cartwheels, I was so impressed with such an amazing idea. IDEs have come a long way since then, but the Lord only know how many hours I spent staring at the old blue and yellow screen of the Turbo Pascal DOS IDE.

Below are two screenshots from TP7. The first is the default layout of 80×25 chars with the default colors, the second is my custom layout with the amazing 80×50 char layout showing twice the number of lines! (Hey it was a big deal back in the day). The pop up box in the blue one shows a successful compile. I’m not sure where the program came from that’s shown in the second image, I’m pretty sure it’s not something I wrote, but it’s what popped up automatically when I started the IDE. I do remember I spent a lot of time playing with interfacing to Netware servers back then, this program appears to be an attempt to log in without using the API (which was just a series of INT calls). I think it’s either the reverse engineered source code that a fellow Netware “hacker” developed who I had the pleasure of exchanging many e-mails with: Willem Jan Hengeveled. If it’s not his code, it’s probably something based off of it. Now I think I’m going to have to install an old Netware server in a VM to play with.

Borland Turbo Pascal 7 IDE - Default
Turbo Pascal 7 IDE - Custom Colors

Statements in most languages can be empty

2 August, 2009 (19:31) | Programming | 0 comments

I was looking through some code that was posted for review when someone had pointed out a statement like the following:

int x=5;;

Note the two semi-colons. I initially thought “Great, someone has us reviewing code they didn’t even try to compile.” But to my amazement, it does compile, and it compiles in pretty much every language. I’ve tested it on the newest and oldest stuff I have, the oldest/obscurest thing I could come up with was Borland Turbo Pascal 7 (the EXE has a date of 10/30/1992). I’m sure there’s some deep theoretic reason parsers need to accept it, but to a human, it looks like an obvious error.

A really tough puzzle

1 August, 2009 (21:37) | Humor | 0 comments

100 prisoners are each locked in a room with three pirates, one of whom will walk the plank in the morning. Each prisoner has 10 bottles of wine, one of which has been poisoned. And each pirate has twelve coins, one of which is counterfeit and weighs either more or less than a genuine coin. In the room is a single switch which the prisoner may either leave as it is or flip. Before being led into the rooms, the prisoners are forced to wear either a red had or a blue hat. They can see all the other prisoner’s hats, but not their own. Meanwhile a six digit prime number of monkeys multiply until their digits reverse. Then all have to get across a river using a canoe that can hold at most two monkeys at a time. But half the monkeys always lie and the other half always tell the truth. Given that the nth prisoner knows that one of the monkeys doesn’t know that a priate doesn’t know product of two numbers between 1 and 100 without knowing that n+1th prisoner has flipped the switch in his room or not after having determined which bottle of wine was poisoned and what color his hat is. What is the solution to this puzzle?

This was played on the July 18, 2009 edition of Car Talk on NPR and attributed only to “Alan”. If you download the podcast, the puzzler starts at the 36:00 minute mark.

Getting confused between closures and eval()

19 June, 2009 (23:51) | JavaScript, Programming | 0 comments

I just saw a question regarding closures in JavaScript regarding code similar to the following:

for (i=0;i<n;i++){
     foo.bind( function() { bar(i); } );
}

The question was why does every closure execute bar(i) with i as the value of n for every instance, rather than whatever the value of i was when the closure was defined. He had reckoned that i was being passed by reference than by copy and found that making a copy of i in a variable local to the closure solved the problem.

But what he’s really done is confused a closure with an eval() statement. If he had written the code similar to eval(”function(){bar(”+i+”);”); he would have gotten what he wanted. The difference being that when you use eval() the variable i is determined when the eval() is executed. But with a closure, i is determined when the closure is executed, and every time the closure is executed.

It’s also important to note that the i referenced inside the enclosure is not a reference to the i in the outer loop, rather it actually IS the same i in the outer loop. No parameter passing is going on.

One other possible solution is to define the closure to take a parameter, and pass i in as a parameter to the enclosure:

for (i=0;i<n;i++){
     foo.bind( function(x) { bar(x); } )(i);
}

Copy a Linux system over the network, with no intermediate files

27 October, 2008 (21:41) | Linux | 1 comment

I had an old Red Had Linux system I wanted to convert to a Virtual Machine. The typical method recommended by most people is to back up the system, then restore it inside the VM. The problem I had with that is that you end up wasting a lot of time creating an image you don’t need, plus you need a storage device large enough to hold the image which can be accessed from both systems.

My solution was to create the VM with a virtual drive the size I needed. Then use a Knoppix image to initially boot the VM, once you get to a command line, use the commands below.

On the receiving server:

sudo nc -p 2222 -l | dd of=/dev/hda

On the system to be copied:

sudo dd if=/dev/hda | nc 192.168.0.56 2222

If your CPU on each device is faster than the network, you could also gain some speed by piping the data stream through bzip2. E.g. “sudo nc -p 2222 -l | bzip2 -d | dd of=/dev/hda” and “sudo dd if=/dev/hda | bzip2 -c | nc 192.168.0.56 2222″. Whether or not it’s worth it depends on the speed of your CPUs and the speed of your network.

It’s not a requirement that you boot the system being imaged from a CD, nor that you shut down any services. But, if you don’t, it’s possible you might end up with some files that aren’t in a valid state from the application’s point of view. There’s no real method I know of to monitor the progress of the copy, but you can run “fdisk /dev/hda” to verify the copy at least got started. If the copy started OK, then you’ll see partition information the same as on the system being imaged. You can also run “ifconfig” and watch the “RX bytes” field to get an idea of how much data has been transferred, but the counter will eventually overflow and start back at 0.

0×8007232b error when attempting to activate Windows Server 2008

9 August, 2008 (14:15) | Windows | 0 comments

I had just ran into an issue attempting to activate my copy of Windows 2008 Server downloaded from MSDN. The error expands to “DNS Entry not found”, although all networking features work fine. The issue was that it was attempting to validate against an Activation Server rather than Microsoft’s website. The solution was to open “System” in the Control Panel, down at the bottom of that window is a link titled “Change Product Key”. I entered my key from the MSDN website and Windows activated automatically after the key was entered.

The difference between window.setTimeout() and window.setInterval()

1 August, 2008 (12:49) | JavaScript, Programming | 1 comment

From what I’ve seen, the problem most people have with the difference between these two JavaScript functions isn’t knowing what they do, but it’s knowing that they both exist. I’ve seen lots of people constantly call setTimeout() calling the same function over and over where the last line of the function calls setTimeout(), but setInterval() is probably what they really wanted, they just didn’t know it existed. But I’ve also seen lots of code that calls setInterval() to execute a function after a specific delay, and the first thing that function does is call clearInterval(), so they obviously really wanted the functionality of setTimeout(). I guess it’s mostly a result of people finding one thing that gets the job done, and never looking for anything else.

The difference between the two functions is fairly trivial. setTimeout() executes the function only once, unless you call it again; and setInterval() continuously calls the function until clearInterval() is called. The only disadvantage to using setTimeout() when you really wanted the functionality of setInterval is that the time between each call will vary depending on how long it takes your code to execute (and sometimes you actually want that feature). There is some danger in using setInterval() and hoping your code is fast enough to call clearInterval() before the interval time passes. In such a case, the next call is queued and will execute your function any number of times depending on how many times the interval time passed while your code was running.