DepthFirstStrategy::forThe()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\PuzzleSolver\SearchStrategy;
4
5
use SplStack;
6
use Stratadox\PuzzleSolver\Puzzle;
7
use Stratadox\PuzzleSolver\Moves;
8
9
/**
10
 * Depth-first search strategy
11
 *
12
 * Depth-first searches continuously follow the first option, until it turns out
13
 * the branch does not lead to a solution, at which point it tracks back to the
14
 * first next available option.
15
 *
16
 * @author Stratadox
17
 */
18
final class DepthFirstStrategy implements SearchStrategy
19
{
20
    /** @var SplStack */
21
    private $stack;
22
    /** @var Puzzle */
23
    private $originalPuzzle;
24
25
    private function __construct(
26
        SplStack $stack,
27
        Puzzle $originalPuzzle
28
    ) {
29
        $this->stack = $stack;
30
        $this->originalPuzzle = $originalPuzzle;
31
    }
32
33
    public static function forThe(Puzzle $puzzle): SearchStrategy
34
    {
35
        $stack = new SplStack();
36
        $stack->push(Moves::none());
37
        return new self($stack, $puzzle);
38
    }
39
40
    public function isOngoing(): bool
41
    {
42
        return !$this->stack->isEmpty();
43
    }
44
45
    public function consider(Puzzle $puzzle): bool
46
    {
47
        $this->stack->push($puzzle->movesSoFar());
48
        return true;
49
    }
50
51
    public function nextCandidate(): Puzzle
52
    {
53
        return $this->originalPuzzle->afterMaking(...$this->stack->pop());
54
    }
55
}
56