Just the Facts Ma’m
What does a PHP geek do when confronted with the task of generating practice math problems for his eight year old daughter? Script it, of course. Madeline wanted to practice addition, so she gave me a crayon and told me to write down 100 math problems consisting of adding two single digit numbers.
A “better” solution lept to mind immediatly:
A class to store and render a “fact”:
<?php
class Fact {
protected $top;
protected $bottom;
public function __construct($t, $b) {
$this->top = $t;
$this->bottom = $b;
}
public function render() {
return ' '.$this->top."\n<u>+".$this->bottom.'</u> ';
}
}
?>
Generate some facts and store them in an array:
<?php
$facts = array();
foreach(range(0,9) as $top) {
foreach(range(0,9) as $bottom) {
$facts[] = new Fact($top, $bottom);
}
}
?>
Make sure they are in random order:
<?php
shuffle($facts);
?>
and render them into a table for easy layout (what can I say, it was a two minute hack):
<?php
echo '<table border="0" cellpadding="9">';
foreach(range(0,9) as $tens) {
echo '<tr>';
foreach(range(0,9) as $ones) {
echo '<td>', $facts[$tens*10+$ones]->render(), '</td>';
}
echo '</tr>';
}
echo '</tr></table>';
?>
fresh, randomly ordered fact sheet ready for printing.
Hey Jason, nice solution. I have kids too (3, 8, & 10) and often hack up scripts like this. (I hear from the troops that the flash card script is giving warnings since upgrading our home server to PHP5 😉 You missed a HTML break in this line which should be:
Also to create sheets other operations (next year):
Ah well, looks like WordPress has stripped out all the HTML in the code I posted. The missing break is between the top and bottom numbers.
Cool… but how long before your daughter posts to php-general and asks someone for help and someone comes up with this:
$fd = fopen("http://domain.com/path/to/math.php", "r");
while (!feof($fd)) {
$line = fgets($fd);
if ( ereg("
$num1 = $ary[1];
$line = fgets($fd);
ereg("\+([0-9])", $line, $ary);
$num2 = $ary[1];
$answer = $num1 + $num2;
print("$num1 + $num2 = $answer
");
}
}
fclose($fd);
Re: Christopher
Yes, WordPress frusterates me often with silliness like this. Striping slashes once too often as well it appears.
Re: Philip
“I already started showing here a little PHP, but she understands that you are not allowed to write new code unless you have a red bar indicating a failing test Hopefully she would ask for the unit tests on the code before paying any attention.”
Laughing out loud over here.
you’ve truly out-geeked yourself this time Jason 😉
lol
Or You can use javascript which is what I did, and seems much faster.
http://www.extrahomework.com/worksheet2.html