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
+255 -459

No files matched your search

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