Search code examples
phprandomhtml-tablefillsudoku

How to fill an array with algorythm


I would like to make a test about a sudoku like table. The first part of code can make a 7x7 table with numbers like sudoku without any normal appareance. The second part of the code make a 7x7 table with a basic appareance. How can i mix it together?

<?php
$n = 7; //szám

$seed_row = range(1, $n); //mettől meddig
shuffle($seed_row); //keverés

$result = array();
for($x = 0; $x < $n; $x++)
{
    $tmp_ar = array();
    $rnd_start = $seed_row[$x];
    for($y = $rnd_start; $y < ($n + $rnd_start); $y++)
    {
        if($y >= $n) $idx = $y - $n;
        else $idx = $y;
        $tmp_ar[] = $seed_row[$idx];
    }
    $result[] = $tmp_ar;
}

for($x = 0; $x < $n; $x++)
{
    echo implode(' ', $result[$x]) . "<br/>\n";

}

//second part

echo '<table border="1" style="height:50%; width:50%;">';
    for ($i=0; $i < 7; $i++) {      
        echo "<tr>";
            for ($j=0; $j < 7; $j++) { 
                echo "<td>";                
                    
                echo "</td>";
                }
        echo "</tr>";
    }
echo "</table>";
?>

Solution

  • You only need to output your array in a for loop

       <?php
        $n = 7; //szám
        
        $seed_row = range(1, $n); //mettől meddig
        shuffle($seed_row); //keverés
        
        $result = array();
        for($x = 0; $x < $n; $x++)
        {
            $tmp_ar = array();
            $rnd_start = $seed_row[$x];
            for($y = $rnd_start; $y < ($n + $rnd_start); $y++)
            {
                if($y >= $n) $idx = $y - $n;
                else $idx = $y;
                $tmp_ar[] = $seed_row[$idx];
            }
            $result[] = $tmp_ar;
        }
        
        
        //second part
        
        echo '<table border="1" style="height:50%; width:50%;">';
            for ($i=0; $i < 7; $i++) {      
                echo "<tr>";
                    for ($j=0; $j < 7; $j++) { 
                        echo "<td>";                
                        echo $result[$i][$j];    
                        echo "</td>";
                        }
                echo "</tr>";
            }
        echo "</table>";
        ?>