Fox, Goose, Beans

Here is the wiki entry about the Fox, Goose and bag of Beans puzzle.

The following Perl program prints the solution to it.

use strict;
use warnings;
use sigtrap;

my @items = qw(goose fox beans farmer);
my %locns = map {$_ => 'A'} @items;     # initially, all items on Shore A

sub is_all_transported {
    my %locns = @_;
	my $count = 0;
    for (keys %locns) {
        $count += 1 if $locns{$_} eq 'B';
    }
    return ($count == 4) ? 1 : 0;
}

sub is_eatable {
    my @eatables = ( {goose => 'A', beans => 'A', farmer => 'B'}
                   , {goose => 'A', fox   => 'A', farmer => 'B'}
                   , {goose => 'B', beans => 'B', farmer => 'A'}
                   , {goose => 'B', fox   => 'B', farmer => 'A'}
			       ) ;
    my %tmp_locn = @_;
    for my $i (0 .. @eatables) {
		my $count = 0;
		for my $item (keys %{$eatables[$i]}) {
			$count += 1 if $tmp_locn{$item} eq $eatables[$i]->{$item};
		}
		return 1 if $count == 3;
    }
	return 0;
}

sub transport_to {
    my $locn_ref = shift;
    my $item     = shift;
	my $locn_dst = shift;
	my $locn_alt = ($locn_dst eq 'A') ? 'B' : 'A';
    
	return 0 if $locn_ref->{'farmer'} eq $locn_dst;
	return 0 if $locn_ref->{$item}    eq $locn_dst;

	$locn_ref->{$item}    = $locn_dst;
	$locn_ref->{'farmer'} = $locn_dst;
    
    return 1 if not is_eatable(%$locn_ref);

	$locn_ref->{$item}    = $locn_alt;
	$locn_ref->{'farmer'} = $locn_alt;

	return 0;
}

sub my_print {
	my ($item, $back) = @_;
	print "Return\n" and return 1 if $item eq 'farmer';
	print "Bring $item$back\n";
}

sub main {
    while(not is_all_transported(%locns)) {
        for(@items) {
            my_print ($_, '') and next if transport_to(\%locns, $_, 'B');
            my_print ($_, ' back') if transport_to(\%locns, $_, 'A');
        }
    }
}

main();

Simple puzzle but solving it with a computer program gives you much more happiness. (Oh! forgive me for poorly naming the functions 😉

Happy programming!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s