Reformat code

This commit is contained in:
niklas committed 2026-11-12 13:52:04 +01:00
1 parent 51c12cc0ea
commit 60c654936a
31 files changed
+260 -464

No files matched your search

+2 -4
View File
@@ -1,12 +1,10 @@
package machine_learning; package machine_learning;
public enum DataClass public enum DataClass {
{
NEGATIVE, NEGATIVE,
POSITIVE; POSITIVE;
public static DataClass valueOf(final int i) public static DataClass valueOf(final int i) {
{
return i == 0 ? NEGATIVE : POSITIVE; return i == 0 ? NEGATIVE : POSITIVE;
} }
} }
+2 -2
View File
@@ -2,8 +2,8 @@ package machine_learning;
import java.util.List; import java.util.List;
public interface MachineLearning public interface MachineLearning {
{
void learn(List<Vector> positives, List<Vector> negatives); void learn(List<Vector> positives, List<Vector> negatives);
DataClass classify(Vector toClassify); DataClass classify(Vector toClassify);
} }
+30 -47
View File
@@ -1,114 +1,100 @@
package machine_learning; package machine_learning;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
public class Vector public class Vector {
{
private final List<Double> values; private final List<Double> values;
public Vector(final int dim) public Vector(final int dim) {
{
this(IntStream.range(0, dim) this(IntStream.range(0, dim)
.mapToDouble(i -> 0d) .mapToDouble(i -> 0d)
.toArray()); .toArray());
} }
public Vector(final double... value) public Vector(final double... value) {
{
this(Arrays.stream(value) this(Arrays.stream(value)
.boxed() .boxed()
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
public Vector(final List<Double> values) public Vector(final List<Double> values) {
{
this.values = values; this.values = values;
} }
public int dimension() public int dimension() {
{
return this.values.size(); return this.values.size();
} }
public Vector add(final Vector b) public Vector add(final Vector b) {
{
checkEqualDimensions(b); checkEqualDimensions(b);
return new Vector(IntStream.range(0, return new Vector(IntStream.range(0,
this.dimension()) this.dimension())
.mapToObj(i -> this.get(i) + b.get(i)) .mapToObj(i -> this.get(i) + b.get(i))
.collect(Collectors.toList()) .collect(Collectors.toList())
); );
} }
public Vector subtract(final Vector b) public Vector subtract(final Vector b) {
{
checkEqualDimensions(b); checkEqualDimensions(b);
return new Vector(IntStream.range(0, return new Vector(IntStream.range(0,
this.dimension()) this.dimension())
.mapToObj(i -> this.get(i) - b.get(i)) .mapToObj(i -> this.get(i) - b.get(i))
.collect(Collectors.toList()) .collect(Collectors.toList())
); );
} }
public double scalar(final Vector b) public double scalar(final Vector b) {
{
checkEqualDimensions(b); checkEqualDimensions(b);
return IntStream.range(0, return IntStream.range(0,
this.dimension()) this.dimension())
.mapToDouble(i -> this.get(i) * b.get(i)) .mapToDouble(i -> this.get(i) * b.get(i))
.sum(); .sum();
} }
public double euclid() public double euclid() {
{
return Math.sqrt(IntStream.range(0, return Math.sqrt(IntStream.range(0,
this.dimension()) this.dimension())
.mapToDouble(i -> this.get(i) * this.get(i)) .mapToDouble(i -> this.get(i) * this.get(i))
.sum()); .sum());
} }
public double distance(final Vector b) public double distance(final Vector b) {
{
return Math.sqrt(IntStream.range(0, return Math.sqrt(IntStream.range(0,
this.dimension()) this.dimension())
.mapToDouble(i -> (this.get(i) - b.get(i)) * (this.get(i) - b.get(i))) .mapToDouble(i -> (this.get(i) - b.get(i)) * (this.get(i) - b.get(i)))
.sum()); .sum());
} }
public Vector divide(final double div) public Vector divide(final double div) {
{
return new Vector(IntStream.range(0, this.dimension()) return new Vector(IntStream.range(0, this.dimension())
.mapToObj(i -> this.values.get(i) / div) .mapToObj(i -> this.values.get(i) / div)
.collect(Collectors.toCollection(ArrayList::new))); .collect(Collectors.toCollection(ArrayList::new)));
} }
public double get(final int index) public double get(final int index) {
{
return this.values.get(index); return this.values.get(index);
} }
public Vector decreasedDimension() public Vector decreasedDimension() {
{ return new Vector(this.values.subList(0, this.dimension() - 1));
return new Vector(this.values.subList(0, this.dimension()-1));
} }
public Vector normalized() public Vector normalized() {
{
return this.divide(this.euclid()); return this.divide(this.euclid());
} }
@Override @Override
public boolean equals(final Object o) public boolean equals(final Object o) {
{ if (this == o) {
if (this == o)
{
return true; return true;
} }
if (o == null || getClass() != o.getClass()) if (o == null || getClass() != o.getClass()) {
{
return false; return false;
} }
@@ -118,19 +104,16 @@ public class Vector
} }
@Override @Override
public int hashCode() public int hashCode() {
{
return values != null ? values.hashCode() : 0; return values != null ? values.hashCode() : 0;
} }
@Override @Override
public String toString() public String toString() {
{
return this.values.toString(); return this.values.toString();
} }
private void checkEqualDimensions(final Vector b) private void checkEqualDimensions(final Vector b) {
{
if (this.dimension() != b.dimension()) if (this.dimension() != b.dimension())
throw new IllegalArgumentException("Dimensions must be equal"); throw new IllegalArgumentException("Dimensions must be equal");
} }
@@ -3,25 +3,25 @@ package machine_learning.nearest_neighbour;
import machine_learning.DataClass; import machine_learning.DataClass;
import machine_learning.Vector; import machine_learning.Vector;
import java.util.*; import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
public class CrossValidation public class CrossValidation {
{
private final int paramMin; private final int paramMin;
private final int paramMax; private final int paramMax;
public CrossValidation(final int paramMin, final int paramMax) public CrossValidation(final int paramMin, final int paramMax) {
{
this.paramMin = paramMin; this.paramMin = paramMin;
this.paramMax = paramMax; this.paramMax = paramMax;
} }
public KNearestNeighbour validate(final List<Vector> data, final int chunkSize) public KNearestNeighbour validate(final List<Vector> data, final int chunkSize) {
{
Collections.shuffle(data); Collections.shuffle(data);
final var counter = new AtomicInteger(0); final var counter = new AtomicInteger(0);
final var chunks = data.stream() final var chunks = data.stream()
@@ -48,15 +48,13 @@ public class CrossValidation
var failCount = 0; var failCount = 0;
for (final var vector : chunk) for (final var vector : chunk) {
{
final var expectedClass = DataClass.valueOf(Double.valueOf(vector.get(vector.dimension() - 1)).intValue()); final var expectedClass = DataClass.valueOf(Double.valueOf(vector.get(vector.dimension() - 1)).intValue());
final var testVector = vector.decreasedDimension().normalized(); final var testVector = vector.decreasedDimension().normalized();
final var actualClass = kNearestNeighbour.classify(testVector); final var actualClass = kNearestNeighbour.classify(testVector);
if (expectedClass != actualClass) if (expectedClass != actualClass) {
{
failCount++; failCount++;
} }
} }
@@ -80,14 +78,13 @@ public class CrossValidation
return finalKNearestNeighbour; return finalKNearestNeighbour;
} }
private Map<DataClass, List<Vector>> splitIntoClasses(final List<Vector> data) private Map<DataClass, List<Vector>> splitIntoClasses(final List<Vector> data) {
{
var positives = data.parallelStream() var positives = data.parallelStream()
.filter(v -> v.get(v.dimension()-1) == 1) .filter(v -> v.get(v.dimension() - 1) == 1)
.collect(Collectors.toList()); .collect(Collectors.toList());
var negatives = data.parallelStream() var negatives = data.parallelStream()
.filter(v -> v.get(v.dimension()-1) == 0) .filter(v -> v.get(v.dimension() - 1) == 0)
.collect(Collectors.toList()); .collect(Collectors.toList());
positives = positives.parallelStream() positives = positives.parallelStream()
@@ -2,7 +2,6 @@ package machine_learning.nearest_neighbour;
import machine_learning.Vector; import machine_learning.Vector;
public interface DistanceFunction public interface DistanceFunction {
{
double distance(Vector a, Vector b); double distance(Vector a, Vector b);
} }
@@ -10,36 +10,29 @@ import java.util.Random;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
public class KNearestNeighbour implements MachineLearning public class KNearestNeighbour implements MachineLearning {
{ private final DistanceFunction distanceFunction;
private final int k;
private List<Vector> positives; private List<Vector> positives;
private List<Vector> negatives; private List<Vector> negatives;
private final DistanceFunction distanceFunction; public KNearestNeighbour(final DistanceFunction distanceFunction) {
private final int k;
public KNearestNeighbour(final DistanceFunction distanceFunction)
{
this(distanceFunction, 1); this(distanceFunction, 1);
} }
public KNearestNeighbour(final DistanceFunction distanceFunction, final int k) public KNearestNeighbour(final DistanceFunction distanceFunction, final int k) {
{
this.distanceFunction = distanceFunction; this.distanceFunction = distanceFunction;
this.k = k; this.k = k;
} }
@Override @Override
public void learn(final List<Vector> positives, final List<Vector> negatives) public void learn(final List<Vector> positives, final List<Vector> negatives) {
{
this.positives = positives; this.positives = positives;
this.negatives = negatives; this.negatives = negatives;
} }
@Override @Override
public DataClass classify(final Vector toClassify) public DataClass classify(final Vector toClassify) {
{
final var nearestNeighbours = this.nearestNeighbours( final var nearestNeighbours = this.nearestNeighbours(
Stream.concat(this.positives.stream(), this.negatives.stream()) Stream.concat(this.positives.stream(), this.negatives.stream())
.collect(Collectors.toList()), .collect(Collectors.toList()),
@@ -54,20 +47,16 @@ public class KNearestNeighbour implements MachineLearning
.filter(this.negatives::contains) .filter(this.negatives::contains)
.count(); .count();
if (positivesWithNearestNeighboursAmount > negativesWithNearestNeighboursAmount) if (positivesWithNearestNeighboursAmount > negativesWithNearestNeighboursAmount) {
{
return DataClass.POSITIVE; return DataClass.POSITIVE;
} } else if (positivesWithNearestNeighboursAmount < negativesWithNearestNeighboursAmount) {
else if (positivesWithNearestNeighboursAmount < negativesWithNearestNeighboursAmount)
{
return DataClass.NEGATIVE; return DataClass.NEGATIVE;
} }
return new Random().nextBoolean() ? DataClass.POSITIVE : DataClass.NEGATIVE; return new Random().nextBoolean() ? DataClass.POSITIVE : DataClass.NEGATIVE;
} }
private List<Vector> nearestNeighbours(final List<Vector> vectors, final Vector vector) private List<Vector> nearestNeighbours(final List<Vector> vectors, final Vector vector) {
{
return vectors.parallelStream() return vectors.parallelStream()
.map(v -> Map.entry(this.distanceFunction.distance(v, vector), v)) .map(v -> Map.entry(this.distanceFunction.distance(v, vector), v))
.sorted((e1, e2) -> e1.getKey() >= e2.getKey() ? (e1.getKey().equals(e2.getKey()) ? 0 : 1) : -1) .sorted((e1, e2) -> e1.getKey() >= e2.getKey() ? (e1.getKey().equals(e2.getKey()) ? 0 : 1) : -1)
+15 -29
View File
@@ -1,36 +1,29 @@
package machine_learning.perceptron; package machine_learning.perceptron;
import machine_learning.DataClass;
import machine_learning.MachineLearning; import machine_learning.MachineLearning;
import machine_learning.Vector; import machine_learning.Vector;
import machine_learning.DataClass;
import java.util.List; import java.util.List;
public class Perceptron implements MachineLearning public class Perceptron implements MachineLearning {
{
private Vector weight; private Vector weight;
@Override @Override
public void learn(final List<Vector> positives, final List<Vector> negatives) public void learn(final List<Vector> positives, final List<Vector> negatives) {
{
var iterationCounter = 0; var iterationCounter = 0;
this.weight = this.getInitializationVector(positives, negatives); this.weight = this.getInitializationVector(positives, negatives);
do do {
{ for (final var x : positives) {
for (final var x : positives) if (weight.scalar(x) <= 0) {
{
if (weight.scalar(x) <= 0)
{
weight = weight.add(x); weight = weight.add(x);
System.out.println(weight); System.out.println(weight);
} }
} }
for (final var x : negatives) for (final var x : negatives) {
{ if (weight.scalar(x) > 0) {
if (weight.scalar(x) > 0)
{
weight = weight.subtract(x); weight = weight.subtract(x);
System.out.println(weight); System.out.println(weight);
} }
@@ -46,37 +39,30 @@ public class Perceptron implements MachineLearning
} }
@Override @Override
public DataClass classify(final Vector vector) public DataClass classify(final Vector vector) {
{
return this.weight.scalar(vector) > 0 ? DataClass.POSITIVE : DataClass.NEGATIVE; return this.weight.scalar(vector) > 0 ? DataClass.POSITIVE : DataClass.NEGATIVE;
} }
private Vector getInitializationVector(final List<Vector> positives, final List<Vector> negatives) private Vector getInitializationVector(final List<Vector> positives, final List<Vector> negatives) {
{
var a = new Vector(positives.getFirst().dimension()); var a = new Vector(positives.getFirst().dimension());
for (final var x : positives) for (final var x : positives) {
{
a = a.add(x); a = a.add(x);
} }
var b = new Vector(positives.getFirst().dimension()); var b = new Vector(positives.getFirst().dimension());
for (final var x : negatives) for (final var x : negatives) {
{
b = b.add(x); b = b.add(x);
} }
return a.subtract(b); return a.subtract(b);
} }
private boolean elementsAreCorrectClassified(final List<Vector> positives, final List<Vector> negatives, final Vector weight) private boolean elementsAreCorrectClassified(final List<Vector> positives, final List<Vector> negatives, final Vector weight) {
{ for (final var x : positives) {
for (final var x : positives)
{
if (weight.scalar(x) <= 0) return false; if (weight.scalar(x) <= 0) return false;
} }
for (final var x : negatives) for (final var x : negatives) {
{
if (weight.scalar(x) > 0) return false; if (weight.scalar(x) > 0) return false;
} }
+11 -10
View File
@@ -55,23 +55,16 @@ public class ChessKnightNode extends Node<ChessKnightNode.KnightPair> {
return "%c%c".formatted(super.value.col, super.value.row); return "%c%c".formatted(super.value.col, super.value.row);
} }
public record KnightPair(char col, char row) {
public KnightPair {
if (col < 'a' || col > 'h') throw new ChessKnightException("Row out of bounds at index %c".formatted(col));
if (row < '1' || row > '8') throw new ChessKnightException("Column out of bounds at index %c".formatted(row));
}
}
protected enum ChessDirections { protected enum ChessDirections {
TOP_LEFT(-1, 2), TOP_RIGHT(1, 2), TOP_LEFT(-1, 2), TOP_RIGHT(1, 2),
RIGHT_TOP(2, 1), RIGHT_BOTTOM(2, -1), RIGHT_TOP(2, 1), RIGHT_BOTTOM(2, -1),
DOWN_RIGHT(1 ,-2), DOWN_LEFT(-1,-2), DOWN_RIGHT(1, -2), DOWN_LEFT(-1, -2),
LEFT_BOTTOM(-2,-1), LEFT_TOP(-2,1); LEFT_BOTTOM(-2, -1), LEFT_TOP(-2, 1);
public final int colChange; public final int colChange;
public final int rowChange; public final int rowChange;
ChessDirections( final int colChange, final int rowChange) { ChessDirections(final int colChange, final int rowChange) {
this.colChange = colChange; this.colChange = colChange;
this.rowChange = rowChange; this.rowChange = rowChange;
} }
@@ -85,6 +78,14 @@ public class ChessKnightNode extends Node<ChessKnightNode.KnightPair> {
} }
} }
public record KnightPair(char col, char row) {
public KnightPair {
if (col < 'a' || col > 'h') throw new ChessKnightException("Row out of bounds at index %c".formatted(col));
if (row < '1' || row > '8')
throw new ChessKnightException("Column out of bounds at index %c".formatted(row));
}
}
protected static class ChessKnightException extends IndexOutOfBoundsException { protected static class ChessKnightException extends IndexOutOfBoundsException {
public ChessKnightException(final String s) { public ChessKnightException(final String s) {
super(s); super(s);
+1 -2
View File
@@ -1,6 +1,5 @@
package search; package search;
enum Direction enum Direction {
{
TOP, RIGHT, DOWN, LEFT TOP, RIGHT, DOWN, LEFT
} }
+28 -52
View File
@@ -5,55 +5,45 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
public class EightPuzzleNode extends Node<int[][]> public class EightPuzzleNode extends Node<int[][]> {
{ public EightPuzzleNode(final int[][] state) {
public EightPuzzleNode(final int[][] state)
{
super(state); super(state);
} }
private EightPuzzleNode(final int[][] value, final Node<int[][]> parent, final int heuristicCosts) private EightPuzzleNode(final int[][] value, final Node<int[][]> parent, final int heuristicCosts) {
{
super(value, parent, heuristicCosts); super(value, parent, heuristicCosts);
} }
@Override @Override
public boolean isTargetReached(final Node<int[][]> target) public boolean isTargetReached(final Node<int[][]> target) {
{
return valueEquals(target); return valueEquals(target);
} }
@Override @Override
public List<Node<int[][]>> generateSuccessors() public List<Node<int[][]>> generateSuccessors() {
{
final var successors = new ArrayList<Node<int[][]>>(); final var successors = new ArrayList<Node<int[][]>>();
final var emptyPosition = Objects.requireNonNull(detectEmptyPosition()); final var emptyPosition = Objects.requireNonNull(detectEmptyPosition());
final var x = emptyPosition.x(); final var x = emptyPosition.x();
final var y = emptyPosition.y(); final var y = emptyPosition.y();
for (final var dir : Direction.values()) for (final var dir : Direction.values()) {
{
final var newState = copyOfState(); final var newState = copyOfState();
try try {
{
final var posToSwap = switch (dir) { final var posToSwap = switch (dir) {
case TOP -> new IntPair(x, y-1); case TOP -> new IntPair(x, y - 1);
case RIGHT -> new IntPair(x+1, y); case RIGHT -> new IntPair(x + 1, y);
case DOWN -> new IntPair(x, y+1); case DOWN -> new IntPair(x, y + 1);
case LEFT -> new IntPair(x-1, y); case LEFT -> new IntPair(x - 1, y);
}; };
this.swapStateField(newState, emptyPosition, posToSwap); this.swapStateField(newState, emptyPosition, posToSwap);
final var successor = new EightPuzzleNode(newState, this, super.heuristicCosts+1); final var successor = new EightPuzzleNode(newState, this, super.heuristicCosts + 1);
if (!successor.valueEquals(this) && !successor.valueEquals(super.getParent())) if (!successor.valueEquals(this) && !successor.valueEquals(super.getParent())) {
{
successors.add(successor); successors.add(successor);
} }
} } catch (final ArrayIndexOutOfBoundsException ignored) {
catch (final ArrayIndexOutOfBoundsException ignored)
{
} }
} }
@@ -61,31 +51,24 @@ public class EightPuzzleNode extends Node<int[][]>
} }
@Override @Override
public String toString() public String toString() {
{
final var builder = new StringBuilder(); final var builder = new StringBuilder();
for (final var row : super.value) for (final var row : super.value) {
{
builder.append(Arrays.toString(row)).append("\n"); builder.append(Arrays.toString(row)).append("\n");
} }
return builder.toString(); return builder.toString();
} }
private boolean valueEquals(final Node<int[][]> node) private boolean valueEquals(final Node<int[][]> node) {
{ if (node == null) {
if (node == null)
{
return false; return false;
} }
for (var row = 0; row < super.value.length; row++) for (var row = 0; row < super.value.length; row++) {
{ for (var col = 0; col < super.value[row].length; col++) {
for (var col = 0; col < super.value[row].length; col++) if (super.value[row][col] != node.value[row][col]) {
{
if (super.value[row][col] != node.value[row][col])
{
return false; return false;
} }
} }
@@ -94,14 +77,10 @@ public class EightPuzzleNode extends Node<int[][]>
return true; return true;
} }
private IntPair detectEmptyPosition() private IntPair detectEmptyPosition() {
{ for (var row = 0; row < super.value.length; row++) {
for (var row = 0; row < super.value.length; row++) for (var col = 0; col < super.value[row].length; col++) {
{ if (super.value[row][col] == 0) {
for (var col = 0; col < super.value[row].length; col++)
{
if (super.value[row][col] == 0)
{
return new IntPair(col, row); return new IntPair(col, row);
} }
} }
@@ -110,20 +89,17 @@ public class EightPuzzleNode extends Node<int[][]>
return null; return null;
} }
private int[][] copyOfState() private int[][] copyOfState() {
{
final var copy = new int[3][3]; final var copy = new int[3][3];
for (var y = 0; y < copy.length; y++) for (var y = 0; y < copy.length; y++) {
{
System.arraycopy(super.value[y], 0, copy[y], 0, copy.length); System.arraycopy(super.value[y], 0, copy[y], 0, copy.length);
} }
return copy; return copy;
} }
private void swapStateField(final int[][] newState, final IntPair emptyPos, final IntPair posToSwap) private void swapStateField(final int[][] newState, final IntPair emptyPos, final IntPair posToSwap) {
{
final var tmp = newState[posToSwap.y()][posToSwap.x()]; final var tmp = newState[posToSwap.y()][posToSwap.x()];
newState[posToSwap.y()][posToSwap.x()] = newState[emptyPos.y()][emptyPos.x()]; newState[posToSwap.y()][posToSwap.x()] = newState[emptyPos.y()][emptyPos.x()];
newState[emptyPos.y()][emptyPos.x()] = tmp; newState[emptyPos.y()][emptyPos.x()] = tmp;
+1 -2
View File
@@ -1,5 +1,4 @@
package search; package search;
public record IntPair(int x, int y) public record IntPair(int x, int y) {
{
} }
+26 -48
View File
@@ -1,33 +1,29 @@
package search; package search;
import java.util.*; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LabyrinthineNode extends Node<boolean[][]> public class LabyrinthineNode extends Node<boolean[][]> {
{ public LabyrinthineNode(final boolean[][] state) {
public LabyrinthineNode(final boolean[][] state)
{
super(state); super(state);
} }
private LabyrinthineNode(final boolean[][] value, final Node<boolean[][]> parent, final int heuristicCosts) private LabyrinthineNode(final boolean[][] value, final Node<boolean[][]> parent, final int heuristicCosts) {
{
super(value, parent, heuristicCosts); super(value, parent, heuristicCosts);
} }
@Override @Override
public boolean isTargetReached(final Node<boolean[][]> target) public boolean isTargetReached(final Node<boolean[][]> target) {
{
return valueEquals(target); return valueEquals(target);
} }
@Override @Override
public List<Node<boolean[][]>> generateSuccessors() public List<Node<boolean[][]>> generateSuccessors() {
{
final var successors = new ArrayList<Node<boolean[][]>>(); final var successors = new ArrayList<Node<boolean[][]>>();
final var offPositions = detectOffPositions(); final var offPositions = detectOffPositions();
for (final var pos : offPositions) for (final var pos : offPositions) {
{
final var newState = copyOfState(); final var newState = copyOfState();
toggleStateAtPos(newState, new IntPair(pos.x(), pos.y())); toggleStateAtPos(newState, new IntPair(pos.x(), pos.y()));
@@ -38,8 +34,7 @@ public class LabyrinthineNode extends Node<boolean[][]>
final var successor = new LabyrinthineNode(newState, this, super.heuristicCosts + 1); final var successor = new LabyrinthineNode(newState, this, super.heuristicCosts + 1);
if (!successor.valueEquals(this) && !successor.valueEquals(super.getParent())) if (!successor.valueEquals(this) && !successor.valueEquals(super.getParent())) {
{
successors.add(successor); successors.add(successor);
} }
} }
@@ -48,31 +43,24 @@ public class LabyrinthineNode extends Node<boolean[][]>
} }
@Override @Override
public String toString() public String toString() {
{
final var builder = new StringBuilder(); final var builder = new StringBuilder();
for (final var row : super.value) for (final var row : super.value) {
{
builder.append(Arrays.toString(row)).append("\n"); builder.append(Arrays.toString(row)).append("\n");
} }
return builder.toString(); return builder.toString();
} }
private boolean valueEquals(final Node<boolean[][]> node) private boolean valueEquals(final Node<boolean[][]> node) {
{ if (node == null) {
if (node == null)
{
return false; return false;
} }
for (var row = 0; row < super.value.length; row++) for (var row = 0; row < super.value.length; row++) {
{ for (var col = 0; col < super.value[row].length; col++) {
for (var col = 0; col < super.value[row].length; col++) if (super.value[row][col] != node.value[row][col]) {
{
if (super.value[row][col] != node.value[row][col])
{
return false; return false;
} }
} }
@@ -81,16 +69,12 @@ public class LabyrinthineNode extends Node<boolean[][]>
return true; return true;
} }
private List<IntPair> detectOffPositions() private List<IntPair> detectOffPositions() {
{
final var positions = new ArrayList<IntPair>(); final var positions = new ArrayList<IntPair>();
for (var row = 0; row < super.value.length; row++) for (var row = 0; row < super.value.length; row++) {
{ for (var col = 0; col < super.value[row].length; col++) {
for (var col = 0; col < super.value[row].length; col++) if (!super.value[row][col]) {
{
if (!super.value[row][col])
{
positions.add(new IntPair(col, row)); positions.add(new IntPair(col, row));
} }
} }
@@ -99,26 +83,20 @@ public class LabyrinthineNode extends Node<boolean[][]>
return positions; return positions;
} }
private boolean[][] copyOfState() private boolean[][] copyOfState() {
{
final var copy = new boolean[super.value.length][super.value[0].length]; final var copy = new boolean[super.value.length][super.value[0].length];
for (var y = 0; y < copy.length; y++) for (var y = 0; y < copy.length; y++) {
{
System.arraycopy(super.value[y], 0, copy[y], 0, copy.length); System.arraycopy(super.value[y], 0, copy[y], 0, copy.length);
} }
return copy; return copy;
} }
private void toggleStateAtPos(final boolean[][] newState, final IntPair pos) private void toggleStateAtPos(final boolean[][] newState, final IntPair pos) {
{ try {
try
{
newState[pos.y()][pos.x()] = !newState[pos.y()][pos.x()]; newState[pos.y()][pos.x()] = !newState[pos.y()][pos.x()];
} } catch (final ArrayIndexOutOfBoundsException ignored) {
catch (final ArrayIndexOutOfBoundsException ignored)
{
} }
} }
} }
+8 -14
View File
@@ -3,45 +3,39 @@ package search;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
public abstract class Node<T> public abstract class Node<T> {
{
protected final T value; protected final T value;
protected final int heuristicCosts; protected final int heuristicCosts;
private final Node<T> parent; private final Node<T> parent;
private int heuristicEstimation; private int heuristicEstimation;
protected Node(final T value) protected Node(final T value) {
{
this(value, null, 0); this(value, null, 0);
} }
protected Node(final T value, final Node<T> parent, final int heuristicCosts) protected Node(final T value, final Node<T> parent, final int heuristicCosts) {
{
this.value = Objects.requireNonNull(value); this.value = Objects.requireNonNull(value);
this.parent = parent; this.parent = parent;
this.heuristicCosts = heuristicCosts; this.heuristicCosts = heuristicCosts;
} }
public T getValue() public T getValue() {
{
return this.value; return this.value;
} }
public Node<T> getParent() public Node<T> getParent() {
{
return this.parent; return this.parent;
} }
public int getHeuristic() public int getHeuristic() {
{
return heuristicCosts + heuristicEstimation; return heuristicCosts + heuristicEstimation;
} }
public void setHeuristicEstimation(final int heuristicEstimation) public void setHeuristicEstimation(final int heuristicEstimation) {
{
this.heuristicEstimation = heuristicEstimation; this.heuristicEstimation = heuristicEstimation;
} }
public abstract boolean isTargetReached(final Node<T> target); public abstract boolean isTargetReached(final Node<T> target);
public abstract List<Node<T>> generateSuccessors(); public abstract List<Node<T>> generateSuccessors();
} }
+7 -14
View File
@@ -5,39 +5,32 @@ import search.Node;
import java.util.Comparator; import java.util.Comparator;
import java.util.PriorityQueue; import java.util.PriorityQueue;
public class AStar<T> public class AStar<T> {
{
private final HeuristicEstimationFunction<T> heuristicFunction; private final HeuristicEstimationFunction<T> heuristicFunction;
public AStar(final HeuristicEstimationFunction<T> heuristicFunction) public AStar(final HeuristicEstimationFunction<T> heuristicFunction) {
{
this.heuristicFunction = heuristicFunction; this.heuristicFunction = heuristicFunction;
} }
public Node<T> heuristicSearch(final Node<T> start, final Node<T> target) public Node<T> heuristicSearch(final Node<T> start, final Node<T> target) {
{
final var nodes = new PriorityQueue<Node<T>>(Comparator.comparingInt(Node::getHeuristic)); final var nodes = new PriorityQueue<Node<T>>(Comparator.comparingInt(Node::getHeuristic));
start.setHeuristicEstimation(this.heuristicFunction.heuristicEstimation(start, target)); start.setHeuristicEstimation(this.heuristicFunction.heuristicEstimation(start, target));
nodes.add(start); nodes.add(start);
while (true) while (true) {
{ if (nodes.isEmpty()) {
if (nodes.isEmpty())
{
return null; return null;
} }
final var node = nodes.poll(); final var node = nodes.poll();
if (node.isTargetReached(target)) if (node.isTargetReached(target)) {
{
return node; return node;
} }
final var successors = node.generateSuccessors(); final var successors = node.generateSuccessors();
for (final var successor : successors) for (final var successor : successors) {
{
successor.setHeuristicEstimation(this.heuristicFunction.heuristicEstimation(successor, target)); successor.setHeuristicEstimation(this.heuristicFunction.heuristicEstimation(successor, target));
} }
@@ -2,7 +2,6 @@ package search.heuristic;
import search.Node; import search.Node;
public interface HeuristicEstimationFunction<T> public interface HeuristicEstimationFunction<T> {
{
int heuristicEstimation(Node<T> node, Node<T> target); int heuristicEstimation(Node<T> node, Node<T> target);
} }
@@ -5,24 +5,19 @@ import search.Node;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
public class BreadthFirstSearch public class BreadthFirstSearch {
{ public <T> Node<T> breadthFirstSearch(final List<Node<T>> nodes, final Node<T> target) {
public <T> Node<T> breadthFirstSearch(final List<Node<T>> nodes, final Node<T> target)
{
final var newNodes = new ArrayList<Node<T>>(); final var newNodes = new ArrayList<Node<T>>();
for (final var node : nodes) for (final var node : nodes) {
{ if (node.isTargetReached(target)) {
if (node.isTargetReached(target))
{
return node; return node;
} }
newNodes.addAll(node.generateSuccessors()); newNodes.addAll(node.generateSuccessors());
} }
if (!newNodes.isEmpty()) if (!newNodes.isEmpty()) {
{
return breadthFirstSearch(newNodes, target); return breadthFirstSearch(newNodes, target);
} }
@@ -2,23 +2,18 @@ package search.uninformed.depthfirstsearch;
import search.Node; import search.Node;
public class DepthFirstSearch public class DepthFirstSearch {
{ public <T> Node<T> depthFirstSearch(final Node<T> node, final Node<T> target) {
public <T> Node<T> depthFirstSearch(final Node<T> node, final Node<T> target) if (node.isTargetReached(target)) {
{
if (node.isTargetReached(target))
{
return node; return node;
} }
final var newNodes = node.generateSuccessors(); final var newNodes = node.generateSuccessors();
while (!newNodes.isEmpty()) while (!newNodes.isEmpty()) {
{
final var resultNode = depthFirstSearch(newNodes.getFirst(), target); final var resultNode = depthFirstSearch(newNodes.getFirst(), target);
if (resultNode != null) if (resultNode != null) {
{
return resultNode; return resultNode;
} }
@@ -2,16 +2,13 @@ package search.uninformed.iterativedeepening;
import search.Node; import search.Node;
public class IterativeDeepening public class IterativeDeepening {
{ public <T> Node<T> iterativeDeepening(final Node<T> node, final Node<T> target) {
public <T> Node<T> iterativeDeepening(final Node<T> node, final Node<T> target)
{
var lowBarrier = 0; var lowBarrier = 0;
Node<T> resultNode; Node<T> resultNode;
do do {
{
resultNode = depthFirstSearch(node, target, 0, lowBarrier++); resultNode = depthFirstSearch(node, target, 0, lowBarrier++);
} }
while (resultNode == null); while (resultNode == null);
@@ -19,21 +16,17 @@ public class IterativeDeepening
return resultNode; return resultNode;
} }
private <T> Node<T> depthFirstSearch(final Node<T> node, final Node<T> target, int depth, final int barrier) private <T> Node<T> depthFirstSearch(final Node<T> node, final Node<T> target, int depth, final int barrier) {
{ if (node.isTargetReached(target)) {
if (node.isTargetReached(target))
{
return node; return node;
} }
final var newNodes = node.generateSuccessors(); final var newNodes = node.generateSuccessors();
while (!newNodes.isEmpty() && depth < barrier) while (!newNodes.isEmpty() && depth < barrier) {
{
final var resultNode = depthFirstSearch(newNodes.getFirst(), target, ++depth, barrier); final var resultNode = depthFirstSearch(newNodes.getFirst(), target, ++depth, barrier);
if (resultNode != null) if (resultNode != null) {
{
return resultNode; return resultNode;
} }
+11 -21
View File
@@ -2,14 +2,12 @@ package machine_learning;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertEquals;
class VectorTest class VectorTest {
{
@Test @Test
void shouldInitializeZeroVector() void shouldInitializeZeroVector() {
{
final var v = new Vector(3); final var v = new Vector(3);
final var expected = new Vector(0d, 0d, 0d); final var expected = new Vector(0d, 0d, 0d);
@@ -19,8 +17,7 @@ class VectorTest
} }
@Test @Test
void shouldReturnCorrectVectorWhenAdding() void shouldReturnCorrectVectorWhenAdding() {
{
final var v1 = new Vector(1d, 2d); final var v1 = new Vector(1d, 2d);
final var v2 = new Vector(3d, 4d); final var v2 = new Vector(3d, 4d);
@@ -31,8 +28,7 @@ class VectorTest
} }
@Test @Test
void shouldReturnCorrectVectorWhenSubtracting() void shouldReturnCorrectVectorWhenSubtracting() {
{
final var v1 = new Vector(1d, 2d); final var v1 = new Vector(1d, 2d);
final var v2 = new Vector(3d, 4d); final var v2 = new Vector(3d, 4d);
@@ -43,8 +39,7 @@ class VectorTest
} }
@Test @Test
void shouldReturnCorrectVectorWhenScalarMultiplying() void shouldReturnCorrectVectorWhenScalarMultiplying() {
{
final var v1 = new Vector(1d, 2d); final var v1 = new Vector(1d, 2d);
final var v2 = new Vector(3d, 4d); final var v2 = new Vector(3d, 4d);
@@ -55,8 +50,7 @@ class VectorTest
} }
@Test @Test
void shouldReturnCorrectVectorWhenEuclid() void shouldReturnCorrectVectorWhenEuclid() {
{
final var v1 = new Vector(1d, 2d); final var v1 = new Vector(1d, 2d);
final var actual = v1.euclid(); final var actual = v1.euclid();
@@ -66,8 +60,7 @@ class VectorTest
} }
@Test @Test
void shouldReturnCorrectDistance() void shouldReturnCorrectDistance() {
{
final var v1 = new Vector(1d, 2d); final var v1 = new Vector(1d, 2d);
final var v2 = new Vector(3d, 4d); final var v2 = new Vector(3d, 4d);
@@ -78,8 +71,7 @@ class VectorTest
} }
@Test @Test
void shouldReturnCorrectVectorWhenDividing() void shouldReturnCorrectVectorWhenDividing() {
{
final var v1 = new Vector(1d, 2d); final var v1 = new Vector(1d, 2d);
final var div = 2d; final var div = 2d;
@@ -90,8 +82,7 @@ class VectorTest
} }
@Test @Test
void shouldDecreaseDimensionCorrect() void shouldDecreaseDimensionCorrect() {
{
final var v = new Vector(1d, 2d, 3d, 4d); final var v = new Vector(1d, 2d, 3d, 4d);
final var decreasedDimensionVector = v.decreasedDimension(); final var decreasedDimensionVector = v.decreasedDimension();
@@ -103,8 +94,7 @@ class VectorTest
} }
@Test @Test
void shouldNormalizeCorrect() void shouldNormalizeCorrect() {
{
final var v = new Vector(4d, 4d, 4d, 4d); final var v = new Vector(4d, 4d, 4d, 4d);
final var actual = v.normalized(); final var actual = v.normalized();
@@ -18,18 +18,16 @@ import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.assertEquals;
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestInstance(TestInstance.Lifecycle.PER_CLASS)
class KNearestNeighbourTest class KNearestNeighbourTest {
{
private List<Vector> positives; private List<Vector> positives;
private List<Vector> negatives; private List<Vector> negatives;
private DistanceFunction distanceFunction; private DistanceFunction distanceFunction;
@BeforeAll @BeforeAll
void initLearnData() void initLearnData() {
{
this.positives = new ArrayList<>(List.of( this.positives = new ArrayList<>(List.of(
new Vector(8d, 4d), new Vector(8d, 4d),
new Vector(8d, 6d), new Vector(8d, 6d),
@@ -48,8 +46,7 @@ class KNearestNeighbourTest
} }
@Test @Test
public void shouldReturnCorrectClassForVectorWithKEquals3() public void shouldReturnCorrectClassForVectorWithKEquals3() {
{
final var kNearestNeighbour = new KNearestNeighbour(this.distanceFunction, 3); final var kNearestNeighbour = new KNearestNeighbour(this.distanceFunction, 3);
kNearestNeighbour.learn(this.positives, this.negatives); kNearestNeighbour.learn(this.positives, this.negatives);
final var vector = new Vector(8, 3.5); final var vector = new Vector(8, 3.5);
@@ -61,8 +58,7 @@ class KNearestNeighbourTest
} }
@Test @Test
public void shouldReturnCorrectClassForVectorWithKEquals5() public void shouldReturnCorrectClassForVectorWithKEquals5() {
{
final var kNearestNeighbour = new KNearestNeighbour(this.distanceFunction, 5); final var kNearestNeighbour = new KNearestNeighbour(this.distanceFunction, 5);
kNearestNeighbour.learn(this.positives, this.negatives); kNearestNeighbour.learn(this.positives, this.negatives);
final var vector = new Vector(8, 3.5); final var vector = new Vector(8, 3.5);
@@ -74,8 +70,7 @@ class KNearestNeighbourTest
} }
@Test @Test
public void shouldReturnCorrectClassesForAppendicitisData() public void shouldReturnCorrectClassesForAppendicitisData() {
{
final var trainDataFile = "./resources/app1.data"; final var trainDataFile = "./resources/app1.data";
final var testDataFile = "./resources/app1.test"; final var testDataFile = "./resources/app1.test";
@@ -91,20 +86,16 @@ class KNearestNeighbourTest
final var testDataVectors = readFromFile(testDataFile); final var testDataVectors = readFromFile(testDataFile);
var failCount = 0; var failCount = 0;
for (final var vector : testDataVectors) for (final var vector : testDataVectors) {
{
final var expectedClass = DataClass.valueOf(Double.valueOf(vector.get(vector.dimension() - 1)).intValue()); final var expectedClass = DataClass.valueOf(Double.valueOf(vector.get(vector.dimension() - 1)).intValue());
final var testVector = vector.decreasedDimension(); final var testVector = vector.decreasedDimension();
final var actualClass = kNearestNeighbour.classify(testVector.normalized()); final var actualClass = kNearestNeighbour.classify(testVector.normalized());
try try {
{
assertEquals(expectedClass, actualClass); assertEquals(expectedClass, actualClass);
} } catch (final AssertionFailedError e) {
catch (final AssertionFailedError e)
{
failCount++; failCount++;
} }
} }
@@ -115,8 +106,7 @@ class KNearestNeighbourTest
@Disabled("Takes long") @Disabled("Takes long")
@Test @Test
public void shouldReturnOptimum() public void shouldReturnOptimum() {
{
final var trainDataFile = "./resources/app1.data"; final var trainDataFile = "./resources/app1.data";
final var testDataFile = "./resources/app1.test"; final var testDataFile = "./resources/app1.test";
@@ -130,16 +120,13 @@ class KNearestNeighbourTest
final var kNearestNeighbour = crossValidation.validate(data, data.size()); final var kNearestNeighbour = crossValidation.validate(data, data.size());
} }
private List<Vector> readFromFile(final String file) private List<Vector> readFromFile(final String file) {
{
final List<Vector> vectorList = new ArrayList<>(); final List<Vector> vectorList = new ArrayList<>();
try (final var reader = new BufferedReader(new FileReader(file))) try (final var reader = new BufferedReader(new FileReader(file))) {
{
String line; String line;
while ((line = reader.readLine()) != null) while ((line = reader.readLine()) != null) {
{
vectorList.add(new Vector( vectorList.add(new Vector(
Arrays.stream(line.split(",")) Arrays.stream(line.split(","))
.map(Double::valueOf) .map(Double::valueOf)
@@ -147,23 +134,20 @@ class KNearestNeighbourTest
)); ));
} }
} } catch (final IOException e) {
catch (final IOException e)
{
e.printStackTrace(); e.printStackTrace();
} }
return vectorList; return vectorList;
} }
private Map<DataClass, List<Vector>> splitIntoClasses(final List<Vector> data) private Map<DataClass, List<Vector>> splitIntoClasses(final List<Vector> data) {
{
var positives = data.stream() var positives = data.stream()
.filter(v -> v.get(v.dimension()-1) == 1) .filter(v -> v.get(v.dimension() - 1) == 1)
.collect(Collectors.toList()); .collect(Collectors.toList());
var negatives = data.stream() var negatives = data.stream()
.filter(v -> v.get(v.dimension()-1) == 0) .filter(v -> v.get(v.dimension() - 1) == 0)
.collect(Collectors.toList()); .collect(Collectors.toList());
positives = positives.stream() positives = positives.stream()
@@ -2,21 +2,22 @@ package machine_learning.perceptron;
import machine_learning.DataClass; import machine_learning.DataClass;
import machine_learning.Vector; import machine_learning.Vector;
import org.junit.jupiter.api.*; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@TestInstance(TestInstance.Lifecycle.PER_CLASS) @TestInstance(TestInstance.Lifecycle.PER_CLASS)
class PerceptronTest class PerceptronTest {
{
List<Vector> positives; List<Vector> positives;
List<Vector> negatives; List<Vector> negatives;
Perceptron perceptron; Perceptron perceptron;
@BeforeAll @BeforeAll
void initLearnData() void initLearnData() {
{
final double biasUnit = 1d; final double biasUnit = 1d;
this.positives = new ArrayList<>(List.of( this.positives = new ArrayList<>(List.of(
new Vector(8d, 4d, biasUnit), new Vector(8d, 4d, biasUnit),
@@ -37,8 +38,7 @@ class PerceptronTest
} }
@Test @Test
void shouldClassifyVectorCorrectAsNegative() void shouldClassifyVectorCorrectAsNegative() {
{
final var vector = new Vector(0d, 0d, 1d); final var vector = new Vector(0d, 0d, 1d);
final var actualClass = this.perceptron.classify(vector); final var actualClass = this.perceptron.classify(vector);
@@ -48,8 +48,7 @@ class PerceptronTest
} }
@Test @Test
void shouldClassifyVectorCorrectAsPositive() void shouldClassifyVectorCorrectAsPositive() {
{
final var vector = new Vector(9d, 3d, 1d); final var vector = new Vector(9d, 3d, 1d);
final var actualClass = this.perceptron.classify(vector); final var actualClass = this.perceptron.classify(vector);
+6 -12
View File
@@ -3,11 +3,9 @@ package search;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class ChessKnightNodeTest public class ChessKnightNodeTest {
{
@Test @Test
public void shouldReturnTrueWhenTargetReached() public void shouldReturnTrueWhenTargetReached() {
{
final var state = new ChessKnightNode.KnightPair('a', '1'); final var state = new ChessKnightNode.KnightPair('a', '1');
final var node = new ChessKnightNode(state); final var node = new ChessKnightNode(state);
@@ -17,8 +15,7 @@ public class ChessKnightNodeTest
} }
@Test @Test
public void shouldReturnFalseWhenTargetNotReached() public void shouldReturnFalseWhenTargetNotReached() {
{
final var actualState = new ChessKnightNode.KnightPair('a', '1'); final var actualState = new ChessKnightNode.KnightPair('a', '1');
final var targetState = new ChessKnightNode.KnightPair('h', '8'); final var targetState = new ChessKnightNode.KnightPair('h', '8');
@@ -30,8 +27,7 @@ public class ChessKnightNodeTest
} }
@Test @Test
public void shouldReturnNonEmptyListOfSuccessors() public void shouldReturnNonEmptyListOfSuccessors() {
{
final var state = new ChessKnightNode.KnightPair('a', '1'); final var state = new ChessKnightNode.KnightPair('a', '1');
final var node = new ChessKnightNode(state); final var node = new ChessKnightNode(state);
@@ -41,8 +37,7 @@ public class ChessKnightNodeTest
} }
@Test @Test
public void shouldReturnCorrectSuccessorsWithMaxPossibleSuccessors() public void shouldReturnCorrectSuccessorsWithMaxPossibleSuccessors() {
{
final var state = new ChessKnightNode.KnightPair('f', '3'); final var state = new ChessKnightNode.KnightPair('f', '3');
final var node = new ChessKnightNode(state); final var node = new ChessKnightNode(state);
@@ -71,8 +66,7 @@ public class ChessKnightNodeTest
} }
@Test @Test
public void shouldReturnCorrectSuccessorsOnEdge() public void shouldReturnCorrectSuccessorsOnEdge() {
{
final var state = new ChessKnightNode.KnightPair('a', '1'); final var state = new ChessKnightNode.KnightPair('a', '1');
final var node = new ChessKnightNode(state); final var node = new ChessKnightNode(state);
+3 -6
View File
@@ -9,11 +9,9 @@ import java.util.List;
import static search.SearchTestUtils.countNodes; import static search.SearchTestUtils.countNodes;
import static search.SearchTestUtils.printSolution; import static search.SearchTestUtils.printSolution;
public class ChessKnightTest public class ChessKnightTest {
{
@Test @Test
public void shouldReturnOne() public void shouldReturnOne() {
{
final var state = new ChessKnightNode.KnightPair('a', '3'); final var state = new ChessKnightNode.KnightPair('a', '3');
final var root = new ChessKnightNode(state); final var root = new ChessKnightNode(state);
@@ -31,8 +29,7 @@ public class ChessKnightTest
} }
@Test @Test
public void shouldReturnThree() public void shouldReturnThree() {
{
final var state = new ChessKnightNode.KnightPair('a', '1'); final var state = new ChessKnightNode.KnightPair('a', '1');
final var root = new ChessKnightNode(state); final var root = new ChessKnightNode(state);
+5 -10
View File
@@ -3,11 +3,9 @@ package search;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
class EightPuzzleNodeTest class EightPuzzleNodeTest {
{
@Test @Test
public void shouldReturnTrueWhenTargetReached() public void shouldReturnTrueWhenTargetReached() {
{
final int[][] state = { final int[][] state = {
{1, 2, 3}, {1, 2, 3},
{4, 5, 6}, {4, 5, 6},
@@ -21,8 +19,7 @@ class EightPuzzleNodeTest
} }
@Test @Test
public void shouldReturnFalseWhenTargetNotReached() public void shouldReturnFalseWhenTargetNotReached() {
{
final int[][] actualState = { final int[][] actualState = {
{7, 1, 6}, {7, 1, 6},
{0, 4, 2}, {0, 4, 2},
@@ -42,8 +39,7 @@ class EightPuzzleNodeTest
} }
@Test @Test
public void shouldReturnNonEmptyListOfSuccessors() public void shouldReturnNonEmptyListOfSuccessors() {
{
final int[][] state = { final int[][] state = {
{7, 1, 6}, {7, 1, 6},
{0, 4, 2}, {0, 4, 2},
@@ -57,8 +53,7 @@ class EightPuzzleNodeTest
} }
@Test @Test
public void shouldReturnCorrectSuccessors() public void shouldReturnCorrectSuccessors() {
{
final int[][] state = { final int[][] state = {
{7, 1, 6}, {7, 1, 6},
{0, 4, 2}, {0, 4, 2},
+5 -9
View File
@@ -5,13 +5,11 @@ import search.uninformed.iterativedeepening.IterativeDeepening;
import static search.SearchTestUtils.printSolution; import static search.SearchTestUtils.printSolution;
public class GameHelperTest public class GameHelperTest {
{
@Test @Test
void shouldReturnCorrectTargetDemonologist() void shouldReturnCorrectTargetDemonologist() {
{
final int[][] state = { final int[][] state = {
{8, 4 ,0}, {8, 4, 0},
{6, 3, 1}, {6, 3, 1},
{2, 5, 7} {2, 5, 7}
}; };
@@ -30,8 +28,7 @@ public class GameHelperTest
} }
@Test @Test
void shouldReturnCorrectTargetWartales() void shouldReturnCorrectTargetWartales() {
{
final int[][] state = { final int[][] state = {
{1, 8, 6}, {1, 8, 6},
{3, 2, 7}, {3, 2, 7},
@@ -52,8 +49,7 @@ public class GameHelperTest
} }
@Test @Test
void shouldReturnCorrectTargetLabyrinthine() void shouldReturnCorrectTargetLabyrinthine() {
{
final boolean[][] state = { final boolean[][] state = {
{true, false, true}, {true, false, true},
{false, true, false}, {false, true, false},
+6 -12
View File
@@ -3,11 +3,9 @@ package search;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
class LabyrinthineNodeTest class LabyrinthineNodeTest {
{
@Test @Test
public void shouldReturnTrueWhenTargetReached() public void shouldReturnTrueWhenTargetReached() {
{
final boolean[][] state = { final boolean[][] state = {
{true, true, true}, {true, true, true},
{true, true, true}, {true, true, true},
@@ -21,8 +19,7 @@ class LabyrinthineNodeTest
} }
@Test @Test
public void shouldReturnFalseWhenTargetNotReached() public void shouldReturnFalseWhenTargetNotReached() {
{
final boolean[][] actualState = { final boolean[][] actualState = {
{true, false, true}, {true, false, true},
{false, true, false}, {false, true, false},
@@ -42,8 +39,7 @@ class LabyrinthineNodeTest
} }
@Test @Test
public void shouldReturnNonEmptyListOfSuccessors() public void shouldReturnNonEmptyListOfSuccessors() {
{
final boolean[][] state = { final boolean[][] state = {
{true, false, true}, {true, false, true},
{false, true, false}, {false, true, false},
@@ -57,8 +53,7 @@ class LabyrinthineNodeTest
} }
@Test @Test
public void shouldReturnCorrectSuccessor() public void shouldReturnCorrectSuccessor() {
{
final boolean[][] state = { final boolean[][] state = {
{true, false, true}, {true, false, true},
{true, true, true}, {true, true, true},
@@ -82,8 +77,7 @@ class LabyrinthineNodeTest
} }
@Test @Test
public void shouldReturnCorrectSuccessors() public void shouldReturnCorrectSuccessors() {
{
final boolean[][] state = { final boolean[][] state = {
{true, false, true}, {true, false, true},
{true, true, false}, {true, true, false},
+5 -10
View File
@@ -1,16 +1,13 @@
package search; package search;
public class SearchTestUtils public class SearchTestUtils {
{ public static <T> void printSolution(final Node<T> targetNode) {
public static <T> void printSolution(final Node<T> targetNode)
{
var node = targetNode; var node = targetNode;
System.out.println("Read from down to top!"); System.out.println("Read from down to top!");
System.out.println("END"); System.out.println("END");
while (node != null) while (node != null) {
{
System.out.println(node); System.out.println(node);
node = node.getParent(); node = node.getParent();
} }
@@ -18,13 +15,11 @@ public class SearchTestUtils
System.out.println("START"); System.out.println("START");
} }
public static <T> int countNodes(final Node<T> targetNode) public static <T> int countNodes(final Node<T> targetNode) {
{
var node = targetNode; var node = targetNode;
int nodeCount = 0; int nodeCount = 0;
while (node != null) while (node != null) {
{
nodeCount++; nodeCount++;
node = node.getParent(); node = node.getParent();
} }
+14 -28
View File
@@ -7,11 +7,9 @@ import search.Node;
import static search.SearchTestUtils.printSolution; import static search.SearchTestUtils.printSolution;
class AStarTest class AStarTest {
{
@Test @Test
void shouldReturnCorrectTargetCubekNodeHeuristic1() void shouldReturnCorrectTargetCubekNodeHeuristic1() {
{
final int[][] state = { final int[][] state = {
{2, 0, 4}, {2, 0, 4},
{6, 7, 1}, {6, 7, 1},
@@ -32,8 +30,7 @@ class AStarTest
} }
@Test @Test
void shouldReturnCorrectTargetCubekNodeHeuristic2() void shouldReturnCorrectTargetCubekNodeHeuristic2() {
{
final int[][] state = { final int[][] state = {
{2, 0, 4}, {2, 0, 4},
{6, 7, 1}, {6, 7, 1},
@@ -53,18 +50,14 @@ class AStarTest
printSolution(actual); printSolution(actual);
} }
private int h1(final Node<int[][]> node, final Node<int[][]> target) private int h1(final Node<int[][]> node, final Node<int[][]> target) {
{
final var value = node.getValue(); final var value = node.getValue();
final var targetValue = target.getValue(); final var targetValue = target.getValue();
var counter = 0; var counter = 0;
for (var row = 0; row < value.length; row++) for (var row = 0; row < value.length; row++) {
{ for (var col = 0; col < value[row].length; col++) {
for (var col = 0; col < value[row].length; col++) if (value[row][col] != 0 && value[row][col] != targetValue[row][col]) {
{
if (value[row][col] != 0 && value[row][col] != targetValue[row][col])
{
counter++; counter++;
} }
} }
@@ -73,19 +66,16 @@ class AStarTest
return counter; return counter;
} }
private int h2(final Node<int[][]> node, final Node<int[][]> target) private int h2(final Node<int[][]> node, final Node<int[][]> target) {
{
final var value = node.getValue(); final var value = node.getValue();
final var targetValue = target.getValue(); final var targetValue = target.getValue();
var manhattanDistance = 0; var manhattanDistance = 0;
for (int i = 1; i <= 8; i++) for (int i = 1; i <= 8; i++) {
{
final var targetPos = detectPositionOf(i, targetValue); final var targetPos = detectPositionOf(i, targetValue);
final var actualPos = detectPositionOf(i, value); final var actualPos = detectPositionOf(i, value);
if (targetPos != null && actualPos != null) if (targetPos != null && actualPos != null) {
{
final var xDistance = Math.abs(targetPos.x() - actualPos.x()); final var xDistance = Math.abs(targetPos.x() - actualPos.x());
final var yDistance = Math.abs(targetPos.y() - actualPos.y()); final var yDistance = Math.abs(targetPos.y() - actualPos.y());
@@ -96,14 +86,10 @@ class AStarTest
return manhattanDistance; return manhattanDistance;
} }
private IntPair detectPositionOf(final int i, final int[][] value) private IntPair detectPositionOf(final int i, final int[][] value) {
{ for (var row = 0; row < value.length; row++) {
for (var row = 0; row < value.length; row++) for (var col = 0; col < value[row].length; col++) {
{ if (value[row][col] == i) {
for (var col = 0; col < value[row].length; col++)
{
if (value[row][col] == i)
{
return new IntPair(col, row); return new IntPair(col, row);
} }
} }
@@ -7,11 +7,9 @@ import java.util.List;
import static search.SearchTestUtils.printSolution; import static search.SearchTestUtils.printSolution;
class BreadthFirstSearchTest class BreadthFirstSearchTest {
{
@Test @Test
void shouldReturnCorrectTarget() void shouldReturnCorrectTarget() {
{
final int[][] state = { final int[][] state = {
{5, 0, 3}, {5, 0, 3},
{2, 1, 6}, {2, 1, 6},
@@ -32,8 +30,7 @@ class BreadthFirstSearchTest
} }
@Test @Test
void shouldReturnCorrectTargetCubekNode() void shouldReturnCorrectTargetCubekNode() {
{
final int[][] state = { final int[][] state = {
{2, 0, 4}, {2, 0, 4},
{6, 7, 1}, {6, 7, 1},
@@ -5,11 +5,9 @@ import search.EightPuzzleNode;
import static search.SearchTestUtils.printSolution; import static search.SearchTestUtils.printSolution;
class DepthFirstSearchTest class DepthFirstSearchTest {
{
@Test @Test
void shouldReturnCorrectTarget() void shouldReturnCorrectTarget() {
{
final int[][] state = { final int[][] state = {
{1, 2, 3}, {1, 2, 3},
{4, 5, 6}, {4, 5, 6},
@@ -5,11 +5,9 @@ import search.EightPuzzleNode;
import static search.SearchTestUtils.printSolution; import static search.SearchTestUtils.printSolution;
class IterativeDeepeningTest class IterativeDeepeningTest {
{
@Test @Test
void shouldReturnCorrectTargetEightPuzzle() void shouldReturnCorrectTargetEightPuzzle() {
{
final int[][] state = { final int[][] state = {
{5, 0, 3}, {5, 0, 3},
{2, 1, 6}, {2, 1, 6},
@@ -30,8 +28,7 @@ class IterativeDeepeningTest
} }
@Test @Test
void shouldReturnCorrectTargetCubekNodeEightPuzzle() void shouldReturnCorrectTargetCubekNodeEightPuzzle() {
{
final int[][] state = { final int[][] state = {
{2, 0, 4}, {2, 0, 4},
{6, 7, 1}, {6, 7, 1},