VisitedNodeSkipper::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\PuzzleSolver\SearchStrategy;
4
5
use Stratadox\PuzzleSolver\Puzzle;
6
7
/**
8
 * Visited Node Skipper
9
 *
10
 * The Visited Node Skipper keeps a list of puzzle states that have already been
11
 * encountered during the search to skip candidates when they are about to be
12
 * considered for a second time.
13
 *
14
 * Decorator for other search strategies.
15
 *
16
 * @author Stratadox
17
 */
18
final class VisitedNodeSkipper implements SearchStrategy
19
{
20
    /** @var SearchStrategy */
21
    private $search;
22
    /** @var bool[] */
23
    private $visited = [];
24
25
    public function __construct(SearchStrategy $search)
26
    {
27
        $this->search = $search;
28
    }
29
30
    public static function forThe(SearchStrategy $search): SearchStrategy
31
    {
32
        return new self($search);
33
    }
34
35
    public function isOngoing(): bool
36
    {
37
        return $this->search->isOngoing();
38
    }
39
40
    public function consider(Puzzle $puzzle): bool
41
    {
42
        if (isset($this->visited[$puzzle->representation()])) {
43
            return false;
44
        }
45
        return $this->search->consider($puzzle);
46
    }
47
48
    public function nextCandidate(): Puzzle
49
    {
50
        $state = $this->search->nextCandidate();
51
        if (!$state->isSolved()) {
52
            $this->visited[$state->representation()] = true;
53
        }
54
        return $state;
55
    }
56
}
57