#!/usr/bin/perl # https://codingcompetitions.withgoogle.com/codejam/round/0000000000051635/0000000000104e03 use strict; use warnings; use List::Util qw( first shuffle ); my $w; my $case = 0; for my $row ( 2 .. 20 ) # testing all sizes, needs change to read input file { for my $col ( 2 .. 20 ) { $case++; if( $row == 2 && $col < 5 || $row < 5 && $col == 2 || $row == 3 && $col == 3) { print "Case #$case: IMPOSSIBLE\n"; # hard coded next; } $w = $col; my @pylons = 0; # first pylon in upper left corner my @empty = shuffle 1 .. $row * $col - 1; while( @empty ) { if( my $try = first { ! conflict($pylons[-1], $_) } @empty ) { push @pylons, $try; @empty = grep $_ != $try, @empty; } else { push @empty, shuffle splice @pylons, 1; # reshuffle } } print "Case #$case: POSSIBLE\n"; # uncomment next line to print grid locations #print +(int 1 + $_ / $w) . ' ' . (1 + $_ % $w) . "\n" for @pylons; } } sub conflict { my ($x, $y) = @_; my ($r, $c, $rr, $cc) = (int $x / $w, $x % $w, int $y / $w, $y % $w); $r == $rr || $c == $cc || $r + $c == $rr + $cc || $r - $c == $rr - $cc; }