Merge branch 'master' into half-wit4u-master

This commit is contained in:
slavisa-baeldung 2017-07-05 12:56:07 +01:00
commit da56de8794
26 changed files with 556 additions and 16 deletions

View File

@ -186,4 +186,4 @@ public class HillClimbing {
return stackHeuristics;
}
}
}

View File

@ -40,4 +40,4 @@ public class State {
public void setHeuristics(int heuristics) {
this.heuristics = heuristics;
}
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.minimax;
import java.util.ArrayList;
import java.util.List;
public class GameOfBones {
public static List<Integer> getPossibleStates(int noOfBonesInHeap) {
List<Integer> listOfPossibleHeaps = new ArrayList<>();
for (int i = 1; i <= 3; i++) {
int newHeapCount = noOfBonesInHeap - i;
if (newHeapCount >= 0) {
listOfPossibleHeaps.add(newHeapCount);
}
}
return listOfPossibleHeaps;
}
}

View File

@ -0,0 +1,68 @@
package com.baeldung.algorithms.minimax;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MiniMax {
private Tree tree;
public Tree getTree() {
return tree;
}
public void setTree(Tree tree) {
this.tree = tree;
}
public void constructTree(int noOfBones) {
tree = new Tree();
Node root = new Node(noOfBones, true);
tree.setRoot(root);
constructTree(root);
}
private void constructTree(Node node) {
List<Integer> listofPossibleHeaps = GameOfBones.getPossibleStates(node.getNoOfBones());
boolean isMaxPlayer = !node.isMaxPlayer();
listofPossibleHeaps.forEach(n -> {
Node newNode = new Node(n, isMaxPlayer);
node.addChild(newNode);
if (newNode.getNoOfBones() > 0) {
constructTree(newNode);
}
});
}
public boolean checkWin() {
Node root = tree.getRoot();
checkWin(root);
return root.getScore() == 1 ? true : false;
}
private void checkWin(Node node) {
List<Node> children = node.getChildren();
boolean isMaxPlayer = node.isMaxPlayer();
children.forEach(child -> {
if (child.getNoOfBones() == 0) {
if (isMaxPlayer) {
child.setScore(1);
} else {
child.setScore(-1);
}
} else {
checkWin(child);
}
});
Node bestChild = findBestChild(isMaxPlayer, children);
node.setScore(bestChild.getScore());
}
private Node findBestChild(boolean isMaxPlayer, List<Node> children) {
if (isMaxPlayer) {
return Collections.max(children, Comparator.comparing(c -> c.getScore()));
} else {
return Collections.min(children, Comparator.comparing(c -> c.getScore()));
}
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.algorithms.minimax;
import java.util.ArrayList;
import java.util.List;
public class Node {
private int noOfBones;
private boolean isMaxPlayer;
private int score;
private List<Node> children;
public Node(int noOfBones, boolean isMaxPlayer) {
this.noOfBones = noOfBones;
this.isMaxPlayer = isMaxPlayer;
children = new ArrayList<>();
}
public int getNoOfBones() {
return noOfBones;
}
public void setNoOfBones(int noOfBones) {
this.noOfBones = noOfBones;
}
public boolean isMaxPlayer() {
return isMaxPlayer;
}
public void setMaxPlayer(boolean maxPlayer) {
isMaxPlayer = maxPlayer;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public void addChild(Node newNode) {
children.add(newNode);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.algorithms.minimax;
public class Tree {
private Node root;
public Tree() {
}
public Tree(Node root) {
this.root = root;
}
public Node getRoot() {
return root;
}
public void setRoot(Node root) {
this.root = root;
}
}

View File

@ -55,4 +55,4 @@ public class HillClimbingAlgorithmTest {
State nextState = hillClimbing.findNextState(currentState, goalStack);
assertTrue(nextState.getHeuristics() > currentState.getHeuristics());
}
}
}

View File

@ -0,0 +1,92 @@
package algorithms;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.algorithms.mcts.montecarlo.MonteCarloTreeSearch;
import com.baeldung.algorithms.mcts.montecarlo.State;
import com.baeldung.algorithms.mcts.montecarlo.UCT;
import com.baeldung.algorithms.mcts.tictactoe.Board;
import com.baeldung.algorithms.mcts.tictactoe.Position;
import com.baeldung.algorithms.mcts.tree.Tree;
public class MCTSTest {
Tree gameTree;
MonteCarloTreeSearch mcts;
@Before
public void initGameTree() {
gameTree = new Tree();
mcts = new MonteCarloTreeSearch();
}
@Test
public void givenStats_whenGetUCTForNode_thenUCTMatchesWithManualData() {
double uctValue = 15.79;
assertEquals(UCT.uctValue(600, 300, 20), uctValue, 0.01);
}
@Test
public void giveninitBoardState_whenGetAllPossibleStates_thenNonEmptyList() {
State initState = gameTree.getRoot().getState();
List<State> possibleStates = initState.getAllPossibleStates();
assertTrue(possibleStates.size() > 0);
}
@Test
public void givenEmptyBoard_whenPerformMove_thenLessAvailablePossitions() {
Board board = new Board();
int initAvailablePositions = board.getEmptyPositions().size();
board.performMove(Board.P1, new Position(1, 1));
int availablePositions = board.getEmptyPositions().size();
assertTrue(initAvailablePositions > availablePositions);
}
@Test
public void givenEmptyBoard_whenSimulateInterAIPlay_thenGameDraw() {
Board board = new Board();
int player = Board.P1;
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
for (int i = 0; i < totalMoves; i++) {
board = mcts.findNextMove(board, player);
if (board.checkStatus() != -1) {
break;
}
player = 3 - player;
}
int winStatus = board.checkStatus();
assertEquals(winStatus, Board.DRAW);
}
@Test
public void givenEmptyBoard_whenLevel1VsLevel3_thenLevel3WinsOrDraw() {
Board board = new Board();
MonteCarloTreeSearch mcts1 = new MonteCarloTreeSearch();
mcts1.setLevel(1);
MonteCarloTreeSearch mcts3 = new MonteCarloTreeSearch();
mcts3.setLevel(3);
int player = Board.P1;
int totalMoves = Board.DEFAULT_BOARD_SIZE * Board.DEFAULT_BOARD_SIZE;
for (int i = 0; i < totalMoves; i++) {
if (player == Board.P1)
board = mcts3.findNextMove(board, player);
else
board = mcts1.findNextMove(board, player);
if (board.checkStatus() != -1) {
break;
}
player = 3 - player;
}
int winStatus = board.checkStatus();
assertTrue(winStatus == Board.DRAW || winStatus == Board.P1);
}
}

View File

@ -0,0 +1,36 @@
package algorithms.minimax;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import com.baeldung.algorithms.minimax.MiniMax;
import com.baeldung.algorithms.minimax.Tree;
public class MinimaxTest {
private Tree gameTree;
private MiniMax miniMax;
@Before
public void initMiniMaxUtility() {
miniMax = new MiniMax();
}
@Test
public void givenMiniMax_whenConstructTree_thenNotNullTree() {
assertNull(gameTree);
miniMax.constructTree(6);
gameTree = miniMax.getTree();
assertNotNull(gameTree);
}
@Test
public void givenMiniMax_whenCheckWin_thenComputeOptimal() {
miniMax.constructTree(6);
boolean result = miniMax.checkWin();
assertTrue(result);
miniMax.constructTree(8);
result = miniMax.checkWin();
assertFalse(result);
}
}

View File

@ -11,4 +11,4 @@ public class NoClassDefFoundErrorExample {
test = new ClassWithInitErrors();
return test;
}
}
}

View File

@ -8,4 +8,4 @@ public class ClassNotFoundExceptionTest {
public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}
}

View File

@ -9,4 +9,4 @@ public class NoClassDefFoundErrorTest {
NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample();
sample.getClassWithInitErrors();
}
}
}

View File

@ -21,6 +21,8 @@
<java.version>1.8</java.version>
<junit.jupiter.version>5.0.0-M4</junit.jupiter.version>
<junit.platform.version>1.0.0-M4</junit.platform.version>
<junit.vintage.version>4.12.0-M4</junit.vintage.version>
<junit4.version>4.12</junit4.version>
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
@ -51,11 +53,40 @@
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit4.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>${junit.vintage.version}</version>
<scope>test</scope>
</dependency> -->
</dependencies>
</project>

View File

@ -0,0 +1,23 @@
package com.baeldung.migration.junit4;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import com.baeldung.migration.junit4.categories.Annotations;
import com.baeldung.migration.junit4.categories.JUnit4Tests;
@Category(value = { Annotations.class, JUnit4Tests.class })
public class AnnotationTestExampleTest {
@Test(expected = Exception.class)
public void shouldRaiseAnException() throws Exception {
throw new Exception("This is my expected exception");
}
@Test(timeout = 1)
@Ignore
public void shouldFailBecauseTimeout() throws InterruptedException {
Thread.sleep(10);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.migration.junit4;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
public class AssertionsExampleTest {
@Test
@Ignore
public void shouldFailBecauseTheNumbersAreNotEqualld() {
assertEquals("Numbers are not equal!", 2, 3);
}
@Test
public void shouldAssertAllTheGroup() {
List<Integer> list = Arrays.asList(1, 2, 3);
assertEquals("List is not incremental", list.get(0)
.intValue(), 1);
assertEquals("List is not incremental", list.get(1)
.intValue(), 2);
assertEquals("List is not incremental", list.get(2)
.intValue(), 3);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.migration.junit4;
import org.junit.Rule;
import org.junit.Test;
import com.baeldung.migration.junit4.rules.TraceUnitTestRule;
public class RuleExampleTest {
@Rule
public final TraceUnitTestRule traceRuleTests = new TraceUnitTestRule();
@Test
public void whenTracingTests() {
System.out.println("This is my test");
/*...*/
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.migration.junit4.categories;
public interface Annotations {
}

View File

@ -0,0 +1,5 @@
package com.baeldung.migration.junit4.categories;
public interface JUnit4Tests {
}

View File

@ -0,0 +1,35 @@
package com.baeldung.migration.junit4.rules;
import java.util.ArrayList;
import java.util.List;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
public class TraceUnitTestRule implements TestRule {
@Override
public Statement apply(Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
List<Throwable> errors = new ArrayList<Throwable>();
System.out.println("Starting test ... " + description.getMethodName());
try {
base.evaluate();
} catch (Throwable e) {
errors.add(e);
} finally {
System.out.println("... test finished. " + description.getMethodName());
}
MultipleFailureException.assertEmpty(errors);
}
};
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.migration.junit5;
import java.time.Duration;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@Tag("annotations")
@Tag("junit5")
@RunWith(JUnitPlatform.class)
public class AnnotationTestExampleTest {
@Test
public void shouldRaiseAnException() throws Exception {
Assertions.assertThrows(Exception.class, () -> {
throw new Exception("This is my expected exception");
});
}
@Test
@Disabled
public void shouldFailBecauseTimeout() throws InterruptedException {
Assertions.assertTimeout(Duration.ofMillis(1), () -> Thread.sleep(10));
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.migration.junit5;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
public class AssertionsExampleTest {
@Test
@Disabled
public void shouldFailBecauseTheNumbersAreNotEqual() {
Assertions.assertEquals(2, 3, "Numbers are not equal!");
}
@Test
@Disabled
public void shouldFailBecauseItsNotTrue_overloading() {
Assertions.assertTrue(() -> {
return false;
}, () -> "It's not true!");
}
@Test
public void shouldAssertAllTheGroup() {
List<Integer> list = Arrays.asList(1, 2, 3);
Assertions.assertAll("List is not incremental", () -> Assertions.assertEquals(list.get(0)
.intValue(), 1),
() -> Assertions.assertEquals(list.get(1)
.intValue(), 2),
() -> Assertions.assertEquals(list.get(2)
.intValue(), 3));
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.migration.junit5;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import com.baeldung.migration.junit5.extensions.TraceUnitExtension;
@RunWith(JUnitPlatform.class)
@ExtendWith(TraceUnitExtension.class)
public class RuleExampleTest {
@Test
public void whenTracingTests() {
System.out.println("This is my test");
/*...*/
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.migration.junit5.extensions;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.TestExtensionContext;
public class TraceUnitExtension implements AfterEachCallback, BeforeEachCallback {
@Override
public void beforeEach(TestExtensionContext context) throws Exception {
System.out.println("Starting test ... " + context.getDisplayName());
}
@Override
public void afterEach(TestExtensionContext context) throws Exception {
System.out.println("... test finished. " + context.getDisplayName());
}
}

View File

@ -2,9 +2,9 @@ package com.baeldung.commons.collectionutil;
public class Address {
String locality;
String city;
String zip;
private String locality;
private String city;
private String zip;
public String getLocality() {
return locality;

View File

@ -2,12 +2,12 @@ package com.baeldung.commons.collectionutil;
public class Customer implements Comparable<Customer> {
Integer id;
String name;
Long phone;
String locality;
String city;
String zip;
private Integer id;
private String name;
private Long phone;
private String locality;
private String city;
private String zip;
public Integer getId() {
return id;

View File

@ -12,6 +12,7 @@ import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@ -45,6 +46,8 @@ public class CollectionUtilsGuideTest {
@Test
public void givenTwoSortedLists_whenCollated_thenSorted() {
List<Customer> sortedList = CollectionUtils.collate(list1, list2);
assertEquals(6, sortedList.size());
assertTrue(sortedList.get(0).getName().equals("Bob"));
assertTrue(sortedList.get(2).getName().equals("Daniel"));
}
@ -61,7 +64,7 @@ public class CollectionUtilsGuideTest {
}
@Test
public void givenCustomerList_WhenFiltered_thenCorrectSize() {
public void givenCustomerList_whenFiltered_thenCorrectSize() {
boolean isModified = CollectionUtils.filter(linkedList1, customer -> Arrays.asList("Daniel","Kyle").contains(customer.getName()));