SolutionGenerator::getRandomEmptyLocation()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 7
c 0
b 0
f 0
rs 10
cc 2
nc 1
nop 0
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