Hallo,
der Fernsehsender »Scheiße hoch 9« (gibt's den eigentlich noch?) hatte immer solche Rätselbilder wie »Wieviele Städtenamen sind in diesem Buchstabensalat versteckt« und so was ...
In einem Bilderrätsel wurde gefragt, wieviele Quadrate in einer bestimmten Figur (s. u.) enthalten sind.
Ich hab' das mal per PHP gelöst, allerdings dauert die Berechnung seine Zeit.
Wer hat eine Idee, wie man das folgende Programm noch optimieren könnte?
PHP-Code:
<?php
/*
Aufgabe: »Wieviele Quadrate sind in folgender Figur enthalten?«
+ + + + +
+ + + + +
+ + + + + + +
+ + + + + +
+ + + + + + +
+ + + + +
+ + + + +
*/
$t0 = explode(' ', microtime());
// x-y-Koordinaten aller Punkte in obigem
// Gebilde ermitteln
for ($x = 0; $x < 7; $x++)
{
for ($y = 0; $y < 7; $y++)
{
if (!
(
($x == 0 AND $y == 5) OR
($x == 0 AND $y == 6) OR
($x == 1 AND $y == 5) OR
($x == 1 AND $y == 6) OR
($x == 5 AND $y == 0) OR
($x == 5 AND $y == 1) OR
($x == 6 AND $y == 0) OR
($x == 6 AND $y == 1) OR
($x == 3 AND $y == 3)
)
)
$p[] = array('x' => $x, 'y' => $y);
}
}
// Prüfen, ob jeweils vier Punkte geometrisch ein Quadrat bilden:
$found = 0;
foreach ($p AS $p1 => $v1)
{
foreach ($p AS $p2 => $v2)
{
if ($p2 == $p1)
continue;
foreach ($p AS $p3 => $v3)
{
if ($p3 == $p2 OR $p3 == $p1)
continue;
foreach ($p AS $p4 => $v4)
{
if ($p4 == $p3 OR $p4 == $p2 OR $p4 == $p1)
continue;
$sq_a = ($v2['x']-$v1['x'])*($v2['x']-$v1['x']) +
($v2['y']-$v1['y'])*($v2['y']-$v1['y']);
if (
($v3['x']-$v2['x'])*($v3['x']-$v2['x']) +
($v3['y']-$v2['y'])*($v3['y']-$v2['y'])
!= $sq_a
)
continue;
if (
($v4['x']-$v3['x'])*($v4['x']-$v3['x']) +
($v4['y']-$v3['y'])*($v4['y']-$v3['y'])
!= $sq_a
)
continue;
if (
($v1['x']-$v4['x'])*($v1['x']-$v4['x']) +
($v1['y']-$v4['y'])*($v1['y']-$v4['y'])
!= $sq_a
)
continue;
if (
($v3['x']-$v1['x'])*($v3['x']-$v1['x']) +
($v3['y']-$v1['y'])*($v3['y']-$v1['y'])
!= 2 * $sq_a
)
continue;
$found++;
}
}
}
}
$t = explode(' ', microtime());
$z = $t[1] - $t0[1] + $t[0] - $t0[0];
echo 'Gefundene Quadrate: ' . $found/8;
echo '<br>benötigte Zeit: ' . number_format($z, 2, ',', '.') . ' s';
/*
function sq ($int)
{
return $int * $int;
}
Diese Funktion hatte ich ursprünglich, um z. B.
($v2['x']-$v1['x'])*($v2['x']-$v1['x'])
durch
sq(($v2['x']-$v1['x']))
zu verkürzen, was sich aber als langsamer rausstellte.
*/
?>