Search code examples
phprandommultiplication

Random multiplication table generator


im creating an multiplication table system in PHP.

The input tho this system is an table number and the amount of questions. The table 1 is skipped so 2 to input table

At this point I just fill an array like this:

$nCount = $_POST['count'];
$nHighest = $_POST['table'];
$aSums = [];
$nCounter = 0;
while($nCount > 0){
    $cSumString = rand(2, $nHighest) . "*" . rand(1, 10);
    $aSums[$nCounter] = $cSumString
    $nCount--;
    $nCounter++;
}

I want to parse the questions in multiple ways:

3 * 5 = ... (normal)
... * 5 = 25 (first number to fill in)
8 * ... = 16 (second to fill in)

This needs to be randomised.

Example:

1 * 2 = ... 
6 * ... = 12 
... * 4 = 20
8 * 4 = ...
2 * ... = 6

The only thing I know that should be able to so this is a switch but I cant seem to get it to work propperly so if anyone can give me a push in the right direction i would appreciate it. Im not asking for instacode just some tips would be great.


Solution

  • $nCount = $_POST['count'];
    $nHighest = $_POST['table'];
    $aSums = [];
    $leftOut = ['leftFactor', 'rightFactor', 'product'];
    
    for ($i = 0; $i <= $nCount; $i++) {
      $leftOutRand = rand(0, count($leftOut) - 1);
      $factor = rand(1, $nHighest);
      $product = rand(0, $nHighest) * $factor;
      switch($leftOut[$leftOutRand]) {
        case 'leftFactor':
          $cSumString = '...' . ' * ' . $factor . ' = ' . $product;
          break;
        case 'rightFactor':
          $cSumString = $factor . ' * ' . '...' . ' = ' . $product;
          break;
        case 'product':
          $cSumString = rand(1, $nHighest) . ' * ' . rand(1, $nHighest) . ' = ' . '...';
          break;
      }
      $aSums[$i] = $cSumString;
    }
    

    example Output:

    2 * ... = 4
    ... * 2 = 6
    1 * 1 = ...
    ... * 2 = 6
    3 * ... = 12
    2 * ... = 2
    2 * 4 = ...
    4 * ... = 0
    3 * 1 = ...
    2 * 1 = ...
    ... * 4 = 16
    1 * ... = 2
    ... * 2 = 2
    1 * 4 = ...
    3 * ... = 9
    2 * 3 = ...
    2 * ... = 6
    ... * 1 = 3
    ... * 4 = 4
    1 * 1 = ...
    ... * 3 = 9