DepthFirstStrategy   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 36
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 36
rs 10
wmc 5

5 Methods

Rating   Name   Duplication   Size   Complexity  
A forThe() 0 5 1
A nextCandidate() 0 3 1
A consider() 0 4 1
A isOngoing() 0 3 1
A __construct() 0 6 1
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