WorseThanBestSolutionSkipper   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
c 1
b 0
f 0
dl 0
loc 40
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A forThe() 0 3 1
A consider() 0 6 2
A nextCandidate() 0 10 3
A __construct() 0 3 1
A isOngoing() 0 3 1
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\PuzzleSolver\SearchStrategy;
4
5
use Stratadox\PuzzleSolver\Puzzle;
6
use const INF;
7
8
/**
9
 * Worse-Than-Best Solution Skipper
10
 *
11
 * The Worse-Than-Best Solution Skipper keeps track of the lowest cost of the
12
 * solutions that have been found during the search. Each time a node is
13
 * encountered of which the path cost is more than the cost of the cheapest
14
 * solution that has already been found, the node is skipped.
15
 *
16
 * @author Stratadox
17
 */
18
final class WorseThanBestSolutionSkipper implements SearchStrategy
19
{
20
    /** @var float */
21
    private $lowestSolutionCost = INF;
22
    /** @var SearchStrategy */
23
    private $search;
24
25
    private function __construct(SearchStrategy $search)
26
    {
27
        $this->search = $search;
28
    }
29
30
    public static function forThe(SearchStrategy $search): self
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 ($puzzle->movesSoFar()->cost() > $this->lowestSolutionCost) {
43
            return false;
44
        }
45
        return $this->search->consider($puzzle);
46
    }
47
48
    public function nextCandidate(): Puzzle
49
    {
50
        $puzzle = $this->search->nextCandidate();
51
        if (
52
            $puzzle->isSolved() &&
53
            ($cost = $puzzle->movesSoFar()->cost()) < $this->lowestSolutionCost
54
        ) {
55
            $this->lowestSolutionCost = $cost;
56
        }
57
        return $puzzle;
58
    }
59
}
60