Skip to content

Instantly share code, notes, and snippets.

@mendelgusmao
Created June 17, 2011 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mendelgusmao/1031967 to your computer and use it in GitHub Desktop.
Save mendelgusmao/1031967 to your computer and use it in GitHub Desktop.
Generates a numeric pyramid based on a string or a sequence of numbers
<?
set_time_limit(120);
error_reporting(E_ALL ^ E_NOTICE);
$in = $_GET["in"];
//$op = $_GET["op"] == 1 ? 1 : 0;
$in = $_GET["mode"] == "rnd()" ? rand(1, str_repeat("9", rand(2,9))) : $in;
$num = explode(" ", $in);
$trace = $_GET["trace"];
echo "<center><font face='Courier New'>
<form action='?'>
<input type='text' name='in' value='{$in}'><br>
<!-- <input type='radio' name='op' value='0' checked='checked'>+
<input type='radio' name='op' value='1'>*<br>-->
<input type='checkbox' name='mode' value='rnd()'>Rnd()
<input type='checkbox' name='trace' value='1'>Trace
<input type='submit' name='mode' value='' style='visibility:hidden'><br>
</form>
</center>";
flush();
foreach ($num as $in) {
$res = array();
if (!preg_match("/[0-9]/", $in)) {
$in = strtolower($in);
$in = preg_replace("/[^a-z]/", "", $in);
$in = correspondentes($in);
}
$tri = triangulo($in, 0, $op);
echo("<center><div style='letter-spacing:20px;'>");
foreach ($tri as $ln)
echo "$ln<br>";
echo "</div></center>";
flush();
if ($trace) {
echo("<pre>");
foreach($tri as $ln) {
$tra = todos($ln);
foreach($tra as $lna)
$res[$ln][] = $lna . (in_array($lna, $tri)
? " +"
: (strpos($lna, "0") > 0
? " -"
: ""));
//if ($i++ == count($lna) + 1) break;
}
print_r($res);
echo("</pre>");
}
echo("<hr>");
}
// ------------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------------
function triangulo($x, $n = 0) {
$ope = $op == 1 ? "*" : "+";
$z[] = $x;
while ($x > 9) {
$y = "";
$s = strlen($x) - 1;
$x = (string) $x;
while($s--) {
$e = $x{$s + 1} + $x{$s};
$y .= $e < 10 ? $e : triangulo($e, 1);
}
$z[] = $x = strrev($y);
}
return $n ? $z[1] : array_reverse($z);
}
function correspondentes($s) {
$x = "";
$y = strlen($s);
while ($y--)
$x .= ord(substr($s, $y, 1)) - 96;
return strrev($x);
}
function todos($prova) {
$base = strlen($prova) + 1;
$off = $base - 2;
$ini = str_repeat(1, $base);
$fim = str_repeat(9, $base);
for ($i = $ini; $i <= $fim; $i++) {
$tri = triangulo($i);
$res = $tri[$off];
// if (/*!strpos($i, "0") && !($i % 10 == 0) &&*/ $res == $prova)
if ($res == $prova)
$x[] = $i;
}
return $x;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment