SolutionGenerator   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 10
eloc 24
dl 0
loc 56
c 0
b 0
f 0
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A placeRandomStarters() 0 6 3
A __construct() 0 3 1
A getRandomEmptyLocation() 0 7 2
A generate() 0 8 2
A gridIsSolvable() 0 8 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace CoenMooij\Sudoku\Generator;
6
7
use CoenMooij\Sudoku\Exception\UnsolvableException;
8
use CoenMooij\Sudoku\Puzzle\Grid;
9
use CoenMooij\Sudoku\Puzzle\Location;
10
use CoenMooij\Sudoku\Solver\BacktrackSolver;
11
use CoenMooij\Sudoku\Validator\GridValidator;
12
13
class SolutionGenerator
14
{
15
    const NUMBER_OF_RANDOM_STARTERS = 11;
16
17
    /**
18
     * @var Grid
19
     */
20
    private $grid;
21
22
    /**
23
     * @var BacktrackSolver
24
     */
25
    private $solver;
26
27
    public function __construct(BacktrackSolver $solver)
28
    {
29
        $this->solver = $solver;
30
    }
31
32
    public function generate(): Grid
33
    {
34
        do {
35
            $this->grid = new Grid();
36
            $this->placeRandomStarters();
37
        } while (!$this->gridIsSolvable());
38
39
        return $this->grid;
40
    }
41
42
    private function placeRandomStarters(): void
43
    {
44
        for ($i = 0; $i < self::NUMBER_OF_RANDOM_STARTERS; $i++) {
45
            $location = $this->getRandomEmptyLocation();
46
            do {
47
                $this->grid->set($location, random_int(1, 9));
48
            } while (!GridValidator::gridIsValid($this->grid));
49
        }
50
    }
51
52
    private function getRandomEmptyLocation(): Location
53
    {
54
        do {
55
            $location = new Location(random_int(0, 8), random_int(0, 8));
56
        } while (!$this->grid->isEmpty($location));
57
58
        return $location;
59
    }
60
61
    private function gridIsSolvable(): bool
0 ignored issues
show
Unused Code introduced by
The method gridIsSolvable() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
62
    {
63
        try {
64
            $this->solver->solve($this->grid);
65
66
            return true;
67
        } catch (UnsolvableException $exception) {
68
            return false;
69
        }
70
    }
71
}
72