abcaeffchen/sudoku-php

Generate random Sudokus of different size and difficulty and check the solution.

Fund package maintenance!
AbcAeffchen

1.1.0 2023-04-05 12:04 UTC

This package is auto-updated.

Last update: 2024-04-05 14:29:49 UTC


README

Unit Tests Latest Stable Version Total Downloads License

Genral

Generate random Sudokus of different size and difficulty and check the solution. Features:

  • Choose from the following sizes: 4, 9, 16, 25, 36.
  • Choose from fife degrees of difficulty.
  • Sudokus are reproducible via a integer seed.
  • Check if a input is a solution of any Sudoku or a solution to a specific task.
  • Solve Sudokus.
  • works with PHP 7.4 up to 8.2 (maybe also work with PHP < 7.4, but these versions are not supported anymore)
  • backend only, so you can build your own frontend however you like it.

Installation

You can install this via composer using

{
    "require": {
        "abcaeffchen/sudoku-php": "~1.1.0"
    }
}

or just download the Sudoku.php file and include it to your project. Make sure to use the namespace AbcAeffchen\sudoku.

How to use

Generate a task

use AbcAeffchen\sudoku\Sudoku;
$task = Sudoku::generate(9, Sudoku::NORMAL);

Generates a standard 9x9 Sudoku with normal difficulty. You can use the difficulties VERY_EASY, EASY, NORMAL, MEDIUM, HARD.

$task contains a two dimensional array of integers, where the gaps are set to null. You can use

list($task,$solution) = Sudoku::generateWithSolution(9, Sudoku::NORMAL)

to generate a task and a possible solution. Maybe to give hints?

You can reproduce the Sudoku by providing a seed.

$seed = 0;
$task = Sudoku::generate(9, Sudoku::NORMAL, $seed);

This way cou could store a seed seed and reproduce the task at any time.
The seed can be any positive integer.

Check a solution

You can check a solution by using

if(Sudoku::checkSolution($solution))
{
    echo 'Nice done!';
}
else
{
    echo 'Try again!';
}

If you also want to also check if the solution relates to the task, you can just also provide the task like this:

if(Sudoku::checkSolution($solution,$task))
    ...

Solve Sudokus

This function is used to generate the Sudokus, but you can also use it to solve some you generated by hand (or get it from somewhere else).

$solution = Sudoku::solve($task);

You only have to make sure, that $task is a two dimensional int array containing only numbers from 1 to the size and all gaps contain null.

License

Licensed under the LGPL v3.0 License.