Skip to content

Commit

Permalink
Merge pull request #3 from hradtke/php
Browse files Browse the repository at this point in the history
Add PHP implementation of bfac.
  • Loading branch information
charlesgarvin committed May 31, 2011
2 parents 055668a + 5fdae0e commit dbd977a
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 0 deletions.
57 changes: 57 additions & 0 deletions php/bfac.php
@@ -0,0 +1,57 @@
<?php

function valid_factoradic($f)
{
$valid = strrev(implode('', range(0,9)));
$max = substr($valid, -strlen($f));

while (($m = substr($max, -1)) != "") {
$max = substr($max, 0, -1);
$d = substr($f, -1);
$f = substr($f, 0, -1);

if ($m < $d) {
return false;
}
}

return ($f <= $max);
}

function fac2ten($x)
{
$n = 0;
$f = 1;

$d = substr($x, -1);
$x = substr($x, 0, -1);
while (($d = substr($x, -1)) != "") {
$x = substr($x, 0, -1);
$n += $d * $f;
$f *= $f + 1;
}

return $n;
}

function ten2fac_r($n, $f)
{
if ($n < $f) {
return array("", $n);
}

list($s, $n) = ten2fac_r($n, $f * ($f + 1));

$d = (int) ($n / $f);
$n %= $f;
$s .= $d;

return array($s, $n);
}

function ten2fac($n)
{
list($f, $n) = ten2fac_r($n, 1);

return $f . "0";
}
42 changes: 42 additions & 0 deletions php/test.php
@@ -0,0 +1,42 @@
<?php

require __DIR__ . '/bfac.php';

$expected = array(0, 10, 100, 110, 200, 210, 1000, 1010, 1100, 1110, 1200,
1210, 2000, 2010, 2100, 2110, 2200, 2210, 3000, 3010, 3100, 3110, 3200,
3210);

echo 'ten2fac', PHP_EOL;
foreach ($expected as $ten => $fac) {
$given = ten2fac($ten);

if ($fac != $given) {
echo "Failed: {$ten} => {$fac} returned {$given}", PHP_EOL;
}
}

echo 'fac2ten', PHP_EOL;
foreach ($expected as $ten => $fac) {
$given = fac2ten($fac);

if ($ten != $given) {
echo "Failed: {$ten} => {$fac} returned {$given}", PHP_EOL;
}
}

echo 'valid_factoradic', PHP_EOL;
foreach ($expected as $ten => $fac) {
if( !valid_factoradic($fac)) {
echo "Failed: {$fac} returned false", PHP_EOL;
}

$fac += 1;
if(valid_factoradic($fac)) {
echo "Failed: {$fac} returned true", PHP_EOL;
}

$fac += 19;
if(valid_factoradic($fac)) {
echo "Failed: {$fac} returned true", PHP_EOL;
}
}

0 comments on commit dbd977a

Please sign in to comment.