BreadthFirstStrategy::nextCandidate()   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 0
dl 0
loc 3
rs 10
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\PuzzleSolver\SearchStrategy;
4
5
use SplQueue;
6
use Stratadox\PuzzleSolver\Puzzle;
7
use Stratadox\PuzzleSolver\Moves;
8
9
/**
10
 * Breadth-first search strategy
11
 *
12
 * Breadth-first searches continuously explore all available options, before
13
 * passing into the options available after those.
14
 *
15
 * @author Stratadox
16
 */
17
final class BreadthFirstStrategy implements SearchStrategy
18
{
19
    /** @var SplQueue */
20
    private $queue;
21
    /** @var Puzzle */
22
    private $originalPuzzle;
23
24
    private function __construct(
25
        SplQueue $queue,
26
        Puzzle $originalPuzzle
27
    ) {
28
        $this->queue = $queue;
29
        $this->originalPuzzle = $originalPuzzle;
30
    }
31
32
    public static function forThe(Puzzle $puzzle): SearchStrategy
33
    {
34
        $queue = new SplQueue();
35
        $queue->enqueue(Moves::none());
36
        return new self($queue, $puzzle);
37
    }
38
39
    public function isOngoing(): bool
40
    {
41
        return !$this->queue->isEmpty();
42
    }
43
44
    public function consider(Puzzle $puzzle): bool
45
    {
46
        $this->queue->enqueue($puzzle->movesSoFar());
47
        return true;
48
    }
49
50
    public function nextCandidate(): Puzzle
51
    {
52
        return $this->originalPuzzle->afterMaking(...$this->queue->dequeue());
53
    }
54
}
55