Skip to content

Instantly share code, notes, and snippets.

@luelista
Created December 28, 2010 17:14
Show Gist options
  • Save luelista/757425 to your computer and use it in GitHub Desktop.
Save luelista/757425 to your computer and use it in GitHub Desktop.
mag_quad03.pl
#!/bin/perl
# mag_quad03.pl
# Max Weller, http://max-weller.de
my $count = $ARGV[0];
if(!$count || $count < 1 || $count % 2 == 0) {
print "Usage: perl $0 count\n\n";
print "Please specify a positive odd integer for count\n\n";
exit(1);
}
# Matrix initialisieren mit Count*Count, Inhalt 0
my @matrix = ();
$matrix[$_] = [(0) x $count] for(0..$count-1);
# Cursor auf Mitte oben
my $x = $count/2, $y = 0;
# Count*Count mal wiederholen, jeweils an der Cursorposition
# den Inhalt des Zaehlers einfuegen
# Bewegung des Cursors:
# - eins nach oben, eins nach rechts
# - wenn Feld belegt, stattdessen eins nach unten
# - Bei Randueberschreitung einfach auf der anderen Seite weiter
for (1..$count**2) {
$matrix[$x][$y] = $_;
$ox=$x++; $oy=$y--;
$x=0 if($x>=$count);
$y=$count-1 if($y<0);
if($matrix[$x][$y] > 0) {
$x=$ox; $y=$oy+1;
$y=$count-1 if($y<0);
}
}
# Ausgabe
my $summe = 0;
$summe += $_ for @{$matrix[0]};
print "Summe in alle richtungen: ",$summe,"\n\n";
for ($x=0; $x<$count; $x++) {
print ($_," \t ") for @{$matrix[$x]};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment