I have to built a function which would list the all possibilities to put +, - or nothing between the numbers ranging from 1 to 9 and print it result.
For example: 1
def hun(exp, i):
if (i<=9):
for mark in ("+", "-", ""):
hun(exp + mark + str(i), i+1)
elif eval(exp) == 100:
print(exp + " = 100")
hun("1",2)
You can do it by recursive - Use the following code:
<?php
function addNum($baseStr, $nextNum)
{
if ($nextNum == 10)
return array($baseStr);
$arr1 = addNum($baseStr. '+' . $nextNum, $nextNum+1);
$arr2 = addNum($baseStr. '-' . $nextNum, $nextNum+1);
$arr3 = addNum($baseStr. '' . $nextNum, $nextNum+1);
return array_merge($arr1, $arr2, $arr3);
}
$permutation = addNum('1', 2);
foreach ($permutation as $perm)
{
$res = eval("return $perm;");
echo $perm . '=' . $res . "\n";
}
?>