HintGenerator   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 9
eloc 18
dl 0
loc 48
c 0
b 0
f 0
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A generateAll() 0 10 3
A hasOnePossibleValue() 0 5 1
A getLocations() 0 10 3
A generateOne() 0 9 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
11
class HintGenerator
12
{
13
    public function generateOne(Grid $grid): Location
14
    {
15
        $locationList = $this->generateAll($grid);
16
        if (empty($locationList)) {
17
            throw new UnsolvableException();
18
        }
19
        shuffle($locationList);
20
21
        return $locationList[0];
22
    }
23
24
    /**
25
     * @return Location[]
26
     */
27
    public function generateAll(Grid $grid): array
28
    {
29
        $locations = [];
30
        foreach ($this->getLocations() as $location) {
31
            if ($this->hasOnePossibleValue($grid, $location)) {
32
                $locations[] = $location;
33
            }
34
        }
35
36
        return $locations;
37
    }
38
39
    /**
40
     * @return Location[]
41
     */
42
    private function getLocations(): array
43
    {
44
        $locations = [];
45
        for ($row = 0; $row < Grid::NUMBER_OF_ROWS; $row++) {
46
            for ($column = 0; $column < Grid::NUMBER_OF_COLUMNS; $column++) {
47
                $locations[] = new Location($row, $column);
48
            }
49
        }
50
51
        return $locations;
52
    }
53
54
    private function hasOnePossibleValue(Grid $grid, Location $location): bool
55
    {
56
        $possibleValues = $grid->getAllPossibilitiesFor($location);
57
58
        return count($possibleValues) === 1;
59
    }
60
}
61