0

I'm trying to code the 8 queen problem in perl and I seem to be running into an infinite loop that I cannot fix. I think the problem is with the queen increments because when I do print "$queen"; in my solve function all I get is a bunch of 1's.

#
# implement 8 queen problem
#

my $size = 8;
my @answer = ();

sub is_conflict($$){
    my ($row, $queen) = @_;

    for(my $i=0; $i<$queen; $i=$i+1){
        my $temp = $answer[$i];
        if (($temp eq $row) or                      #same row
            ($temp eq ($row - ($queen - $i))) or    #same diagonal
            ($temp eq ($row + ($queen-$i)))){       #same diagonal
            return 1;   #return true
        }
    }
    return 0;   #return false
}

sub solve($){
    my $queen = @_;

    if($queen eq $size){
        print "@answer\n";
        @answer = ();
    }
    else{
        for(my $i=0; $i<$size; $i=$i+1){
            if(is_conflict($i,$queen) eq 0){
                push(@answer, $i);
                solve($queen+1);
            }
        }
    }
}

solve(0);

1 Answers1

3

my $queen = @_ is almost surely not what you meant.

my $var = @_ evaluates @_ in scalar context, giving you the size of @_ and not the first element of @_. In your program, you are always assigning the value 1 to $queen.

Instead, you want to say one of

my ($queen) = @_;     # list context, assigns first element of @_
my $queen = shift @_; # extract first element from @_
my $queen = shift;    # inside a sub, same as  shift @_
mob
  • 117,087
  • 18
  • 149
  • 283
  • So I was assuming that my $queen = @_ was just passing in variables. Now I don't have an infinite loop but my program still doesn't print out anything. – Krit Phosamritlert May 31 '17 at 05:14