Compare commits
103 commits
Author | SHA1 | Date | |
---|---|---|---|
Manuel Thalmann | 39a1585a4b | ||
Manuel Thalmann | c99b0817c0 | ||
Manuel Thalmann | a410e816f4 | ||
Manuel Thalmann | 0ad3397ad0 | ||
Manuel Thalmann | 3390369d0e | ||
Manuel Thalmann | 88ca5cf6a0 | ||
Manuel Thalmann | 27d815812e | ||
Manuel Thalmann | 6759e4e9eb | ||
Manuel Thalmann | 55eedb5599 | ||
Manuel Thalmann | 0b11be8442 | ||
Manuel Thalmann | cae8f549ba | ||
Manuel Thalmann | 98ee51154b | ||
Manuel Thalmann | 3efdc088fc | ||
Manuel Thalmann | e885c492ad | ||
Manuel Thalmann | b5e1e861bc | ||
Manuel Thalmann | bfea9712ec | ||
Manuel Thalmann | 677b73ee6e | ||
Manuel Thalmann | 92e901392b | ||
Manuel Thalmann | c120592296 | ||
Manuel Thalmann | 025bfa7a7f | ||
Manuel Thalmann | 9af35e8cb9 | ||
Manuel Thalmann | e432360dc9 | ||
Manuel Thalmann | f907dc03af | ||
Manuel Thalmann | 1d0e670597 | ||
Manuel Thalmann | 13991b6bd2 | ||
Manuel Thalmann | 11983e0f08 | ||
Manuel Thalmann | aaea1a9d87 | ||
Manuel Thalmann | ce65993bee | ||
Manuel Thalmann | 5e93294c38 | ||
Manuel Thalmann | 25068543ad | ||
Manuel Thalmann | ff0c3f0b98 | ||
Manuel Thalmann | e9d1148cd0 | ||
Manuel Thalmann | 29bd296ceb | ||
Manuel Thalmann | 785b359d37 | ||
Manuel Thalmann | ed5cfd5cb9 | ||
Manuel Thalmann | 69e1646e3f | ||
Manuel Thalmann | 4f3fb4c0d9 | ||
Manuel Thalmann | 466bd318ab | ||
Manuel Thalmann | 235f9857c9 | ||
Manuel Thalmann | 224a67dc9f | ||
Manuel Thalmann | 53756b586c | ||
Manuel Thalmann | 90ad88ee2f | ||
Manuel Thalmann | aad53176f8 | ||
Manuel Thalmann | 0033b66a11 | ||
Manuel Thalmann | 6ec8285d20 | ||
Manuel Thalmann | ebdde65832 | ||
Manuel Thalmann | ac7372738c | ||
Manuel Thalmann | 532788980e | ||
Manuel Thalmann | 7a8e7a973d | ||
Manuel Thalmann | 63da19757e | ||
Manuel Thalmann | 0a4895c538 | ||
Manuel Thalmann | 479cac0393 | ||
Manuel Thalmann | 24225d7595 | ||
Manuel Thalmann | 2d1e65730c | ||
Manuel Thalmann | d04f74f992 | ||
Manuel Thalmann | 1f5b475645 | ||
Manuel Thalmann | e4c4da8fb9 | ||
Manuel Thalmann | 630a5c8acb | ||
Manuel Thalmann | 13b54d1e88 | ||
Manuel Thalmann | e47818c3fa | ||
Manuel Thalmann | e5068eecc8 | ||
Manuel Thalmann | d76b797dce | ||
Manuel Thalmann | 7d56d30e19 | ||
Manuel Thalmann | aecc499585 | ||
Manuel Thalmann | 389d29c66b | ||
Manuel Thalmann | 983ef9cf60 | ||
Manuel Thalmann | 019c56c849 | ||
Manuel Thalmann | 67d698f537 | ||
Manuel Thalmann | 3c1486854b | ||
Manuel Thalmann | 7ffda12287 | ||
Manuel Thalmann | f6fe871d80 | ||
Manuel Thalmann | 3a3ecefed2 | ||
Manuel Thalmann | 6722d8ee02 | ||
Manuel Thalmann | 1a1351c38f | ||
Manuel Thalmann | 73374ed7bb | ||
Manuel Thalmann | 72b926a0a8 | ||
Manuel Thalmann | 1ed56f10da | ||
Manuel Thalmann | bca09ae2d1 | ||
Manuel Thalmann | 7e46399a4a | ||
Manuel Thalmann | 29adffee18 | ||
Manuel Thalmann | 32799964b9 | ||
Manuel Thalmann | bf793a8cea | ||
Manuel Thalmann | 3f6493694c | ||
Manuel Thalmann | cfe533f03b | ||
Manuel Thalmann | 447e63837b | ||
Manuel Thalmann | 882130f703 | ||
Manuel Thalmann | 0aeb39d677 | ||
Manuel Thalmann | 83700823d0 | ||
Manuel Thalmann | aee1199bee | ||
Manuel Thalmann | 8a80db94a9 | ||
Manuel Thalmann | d6ad55619a | ||
Manuel Thalmann | 3078d312a7 | ||
Manuel Thalmann | 2f43b81823 | ||
Manuel Thalmann | 3081d67e0f | ||
Manuel Thalmann | f53e58a3b8 | ||
Manuel Thalmann | cdc7517afa | ||
Manuel Thalmann | 0f808a371b | ||
Manuel Thalmann | 8aa71b1ee5 | ||
Manuel Thalmann | b13632ccc8 | ||
Manuel Thalmann | 9d200788d0 | ||
Manuel Thalmann | d13598d9c0 | ||
Manuel Thalmann | 1cf8747072 | ||
Manuel Thalmann | 2f8d31a75e |
9
.gitattributes
vendored
Normal file
9
.gitattributes
vendored
Normal file
|
@ -0,0 +1,9 @@
|
|||
#
|
||||
# https://help.github.com/articles/dealing-with-line-endings/
|
||||
#
|
||||
# Linux start script should use lf
|
||||
/gradlew text eol=lf
|
||||
|
||||
# These are Windows script files and should use crlf
|
||||
*.bat text eol=crlf
|
||||
|
3
.gitignore
vendored
3
.gitignore
vendored
|
@ -47,3 +47,6 @@ gradle-app.setting
|
|||
hs_err_pid*
|
||||
replay_pid*
|
||||
|
||||
|
||||
# Ignore Gradle build output directory
|
||||
build
|
||||
|
|
4
.vscode/settings.json
vendored
Normal file
4
.vscode/settings.json
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"java.configuration.updateBuildConfiguration": "interactive",
|
||||
"java.compile.nullAnalysis.mode": "automatic"
|
||||
}
|
3166
HashRangZuerich.csv
Normal file
3166
HashRangZuerich.csv
Normal file
File diff suppressed because it is too large
Load diff
16
Labyrinth.txt
Normal file
16
Labyrinth.txt
Normal file
|
@ -0,0 +1,16 @@
|
|||
0-6 4-6
|
||||
4-6 7-6
|
||||
7-6 9-6
|
||||
7-6 7-4
|
||||
7-4 6-4
|
||||
7-4 9-4
|
||||
9-4 9-1
|
||||
7-4 7-1
|
||||
7-1 5-1
|
||||
4-6 4-4
|
||||
4-4 4-3
|
||||
4-4 1-4
|
||||
1-4 1-1
|
||||
1-1 3-1
|
||||
3-1 3-2
|
||||
3-1 3-0
|
3166
RangZuerich.csv
Normal file
3166
RangZuerich.csv
Normal file
File diff suppressed because it is too large
Load diff
10
Rangliste.csv
Normal file
10
Rangliste.csv
Normal file
|
@ -0,0 +1,10 @@
|
|||
Mueller Stefan;02:31:14
|
||||
Marti Adrian;02:30:09
|
||||
Kiptum Daniel;02:11:31
|
||||
Ancay Tarcis;02:20:02
|
||||
Kreibuhl Christian;02:21:47
|
||||
Ott Michael;02:33:48
|
||||
Menzi Christoph;02:27:26
|
||||
Oliver Ruben;02:32:12
|
||||
Elmer Beat;02:33:53
|
||||
Kuehni Martin;02:33:36
|
|
19
Solutions/Exercise 10.md
Normal file
19
Solutions/Exercise 10.md
Normal file
|
@ -0,0 +1,19 @@
|
|||
# Exercise 10
|
||||
## Levenstein-Distanz
|
||||
|
||||
| Input | Reference | Distance |
|
||||
| ----------- | ----------- | :------: |
|
||||
| `AUSTAUSCH` | `AUFBAUSCH` | $2$ |
|
||||
| `BARBAREN` | `BARBARA` | $2$ |
|
||||
| `COCACOLA` | `COCAINA` | $3$ |
|
||||
|
||||
## Reguläre Ausdrücke (Regex)
|
||||
### a)
|
||||
```js
|
||||
/^(((2(5[0-5]|[0-4][0-9]))|((1[0-9]|[1-9])?[0-9]))\.){3}((2(5[0-5]|[0-4][0-9]))|((1[0-9]|[1-9])?[0-9]))$/
|
||||
```
|
||||
|
||||
### b)
|
||||
```js
|
||||
/([^@]+)@([^@]*)/
|
||||
```
|
14
Swiss.txt
Normal file
14
Swiss.txt
Normal file
|
@ -0,0 +1,14 @@
|
|||
Winterthur Zürich 25
|
||||
Zürich Bern 126
|
||||
Zürich Genf 277
|
||||
Zürich Luzern 54
|
||||
Zürich Chur 121
|
||||
Zürich Berikon 16
|
||||
Bern Genf 155
|
||||
Genf Lugano 363
|
||||
Lugano Luzern 206
|
||||
Lugano Chur 152
|
||||
Chur Luzern 146
|
||||
Luzern Bern 97
|
||||
Bern Berikon 102
|
||||
Luzern Berikon 41
|
41
app/build.gradle
Normal file
41
app/build.gradle
Normal file
|
@ -0,0 +1,41 @@
|
|||
/*
|
||||
* This file was generated by the Gradle 'init' task.
|
||||
*
|
||||
* This generated file contains a sample Java application project to get you started.
|
||||
* For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle
|
||||
* User Manual available at https://docs.gradle.org/7.5.1/userguide/building_java_projects.html
|
||||
* This project uses @Incubating APIs which are subject to change.
|
||||
*/
|
||||
|
||||
plugins {
|
||||
// Apply the application plugin to add support for building a CLI application in Java.
|
||||
id 'application'
|
||||
}
|
||||
|
||||
repositories {
|
||||
// Use Maven Central for resolving dependencies.
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// This dependency is used by the application.
|
||||
implementation 'com.google.guava:guava:31.0.1-jre'
|
||||
implementation 'org.junit.jupiter:junit-jupiter:5.9.0'
|
||||
implementation 'org.junit.platform:junit-platform-engine:1.9.0'
|
||||
implementation 'org.junit.platform:junit-platform-launcher:1.9.0'
|
||||
}
|
||||
|
||||
testing {
|
||||
suites {
|
||||
// Configure the built-in test suite
|
||||
test {
|
||||
// Use JUnit Jupiter test framework
|
||||
useJUnitJupiter('5.8.2')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
application {
|
||||
// Define the main class for the application.
|
||||
mainClass = 'ch.nuth.zhaw.exbox.App'
|
||||
}
|
213
app/src/main/java/ch/nuth/zhaw/exbox/AVLSearchTree.java
Normal file
213
app/src/main/java/ch/nuth/zhaw/exbox/AVLSearchTree.java
Normal file
|
@ -0,0 +1,213 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/**
|
||||
* Implements an AVL tree.
|
||||
* Note that all "matching" is based on the compareTo method.
|
||||
*
|
||||
* @author Mark Allen Weiss
|
||||
* Generic K.Rege
|
||||
*/
|
||||
public class AVLSearchTree<T extends Comparable<T>> extends SortedBinaryTree<T> {
|
||||
private boolean balanced(TreeNode<T> node) {
|
||||
if (node == null) {
|
||||
return true;
|
||||
} else if (balanced(node.left) && balanced(node.right)) {
|
||||
return Math.abs(calcHeight(node.left) - calcHeight(node.right)) < 2;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean balanced() {
|
||||
return balanced(root);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected int calcSize(TreeNode<T> p) {
|
||||
if (p == null) {
|
||||
return 0;
|
||||
} else {
|
||||
return super.calcSize(p) + p.values.size() - 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the height of node t, or 0, if null.
|
||||
*/
|
||||
private static <T extends Comparable<T>> int height(TreeNode<T> t) {
|
||||
return t == null ? 0 : t.height;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert into the tree; duplicates are ignored.
|
||||
*
|
||||
* @param element the item to insert.
|
||||
*/
|
||||
public void add(T element) {
|
||||
root = insertAt(root, element);
|
||||
}
|
||||
|
||||
private TreeNode<T> balance(TreeNode<T> p) {
|
||||
if (p == null) {
|
||||
return null;
|
||||
} else if (height(p.left) - height(p.right) == 2) {
|
||||
if (height(p.left.left) >= height(p.left.right)) {
|
||||
p = rotateR(p);
|
||||
} else {
|
||||
p = rotateLR(p);
|
||||
}
|
||||
} else if (height(p.right) - height(p.left) == 2) {
|
||||
if (height(p.right.right) >= height(p.right.left)) {
|
||||
p = rotateL(p);
|
||||
} else {
|
||||
p = rotateRL(p);
|
||||
}
|
||||
}
|
||||
p.height = Math.max(height(p.left), height(p.right)) + 1;
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal method to insert into a subtree.
|
||||
*
|
||||
* @param element the item to insert.
|
||||
* @param p the node that roots the tree.
|
||||
* @return the new root.
|
||||
*/
|
||||
private TreeNode<T> insertAt(TreeNode<T> p, T element) {
|
||||
if (p == null) {
|
||||
p = new TreeNode<>(element);
|
||||
p.height = 1;
|
||||
return p;
|
||||
} else {
|
||||
int c = element.compareTo(p.getValue());
|
||||
if (c == 0) {
|
||||
p.values.add(element);
|
||||
} else if (c < 0) {
|
||||
p.left = insertAt(p.left, element);
|
||||
} else {
|
||||
p.right = insertAt(p.right, element);
|
||||
}
|
||||
}
|
||||
p = balance(p);
|
||||
return p;
|
||||
}
|
||||
|
||||
// find node to replace
|
||||
private TreeNode<T> rep;
|
||||
|
||||
private TreeNode<T> findRepAt(TreeNode<T> node) {
|
||||
if (node.right != null) {
|
||||
node.right = findRepAt(node.right);
|
||||
node = balance(node);
|
||||
} else {
|
||||
rep = node;
|
||||
node = node.left;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
private T removed;
|
||||
|
||||
// remove node
|
||||
private TreeNode<T> removeAt(TreeNode<T> node, T x) {
|
||||
if (node == null) {
|
||||
return null;
|
||||
} else {
|
||||
if (x.compareTo(node.getValue()) == 0) {
|
||||
// found
|
||||
removed = node.getValue();
|
||||
if (node.values.size() > 1) {
|
||||
node.values.remove(0);
|
||||
return node;
|
||||
} else if (node.left == null) {
|
||||
node = node.right;
|
||||
} else if (node.right == null) {
|
||||
node = node.left;
|
||||
} else {
|
||||
node.left = findRepAt(node.left);
|
||||
rep.left = node.left;
|
||||
rep.right = node.right;
|
||||
node = rep;
|
||||
}
|
||||
} else if (x.compareTo(node.getValue()) <= 0) {
|
||||
// search left
|
||||
node.left = removeAt(node.left, x);
|
||||
} else {
|
||||
// search right
|
||||
node.right = removeAt(node.right, x);
|
||||
}
|
||||
|
||||
return balance(node);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove from the tree. Nothing is done if x is not found.
|
||||
*
|
||||
* @param x the item to remove.
|
||||
*/
|
||||
public T remove(T x) {
|
||||
removed = null;
|
||||
root = removeAt(root, x);
|
||||
return removed;
|
||||
}
|
||||
|
||||
public Traversal<T> traversal() {
|
||||
return new AVLTreeTraversal<>(root);
|
||||
}
|
||||
|
||||
public T removeLast() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotate binary tree node with left child.
|
||||
* For AVL trees, this is a single rotation for case 1.
|
||||
* Update heights, then return new root.
|
||||
*/
|
||||
private static <T extends Comparable<T>> TreeNode<T> rotateR(TreeNode<T> k2) {
|
||||
TreeNode<T> k1 = k2.left;
|
||||
k2.left = k1.right;
|
||||
k1.right = k2;
|
||||
k2.height = Math.max(height(k2.left), height(k2.right)) + 1;
|
||||
k1.height = Math.max(height(k1.left), k2.height) + 1;
|
||||
return k1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotate binary tree node with right child.
|
||||
* For AVL trees, this is a single rotation for case 4.
|
||||
* Update heights, then return new root.
|
||||
*/
|
||||
private static <T extends Comparable<T>> TreeNode<T> rotateL(TreeNode<T> k1) {
|
||||
TreeNode<T> k2 = k1.right;
|
||||
k1.right = k2.left;
|
||||
k2.left = k1;
|
||||
k1.height = Math.max(height(k1.left), height(k1.right)) + 1;
|
||||
k2.height = Math.max(height(k2.right), k1.height) + 1;
|
||||
return k2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Double rotate binary tree node: first left child
|
||||
* with its right child; then node k3 with new left child.
|
||||
* For AVL trees, this is a double rotation for case 2.
|
||||
* Update heights, then return new root.
|
||||
*/
|
||||
private static <T extends Comparable<T>> TreeNode<T> rotateLR(TreeNode<T> k3) {
|
||||
k3.left = rotateL(k3.left);
|
||||
return rotateR(k3);
|
||||
}
|
||||
|
||||
/**
|
||||
* Double rotate binary tree node: first right child
|
||||
* with its left child; then node k1 with new right child.
|
||||
* For AVL trees, this is a double rotation for case 3.
|
||||
* Update heights, then return new root.
|
||||
*/
|
||||
private static <T extends Comparable<T>> TreeNode<T> rotateRL(TreeNode<T> k1) {
|
||||
k1.right = rotateR(k1.right);
|
||||
return rotateL(k1);
|
||||
}
|
||||
}
|
88
app/src/main/java/ch/nuth/zhaw/exbox/AVLTreeTraversal.java
Normal file
88
app/src/main/java/ch/nuth/zhaw/exbox/AVLTreeTraversal.java
Normal file
|
@ -0,0 +1,88 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.Queue;
|
||||
|
||||
public class AVLTreeTraversal<T extends Comparable<T>> implements Traversal<T> {
|
||||
private final TreeNode<T> root;
|
||||
|
||||
public AVLTreeTraversal(TreeNode<T> root) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
private void inorder(TreeNode<T> node, Visitor<T> vis) {
|
||||
if (node != null) {
|
||||
inorder(node.left, vis);
|
||||
for (T v : node.values) vis.visit(v);
|
||||
inorder(node.right, vis);
|
||||
}
|
||||
}
|
||||
|
||||
public void inorder(Visitor<T> vis) {
|
||||
inorder(root, vis);
|
||||
}
|
||||
|
||||
private void preorder(TreeNode<T> node, Visitor<T> vis) {
|
||||
if (node != null) {
|
||||
for (T v : node.values) vis.visit(v);
|
||||
preorder(node.left, vis);
|
||||
preorder(node.right, vis);
|
||||
}
|
||||
}
|
||||
|
||||
public void preorder(Visitor<T> vis) {
|
||||
preorder(root, vis);
|
||||
}
|
||||
|
||||
private void postorder(TreeNode<T> node, Visitor<T> vis) {
|
||||
if (node != null) {
|
||||
postorder(node.left, vis);
|
||||
postorder(node.right, vis);
|
||||
for (T v : node.values) vis.visit(v);
|
||||
}
|
||||
}
|
||||
|
||||
public void postorder(Visitor<T> vis) {
|
||||
postorder(root, vis);
|
||||
}
|
||||
|
||||
void levelorder(TreeNode<T> node, Visitor<T> visitor) {
|
||||
Queue<TreeNode<T>> q = new LinkedList<>();
|
||||
if (node != null) {
|
||||
q.offer(node);
|
||||
}
|
||||
while (!q.isEmpty()) {
|
||||
node = q.poll();
|
||||
for (T v : node.values) visitor.visit(v);
|
||||
if (node.left != null) {
|
||||
q.offer(node.left);
|
||||
}
|
||||
if (node.right != null) {
|
||||
q.offer(node.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void levelorder(Visitor<T> vis) {
|
||||
levelorder(root, vis);
|
||||
}
|
||||
|
||||
private void interval(T min, T max, Visitor<T> visitor, TreeNode<T> node) {
|
||||
if (node != null) {
|
||||
if (0 > node.getValue().compareTo(min)) {
|
||||
interval(min, max, visitor, node.right);
|
||||
} else if (0 < node.getValue().compareTo(max)) {
|
||||
interval(min, max, visitor, node.left);
|
||||
} else {
|
||||
for (T v : node.values) visitor.visit(v);
|
||||
interval(min, max, visitor, node.left);
|
||||
interval(min, max, visitor, node.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void interval(T min, T max, Visitor<T> v) {
|
||||
interval(min, max, v, this.root);
|
||||
}
|
||||
}
|
53
app/src/main/java/ch/nuth/zhaw/exbox/AdjListGraph.java
Normal file
53
app/src/main/java/ch/nuth/zhaw/exbox/AdjListGraph.java
Normal file
|
@ -0,0 +1,53 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class AdjListGraph<N extends Node, E extends Edge>
|
||||
implements Graph<N, E> {
|
||||
private final List<N> nodes = new LinkedList<>();
|
||||
private final Class<N> nodeClazz;
|
||||
private final Class<E> edgeClazz;
|
||||
|
||||
public AdjListGraph(Class<N> nodeClazz, Class<E> edgeClazz) {
|
||||
this.nodeClazz = nodeClazz;
|
||||
this.edgeClazz = edgeClazz;
|
||||
}
|
||||
|
||||
/** füge Knoten hinzu, gebe alten zurück falls Knoten schon existiert */
|
||||
public N addNode(String name) throws Throwable {
|
||||
N node = findNode(name);
|
||||
if (node == null) {
|
||||
node = nodeClazz.getConstructor().newInstance();
|
||||
node.setName(name);
|
||||
nodes.add(node);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/** füge gerichtete Kante hinzu */
|
||||
public void addEdge(String source, String dest, double weight) throws Throwable {
|
||||
N src = addNode(source);
|
||||
N dst = addNode(dest);
|
||||
|
||||
E edge = edgeClazz.getConstructor().newInstance();
|
||||
edge.setDest(dst);
|
||||
edge.setWeight(weight);
|
||||
src.addEdge(edge);
|
||||
}
|
||||
|
||||
/** finde den Knoten anhand seines Namens */
|
||||
public N findNode(String name) {
|
||||
for (N node : nodes) {
|
||||
if (node.getName().equals(name)) {
|
||||
return node;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Iterator über alle Knoten */
|
||||
public Iterable<N> getNodes() {
|
||||
return nodes;
|
||||
}
|
||||
}
|
13
app/src/main/java/ch/nuth/zhaw/exbox/AnyServer.java
Normal file
13
app/src/main/java/ch/nuth/zhaw/exbox/AnyServer.java
Normal file
|
@ -0,0 +1,13 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/**
|
||||
* AnyServer -- Praktikum Experimentierkasten -- ADS
|
||||
*
|
||||
*/
|
||||
public class AnyServer implements CommandExecutor {
|
||||
// ----- Dies implementiert das CommandExecutor Interface.
|
||||
@Override
|
||||
public String execute(String command) {
|
||||
return "Die Eingabe ist \"" + command + "\"\n";
|
||||
}
|
||||
}
|
13
app/src/main/java/ch/nuth/zhaw/exbox/App.java
Normal file
13
app/src/main/java/ch/nuth/zhaw/exbox/App.java
Normal file
|
@ -0,0 +1,13 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/**
|
||||
* @author K. Rege
|
||||
* @version 1.0 -- Experimentierkasten
|
||||
*/
|
||||
public class App {
|
||||
public static void main(String[] args) {
|
||||
ExBoxFrame f = new ExBoxFrame();
|
||||
f.setLocationRelativeTo(null);
|
||||
f.setVisible(true);
|
||||
}
|
||||
}
|
162
app/src/main/java/ch/nuth/zhaw/exbox/BakeryCookieServer.java
Normal file
162
app/src/main/java/ch/nuth/zhaw/exbox/BakeryCookieServer.java
Normal file
|
@ -0,0 +1,162 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class BakeryCookieServer implements CommandExecutor {
|
||||
private Ingredient mehl, zucker, salz, eier, butter, milch, zitrone, konfituere, schokolade;
|
||||
private Ingredient[] stockOfIngredients;
|
||||
|
||||
private Cookie mailaenderli, spitzbuben, brownies;
|
||||
private Cookie[] cookiesOfBakery;
|
||||
|
||||
private float temperature;
|
||||
private Random heatGenerator = new Random();
|
||||
|
||||
public String execute (String input) {
|
||||
initialiseIngredients();
|
||||
initialiseCookies();
|
||||
return simulatedAnnealing();
|
||||
}
|
||||
|
||||
/**
|
||||
* initializes the ingredients and their quantity in stock
|
||||
*/
|
||||
private void initialiseIngredients() {
|
||||
mehl = new Ingredient("Mehl", 20000);
|
||||
zucker = new Ingredient("Zucker", 25000);
|
||||
salz = new Ingredient("Salz", 5000);
|
||||
eier = new Ingredient("Eier", 2000);
|
||||
butter = new Ingredient("Butter", 10000);
|
||||
milch = new Ingredient("Milch", 5000);
|
||||
zitrone = new Ingredient("Zitrone", 10000);
|
||||
konfituere = new Ingredient("Konfitüre", 2000);
|
||||
schokolade = new Ingredient("Schokolade", 1000);
|
||||
stockOfIngredients = new Ingredient[] { mehl, zucker, salz, eier, butter, milch, zitrone, konfituere, schokolade };
|
||||
}
|
||||
|
||||
/**
|
||||
* initialises the cookies and the ingredients used for one cookie
|
||||
*/
|
||||
private void initialiseCookies() {
|
||||
mailaenderli = new Cookie("Mailänderli", 7);
|
||||
mailaenderli.addIngredient(mehl, 15);
|
||||
mailaenderli.addIngredient(zucker, 11.25f);
|
||||
mailaenderli.addIngredient(salz, 0.2f);
|
||||
mailaenderli.addIngredient(eier, 5);
|
||||
mailaenderli.addIngredient(butter, 12.5f);
|
||||
mailaenderli.addIngredient(milch, 1);
|
||||
mailaenderli.addIngredient(zitrone, 7.5f);
|
||||
|
||||
spitzbuben = new Cookie("Spitzbuben", 6);
|
||||
spitzbuben.addIngredient(mehl, 25.5f);
|
||||
spitzbuben.addIngredient(zucker, 6.25f);
|
||||
spitzbuben.addIngredient(salz, 0.15f);
|
||||
spitzbuben.addIngredient(eier, 4);
|
||||
spitzbuben.addIngredient(butter, 12.5f);
|
||||
spitzbuben.addIngredient(konfituere, 10.5f);
|
||||
|
||||
brownies = new Cookie("Schoggibuben", 6);
|
||||
brownies.addIngredient(mehl, 15.5f);
|
||||
brownies.addIngredient(zucker, 10);
|
||||
brownies.addIngredient(salz, 0.10f);
|
||||
brownies.addIngredient(eier, 3);
|
||||
brownies.addIngredient(butter, 10.5f);
|
||||
brownies.addIngredient(schokolade, 20.5f);
|
||||
|
||||
cookiesOfBakery = new Cookie[] {mailaenderli, spitzbuben, brownies};
|
||||
}
|
||||
|
||||
/**
|
||||
* uses simulated annealing to generate new possible solutions
|
||||
* @return string contains the best found solution for all cookies
|
||||
*/
|
||||
private String simulatedAnnealing() {
|
||||
String result = "";
|
||||
|
||||
// TODO
|
||||
float startTemperature = temperature;
|
||||
creationOfInitialConfiguration();
|
||||
|
||||
while (temperature >= 0) {
|
||||
generateNextTestConfiguration();
|
||||
|
||||
if (checkIfValidSolution())
|
||||
{
|
||||
if (checkIfMoreCookiesAndBetterSolution() || (Math.random() * startTemperature) > temperature)
|
||||
{
|
||||
for (Cookie cookie : cookiesOfBakery) {
|
||||
cookie.setBestNrOfCookies(cookie.getTestedNrOfCookies());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
temperature -= heatGenerator.nextFloat();
|
||||
}
|
||||
|
||||
for (Cookie cookie : cookiesOfBakery) {
|
||||
result += cookie.getNameOfCookie() + ": " + cookie.getBestNrOfCookies() + ", ";
|
||||
}
|
||||
return result + "\n";
|
||||
}
|
||||
|
||||
/**
|
||||
* initialize very first run (temperature)
|
||||
*/
|
||||
private void creationOfInitialConfiguration() {
|
||||
// TODO
|
||||
temperature = 10_000_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a randomized new test set of cookies
|
||||
*/
|
||||
private void generateNextTestConfiguration() {
|
||||
// TODO
|
||||
|
||||
for (Cookie cookie : cookiesOfBakery)
|
||||
{
|
||||
if (heatGenerator.nextBoolean())
|
||||
{
|
||||
int incremental = cookie.getBestNrOfCookies() > 0 ? (heatGenerator.nextBoolean() ? 1 : -1) : 1;
|
||||
cookie.setTestedNrOfCookies(cookie.getBestNrOfCookies() + incremental);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if this is a better solution (more cookies) then the solution already found
|
||||
* @return true if the newly tested solution is better
|
||||
*/
|
||||
private boolean checkIfMoreCookiesAndBetterSolution() {
|
||||
// TODO
|
||||
return Stream.of(cookiesOfBakery).mapToInt((cookie) -> cookie.getTestedNrOfCookies()).sum()
|
||||
>= Stream.of(cookiesOfBakery).mapToInt((cookie) -> cookie.getBestNrOfCookies()).sum();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there are enough ingredients to bake this new solution
|
||||
* @return true if enough ingredients
|
||||
*/
|
||||
private boolean checkIfValidSolution() {
|
||||
// TODO
|
||||
for (Ingredient ingredient : stockOfIngredients)
|
||||
{
|
||||
ingredient.initialiseStockBeforeCooking();
|
||||
}
|
||||
|
||||
for (Cookie cookie : cookiesOfBakery)
|
||||
{
|
||||
for (int i = 0; i < cookie.getNrOfIngredients(); i++)
|
||||
{
|
||||
if (!cookie.getIngredientOfCookie(i).removeFromStock(cookie.getGramsPerIngredient(i) * cookie.getTestedNrOfCookies()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
51
app/src/main/java/ch/nuth/zhaw/exbox/BracketServer.java
Normal file
51
app/src/main/java/ch/nuth/zhaw/exbox/BracketServer.java
Normal file
|
@ -0,0 +1,51 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.regex.MatchResult;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class BracketServer implements CommandExecutor {
|
||||
private static Pattern bracketPattern = Pattern.compile("(/\\*|\\*/|[(){}\\[\\]<>])");
|
||||
|
||||
private static Map<String, String> bracketPairs;
|
||||
|
||||
public BracketServer() {
|
||||
super();
|
||||
|
||||
bracketPairs = new HashMap<>() {
|
||||
{
|
||||
put("(", ")");
|
||||
put("[", "]");
|
||||
put("{", "}");
|
||||
put("<", ">");
|
||||
put("/*", "*/");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public String execute(String command) throws Exception {
|
||||
return Boolean.toString(checkBrackets(command)) + "\n";
|
||||
}
|
||||
|
||||
public boolean checkBrackets(String expression) {
|
||||
ListStack openBrackets = new ListStack();
|
||||
Matcher matcher = bracketPattern.matcher(expression);
|
||||
Iterable<MatchResult> results = () -> matcher.results().iterator();
|
||||
|
||||
for (MatchResult result : results) {
|
||||
if (bracketPairs.keySet().contains(result.group())) {
|
||||
openBrackets.push(result.group());
|
||||
} else if (!openBrackets.isEmpty() &&
|
||||
result.group().equals(bracketPairs.get(openBrackets.peek()))) {
|
||||
openBrackets.pop();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return openBrackets.isEmpty();
|
||||
}
|
||||
}
|
29
app/src/main/java/ch/nuth/zhaw/exbox/CObject.java
Normal file
29
app/src/main/java/ch/nuth/zhaw/exbox/CObject.java
Normal file
|
@ -0,0 +1,29 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/** base class of collectable objects */
|
||||
public class CObject implements Collectable {
|
||||
private boolean mark; // to mark object
|
||||
public CObject next, down;
|
||||
public String value;
|
||||
|
||||
public CObject (String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public void setMark(boolean mark) {
|
||||
this.mark = mark;
|
||||
}
|
||||
|
||||
public boolean isMarked() {
|
||||
return mark;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
return this.getClass() == o.getClass() && this.value.equals(((CObject)o).value);
|
||||
}
|
||||
}
|
6
app/src/main/java/ch/nuth/zhaw/exbox/Collectable.java
Normal file
6
app/src/main/java/ch/nuth/zhaw/exbox/Collectable.java
Normal file
|
@ -0,0 +1,6 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
public interface Collectable {
|
||||
void setMark(boolean b);
|
||||
boolean isMarked();
|
||||
}
|
20
app/src/main/java/ch/nuth/zhaw/exbox/CommandExecutor.java
Normal file
20
app/src/main/java/ch/nuth/zhaw/exbox/CommandExecutor.java
Normal file
|
@ -0,0 +1,20 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/**
|
||||
* CommandExecutor -- Praktikum Experimentierkasten -- SW3 Dieses Interface muss
|
||||
* von jedem Server implementiert werden.
|
||||
*
|
||||
* @author E. Mumprecht
|
||||
* @version 1.0 -- Geruest fuer irgendeinen Server
|
||||
* @version 1.1 -- K. Rege Fehlerueckgabe hinzugefuegt
|
||||
*/
|
||||
public interface CommandExecutor {
|
||||
/**
|
||||
* execute -- nimmt eine Kommandozeile, tut irgendetwas gescheites, und
|
||||
* berichtet das Resultat.
|
||||
*
|
||||
* @param command Kommandozeile
|
||||
* @return Resultat, ueblicherweise eine oder mehrere Zeilen.
|
||||
*/
|
||||
String execute(String command) throws Exception;
|
||||
}
|
95
app/src/main/java/ch/nuth/zhaw/exbox/Competitor.java
Normal file
95
app/src/main/java/ch/nuth/zhaw/exbox/Competitor.java
Normal file
|
@ -0,0 +1,95 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
|
||||
public class Competitor implements Comparable<Competitor> {
|
||||
private final String name;
|
||||
private final String time;
|
||||
private int rank;
|
||||
|
||||
public Competitor(int rank, String name, String time) {
|
||||
this.rank = rank;
|
||||
this.name = name;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public void setRank(int rank) {
|
||||
this.rank = rank;
|
||||
}
|
||||
|
||||
public String getTime() {
|
||||
return time;
|
||||
}
|
||||
|
||||
public Long getTimeValue() {
|
||||
return parseTime(getTime());
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
private static long parseTime(String s) {
|
||||
try {
|
||||
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
|
||||
Date date = sdf.parse(s);
|
||||
return date.getTime();
|
||||
} catch (Exception e) {
|
||||
System.err.println(e);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "" + rank + " " + name + " " + time;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(Competitor o) {
|
||||
int result = rank - o.rank;
|
||||
|
||||
if (result == 0) {
|
||||
result = Long.compare(parseTime(getTime()), parseTime(o.getTime()));
|
||||
|
||||
if (result == 0) {
|
||||
result = getName().compareTo(o.getName());
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o instanceof Competitor) {
|
||||
Competitor c = (Competitor) o;
|
||||
return compareTo(c) == 0;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return (getTime().hashCode() + getName().hashCode()) * rank;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class AlphaComparatorCompetitor implements Comparator<Competitor> {
|
||||
|
||||
@Override
|
||||
public int compare(Competitor o1, Competitor o2) {
|
||||
int result = o1.getName().compareTo(o2.getName());
|
||||
|
||||
if (result == 0) {
|
||||
return Long.compare(o1.getTimeValue(), o2.getTimeValue());
|
||||
} else {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
56
app/src/main/java/ch/nuth/zhaw/exbox/Cookie.java
Normal file
56
app/src/main/java/ch/nuth/zhaw/exbox/Cookie.java
Normal file
|
@ -0,0 +1,56 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
public class Cookie {
|
||||
private final String nameOfCookie;
|
||||
private int bestNrOfCookies = 0;
|
||||
private int testedNrOfCookies;
|
||||
private final Ingredient[] ingredientsOfCookie;
|
||||
private final float[] gramsPerIngredient;
|
||||
private int nrOfIngredient = 0;
|
||||
|
||||
Cookie(String nameOfCookie, int nrOfIngridients) {
|
||||
this.nameOfCookie = nameOfCookie;
|
||||
ingredientsOfCookie = new Ingredient[nrOfIngridients];
|
||||
gramsPerIngredient = new float[nrOfIngridients];
|
||||
}
|
||||
|
||||
public String getNameOfCookie() {
|
||||
return nameOfCookie;
|
||||
}
|
||||
|
||||
public int getBestNrOfCookies() {
|
||||
return bestNrOfCookies;
|
||||
}
|
||||
|
||||
public void setBestNrOfCookies(int bestNrOfCookies) {
|
||||
this.bestNrOfCookies = bestNrOfCookies;
|
||||
}
|
||||
|
||||
public int getTestedNrOfCookies() {
|
||||
return testedNrOfCookies;
|
||||
}
|
||||
|
||||
public void setTestedNrOfCookies(int testedNrOfCookies) {
|
||||
this.testedNrOfCookies = testedNrOfCookies;
|
||||
}
|
||||
|
||||
void addIngredient(Ingredient ingredient, float gramsPerCookie) {
|
||||
ingredientsOfCookie[nrOfIngredient] = ingredient;
|
||||
this.gramsPerIngredient[nrOfIngredient] = gramsPerCookie;
|
||||
nrOfIngredient++;
|
||||
}
|
||||
|
||||
Ingredient getIngredientOfCookie(int nrOfIngredient)
|
||||
{
|
||||
return ingredientsOfCookie[nrOfIngredient];
|
||||
}
|
||||
|
||||
float getGramsPerIngredient(int nrOfIngredient)
|
||||
{
|
||||
return gramsPerIngredient[nrOfIngredient];
|
||||
}
|
||||
|
||||
int getNrOfIngredients() {
|
||||
return nrOfIngredient;
|
||||
}
|
||||
}
|
41
app/src/main/java/ch/nuth/zhaw/exbox/DijkstraNode.java
Normal file
41
app/src/main/java/ch/nuth/zhaw/exbox/DijkstraNode.java
Normal file
|
@ -0,0 +1,41 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
class DijkstraNode extends Node implements Comparable<DijkstraNode> {
|
||||
boolean mark;
|
||||
DijkstraNode prev;
|
||||
double dist;
|
||||
|
||||
public DijkstraNode() { }
|
||||
|
||||
public double getDist (){
|
||||
return dist;
|
||||
}
|
||||
|
||||
public void setDist(double dist) {
|
||||
this.dist = dist;
|
||||
}
|
||||
|
||||
public void setMark(boolean m) {
|
||||
mark = m;
|
||||
}
|
||||
|
||||
public boolean getMark() {
|
||||
return mark;
|
||||
}
|
||||
|
||||
public void setPrev(DijkstraNode p) {
|
||||
prev = p;
|
||||
}
|
||||
|
||||
public DijkstraNode getPrev() {
|
||||
return prev;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return getName() + " "+getDist();
|
||||
}
|
||||
|
||||
public int compareTo(DijkstraNode n) {
|
||||
return (int)(dist - n.dist);
|
||||
}
|
||||
}
|
19
app/src/main/java/ch/nuth/zhaw/exbox/Edge.java
Normal file
19
app/src/main/java/ch/nuth/zhaw/exbox/Edge.java
Normal file
|
@ -0,0 +1,19 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
public class Edge {
|
||||
protected Node dest; // Zielknoten der Kante
|
||||
protected double weight; // Kantengewicht
|
||||
|
||||
public Edge() {}
|
||||
|
||||
public Edge(Node dest, double weight) {
|
||||
this.dest = dest;
|
||||
this.weight = weight;
|
||||
}
|
||||
|
||||
public void setDest(Node node) { this.dest = node; }
|
||||
public Node getDest() { return dest; }
|
||||
|
||||
public void setWeight(double w) { this.weight = w; }
|
||||
double getWeight() { return weight; }
|
||||
}
|
325
app/src/main/java/ch/nuth/zhaw/exbox/ExBoxFrame.java
Normal file
325
app/src/main/java/ch/nuth/zhaw/exbox/ExBoxFrame.java
Normal file
|
@ -0,0 +1,325 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
import java.awt.event.ActionEvent;
|
||||
import java.awt.event.ActionListener;
|
||||
import java.awt.event.ItemEvent;
|
||||
import java.awt.event.ItemListener;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* @(#)ExBoxFrame.java
|
||||
*
|
||||
* JFC ExBox application
|
||||
*
|
||||
* @author K.Rege
|
||||
* @version 1.00 2014/2/3
|
||||
* @version 1.01 2016/8/2
|
||||
* @version 2.00 2017/8/30 Test
|
||||
* @version 2.01 2018/2/5 AutoscaleFaktor
|
||||
* @version 2.02 2018/3/12 Reconnect (inspired by S. Kunz)
|
||||
* @version 2.03 2021/7/24 Test (repeat)
|
||||
* @version 2.04 2021/9/11 Test as plugin
|
||||
*/
|
||||
public class ExBoxFrame extends JFrame implements ActionListener, ItemListener {
|
||||
private final Dimension UHDTHRESHOLD = new Dimension(2000, 1500);
|
||||
private final String STANDARDENCODING = "UTF-8";
|
||||
|
||||
private JMenuItem connect, reset, exit, open, test, retest, textView, graphicView, clear;
|
||||
private JMenu menuServer;
|
||||
private JButton enter;
|
||||
private JTextField arguments;
|
||||
private JComboBox<String> history;
|
||||
private JTextArea output;
|
||||
private JScrollPane scrollPane;
|
||||
private CommandExecutor command;
|
||||
private CommandExecutor unitTest;
|
||||
private boolean graphicOn;
|
||||
private GraphicPanel graphic;
|
||||
private String lastServer;
|
||||
private String lastTestFile;
|
||||
|
||||
public void setFontSize(int size) {
|
||||
Set<Object> keySet = UIManager.getLookAndFeelDefaults().keySet();
|
||||
|
||||
for (Object key : keySet) {
|
||||
if (key != null && key.toString().toLowerCase().contains("font")) {
|
||||
Font font = UIManager.getDefaults().getFont(key);
|
||||
|
||||
if (font != null) {
|
||||
font = font.deriveFont((float) size);
|
||||
UIManager.put(key, font);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void initMenu() {
|
||||
JMenuBar menuBar = new JMenuBar();
|
||||
setJMenuBar(menuBar);
|
||||
|
||||
JMenu menuFile = new JMenu("File");
|
||||
menuBar.add(menuFile);
|
||||
open = new JMenuItem("Open...");
|
||||
open.addActionListener(this);
|
||||
menuFile.add(open);
|
||||
exit = new JMenuItem();
|
||||
exit.setText("Exit");
|
||||
exit.addActionListener(this);
|
||||
menuFile.add(exit);
|
||||
|
||||
menuServer = new JMenu("Server");
|
||||
menuBar.add(menuServer);
|
||||
connect = new JMenuItem("Connect ...");
|
||||
connect.addActionListener(this);
|
||||
menuServer.add(connect);
|
||||
reset = new JMenuItem("Reset Server...");
|
||||
reset.addActionListener(this);
|
||||
menuServer.add(reset);
|
||||
|
||||
JMenu menuView = new JMenu("View");
|
||||
menuBar.add(menuView);
|
||||
clear = new JMenuItem("Clear");
|
||||
clear.addActionListener(this);
|
||||
menuView.add(clear);
|
||||
textView = new JMenuItem("Text");
|
||||
textView.addActionListener(this);
|
||||
menuView.add(textView);
|
||||
graphicView = new JMenuItem("Graphic");
|
||||
graphicView.addActionListener(this);
|
||||
menuView.add(graphicView);
|
||||
}
|
||||
|
||||
private void initJUnit() {
|
||||
try {
|
||||
unitTest = ServerFactory.createServer(getPathCompiled().resolve("ExBoxJUnit.class").toString());
|
||||
test = new JMenuItem("Test ...");
|
||||
test.addActionListener(this);
|
||||
menuServer.add(test);
|
||||
retest = new JMenuItem("Test");
|
||||
retest.addActionListener(this);
|
||||
menuServer.add(retest);
|
||||
} catch (Exception e) {
|
||||
warning("Test Plugin not found\n");
|
||||
}
|
||||
}
|
||||
|
||||
private void initComponents() {
|
||||
setLayout(new BorderLayout());
|
||||
output = new JTextArea();
|
||||
scrollPane = new JScrollPane(output);
|
||||
add(BorderLayout.CENTER, scrollPane);
|
||||
|
||||
JPanel panel = new JPanel(new BorderLayout());
|
||||
panel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
|
||||
arguments = new JTextField();
|
||||
arguments.addActionListener(this);
|
||||
panel.add(BorderLayout.CENTER, arguments);
|
||||
enter = new JButton("enter");
|
||||
enter.addActionListener(this);
|
||||
panel.add(BorderLayout.EAST, enter);
|
||||
history = new JComboBox<>();
|
||||
history.addItemListener(this);
|
||||
panel.add(BorderLayout.SOUTH, history);
|
||||
add(BorderLayout.SOUTH, panel);
|
||||
}
|
||||
|
||||
/**
|
||||
* get default path for file open dialog
|
||||
*/
|
||||
private Path getPathCompiled() {
|
||||
try {
|
||||
Path path = Paths.get(getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
|
||||
|
||||
for (String part : getClass().getPackage().getName().split("\\.")) {
|
||||
path = path.resolve(part);
|
||||
}
|
||||
|
||||
return path;
|
||||
} catch (URISyntaxException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The constructor
|
||||
*/
|
||||
public ExBoxFrame() {
|
||||
try {
|
||||
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
|
||||
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
|
||||
|
||||
double scale = (
|
||||
screenSize.getWidth() > UHDTHRESHOLD.getWidth() &&
|
||||
screenSize.getHeight() > UHDTHRESHOLD.getHeight()) ? 2 : 1;
|
||||
|
||||
scale = Math.max(scale, Toolkit.getDefaultToolkit().getScreenResolution() / 96.0);
|
||||
setFontSize((int) (11 * scale));
|
||||
|
||||
setSize(
|
||||
new Dimension((int)(400 * scale), (int)(400 * scale)));
|
||||
|
||||
setTitle("ExBox");
|
||||
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
|
||||
initComponents();
|
||||
initMenu();
|
||||
initJUnit();
|
||||
}
|
||||
|
||||
private void warning(String s) {
|
||||
System.err.println("\nWARNING: " + s + "\n");
|
||||
}
|
||||
|
||||
private void error(String s) {
|
||||
output.append("\nERROR: " + s + "\n");
|
||||
}
|
||||
|
||||
private void execute(String args) throws Exception {
|
||||
if (!arguments.getText().equals(history.getItemAt(0))
|
||||
&& !arguments.getText().equals(history.getSelectedItem())) {
|
||||
history.insertItemAt(arguments.getText(), 0);
|
||||
}
|
||||
|
||||
if (command == null) {
|
||||
error("no Server connected");
|
||||
} else {
|
||||
String res = command.execute(args);
|
||||
|
||||
if (graphicOn) {
|
||||
graphic.setFigure(res);
|
||||
} else {
|
||||
output.append(res);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void setGraphicView() {
|
||||
if (!graphicOn) {
|
||||
remove(scrollPane);
|
||||
graphic = new GraphicPanel();
|
||||
output.removeNotify();
|
||||
add(BorderLayout.CENTER, graphic);
|
||||
graphicOn = true;
|
||||
validate();
|
||||
repaint();
|
||||
}
|
||||
}
|
||||
|
||||
private void setTextView() {
|
||||
if (graphicOn) {
|
||||
remove(graphic);
|
||||
add(BorderLayout.CENTER, scrollPane);
|
||||
graphicOn = false;
|
||||
validate();
|
||||
repaint();
|
||||
}
|
||||
}
|
||||
|
||||
private String openFileDialog(Path startDirectory, String pattern) {
|
||||
FileDialog fd = new FileDialog(this, "Open");
|
||||
if (pattern != null)
|
||||
fd.setFile(pattern);
|
||||
if (startDirectory != null)
|
||||
fd.setDirectory(startDirectory.toString());
|
||||
fd.setVisible(true);
|
||||
return fd.getDirectory() + fd.getFile();
|
||||
}
|
||||
|
||||
private void testCommand(boolean retest) throws Exception {
|
||||
if (!retest) {
|
||||
lastTestFile = openFileDialog(getPathCompiled(), "*test.class");
|
||||
}
|
||||
|
||||
if (lastTestFile == null) {
|
||||
output.append("ERROR no Test spezified\n");
|
||||
} else if (unitTest != null) {
|
||||
output.append(unitTest.execute(lastTestFile));
|
||||
}
|
||||
}
|
||||
|
||||
private void connectCommand() throws Exception {
|
||||
String name = openFileDialog(getPathCompiled(), "*Server.class");
|
||||
loadServer(name);
|
||||
lastServer = name;
|
||||
String fullClassName = command.getClass().getName();
|
||||
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
|
||||
setTitle("ExBox connected to " + simpleClassName);
|
||||
|
||||
}
|
||||
|
||||
private void resetCommand() throws Exception {
|
||||
if (lastServer != null) {
|
||||
loadServer(lastServer);
|
||||
}
|
||||
}
|
||||
|
||||
private void loadServer(String name) throws Exception {
|
||||
command = ServerFactory.createServer(name);
|
||||
}
|
||||
|
||||
private void openFile() throws Exception {
|
||||
String name = openFileDialog(null, null);
|
||||
|
||||
try (BufferedReader br = new BufferedReader(
|
||||
new InputStreamReader(new FileInputStream(name), STANDARDENCODING))) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
String line;
|
||||
|
||||
while ((line = br.readLine()) != null) {
|
||||
b.append(line);
|
||||
b.append('\n');
|
||||
}
|
||||
|
||||
execute(b.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public void itemStateChanged(ItemEvent e) {
|
||||
try {
|
||||
arguments.setText((String) e.getItem());
|
||||
execute(arguments.getText());
|
||||
} catch (Throwable ex) {
|
||||
error(ex.toString());
|
||||
}
|
||||
}
|
||||
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
try {
|
||||
if ((e.getSource() == arguments) || (e.getSource() == enter)) {
|
||||
execute(arguments.getText());
|
||||
} else if (e.getSource() == connect) {
|
||||
connectCommand();
|
||||
} else if (e.getSource() == reset) {
|
||||
resetCommand();
|
||||
} else if (e.getSource() == test) {
|
||||
testCommand(false);
|
||||
} else if (e.getSource() == retest) {
|
||||
testCommand(true);
|
||||
} else if (e.getSource() == open) {
|
||||
openFile();
|
||||
} else if (e.getSource() == textView) {
|
||||
setTextView();
|
||||
} else if (e.getSource() == graphicView) {
|
||||
setGraphicView();
|
||||
} else if (e.getSource() == clear) {
|
||||
output.setText("");
|
||||
} else if (e.getSource() == exit) {
|
||||
System.exit(0);
|
||||
}
|
||||
} catch (Throwable ex) {
|
||||
ex.printStackTrace();
|
||||
error(ex.toString());
|
||||
}
|
||||
}
|
||||
}
|
98
app/src/main/java/ch/nuth/zhaw/exbox/ExBoxJUnit.java
Normal file
98
app/src/main/java/ch/nuth/zhaw/exbox/ExBoxJUnit.java
Normal file
|
@ -0,0 +1,98 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.platform.engine.TestDescriptor;
|
||||
import org.junit.platform.engine.TestExecutionResult;
|
||||
import org.junit.platform.engine.discovery.DiscoverySelectors;
|
||||
import org.junit.platform.launcher.Launcher;
|
||||
import org.junit.platform.launcher.LauncherDiscoveryRequest;
|
||||
import org.junit.platform.launcher.TestExecutionListener;
|
||||
import org.junit.platform.launcher.TestIdentifier;
|
||||
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
|
||||
import org.junit.platform.launcher.core.LauncherFactory;
|
||||
|
||||
import java.io.*;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class ExBoxJUnit implements CommandExecutor {
|
||||
@Override
|
||||
public String execute(String testFile) throws Exception {
|
||||
final List<String> successfulTests = new LinkedList<>();
|
||||
final List<TestFailure> failedResults = new LinkedList<>();
|
||||
StringBuilder output = new StringBuilder();
|
||||
output.append("\nRUN TESTS ").append(new File(testFile).getName().split("\\.")[0]).append("\n");
|
||||
|
||||
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
|
||||
.selectors(DiscoverySelectors.selectClass(ServerFactory.loadClass(testFile)))
|
||||
.build();
|
||||
|
||||
Launcher launcher = LauncherFactory.create();
|
||||
launcher.discover(request);
|
||||
|
||||
launcher.registerTestExecutionListeners(new TestExecutionListener() {
|
||||
@Override
|
||||
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
|
||||
if (testIdentifier.getType() != TestDescriptor.Type.TEST) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (testExecutionResult.getStatus() == TestExecutionResult.Status.SUCCESSFUL) {
|
||||
successfulTests.add(testIdentifier.getDisplayName());
|
||||
} else {
|
||||
failedResults.add(new TestFailure(testIdentifier.getDisplayName(),
|
||||
testExecutionResult.getThrowable().orElse(null)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
launcher.execute(request);
|
||||
|
||||
for (String testName : successfulTests) {
|
||||
output.append(testName).append(": OK\n");
|
||||
}
|
||||
|
||||
for (TestFailure result : failedResults) {
|
||||
output.append(result.getName()).append(": ERROR\n");
|
||||
String error = result.errorString();
|
||||
|
||||
if (!error.isEmpty()) {
|
||||
output.append(error).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
boolean wasSuccessful = failedResults.isEmpty();
|
||||
|
||||
output.append("TESTS ").append(wasSuccessful ? "PASSED" : "FAILED").append(": ")
|
||||
.append(wasSuccessful ? "OK \u263a" : failedResults.size() + " ERRORS").append("\n");
|
||||
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
private static class TestFailure {
|
||||
private final String name;
|
||||
private final Throwable throwable;
|
||||
|
||||
TestFailure(String name, Throwable throwable) {
|
||||
this.name = name;
|
||||
this.throwable = throwable;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public String errorString() {
|
||||
if (throwable == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
try (StringWriter stringWriter = new StringWriter();
|
||||
PrintWriter printWriter = new PrintWriter(stringWriter)) {
|
||||
throwable.printStackTrace(printWriter);
|
||||
return stringWriter.toString();
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
142
app/src/main/java/ch/nuth/zhaw/exbox/FuzzySearchServer.java
Normal file
142
app/src/main/java/ch/nuth/zhaw/exbox/FuzzySearchServer.java
Normal file
|
@ -0,0 +1,142 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.StringReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
|
||||
public class FuzzySearchServer implements CommandExecutor {
|
||||
public static List<String> names = new ArrayList<>(); // List of all names
|
||||
public static Map<String, List<Integer>> trigrams = new HashMap<>(); // List of all Trigrams
|
||||
public static Map<Integer, Integer> counts = new HashMap<>(); // Key: index of
|
||||
|
||||
// load all names into names List
|
||||
// each name only once (i.e. no doublettes allowed
|
||||
public static void loadNames(String nameString) {
|
||||
// TODO implement
|
||||
BufferedReader reader = new BufferedReader(new StringReader(nameString));
|
||||
String line;
|
||||
|
||||
try {
|
||||
while ((line = reader.readLine()) != null) {
|
||||
String name = line.split(";")[0];
|
||||
names.add(name);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("An error occurred:");
|
||||
System.err.println(e);
|
||||
}
|
||||
}
|
||||
|
||||
// add a single trigram to 'trigrams' index
|
||||
public static void addToTrigrams(int nameIdx, String trig) {
|
||||
// TODO implement
|
||||
trigrams.computeIfAbsent(trig, (_name) -> new ArrayList<>()).add(nameIdx);
|
||||
}
|
||||
|
||||
// works better for flipped and short names if " " added and lowercase
|
||||
private static String nomalize(String name) {
|
||||
return " " + name.toLowerCase().trim() + " ";
|
||||
}
|
||||
|
||||
// construct a list of trigrams for a name
|
||||
public static List<String> trigramForName(String name) {
|
||||
List<String> result = new ArrayList<>();
|
||||
name = nomalize(name);
|
||||
// TODO implement
|
||||
|
||||
for (int i = 0; i <= name.length() - 3; i++) {
|
||||
result.add(name.substring(i, i + 3));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static void constructTrigramIndex(List<String> names) {
|
||||
for (int nameIdx = 0; nameIdx < names.size(); nameIdx++) {
|
||||
List<String> trigs = trigramForName(names.get(nameIdx));
|
||||
|
||||
for (String trig : trigs) {
|
||||
addToTrigrams(nameIdx, trig);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void incCount(int cntIdx, Map<Integer, Integer> counts) {
|
||||
int count = counts.computeIfAbsent(cntIdx, (_index) -> 0);
|
||||
counts.put(cntIdx, count + 1);
|
||||
}
|
||||
|
||||
// find name index with most corresponding trigrams
|
||||
// if no trigram/name matches at all then return -1
|
||||
public static int findIdx(String name, Map<Integer, Integer> counts) {
|
||||
int maxIdx = -1;
|
||||
int maxCount = -1;
|
||||
|
||||
for (String trigram : trigramForName(name)) {
|
||||
if (trigrams.containsKey(trigram)) {
|
||||
for (int index : trigrams.get(trigram)) {
|
||||
incCount(index, counts);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (Entry<Integer, Integer> entry : counts.entrySet()) {
|
||||
if (entry.getValue() > maxCount) {
|
||||
maxCount = entry.getValue();
|
||||
maxIdx = entry.getKey();
|
||||
}
|
||||
}
|
||||
|
||||
return maxIdx;
|
||||
}
|
||||
|
||||
// finde Namen gebe "" zurück wenn gefundener Name nicht grösser als verlangter
|
||||
// score ist.
|
||||
public static String find(String searchName, int scoreRequired) {
|
||||
Map<Integer, Integer> counts = new HashMap<>();
|
||||
int found = findIdx(searchName, counts);
|
||||
String foundName = "";
|
||||
|
||||
if (found >= 0 && score(found, counts) >= scoreRequired) {
|
||||
foundName = names.get(found);
|
||||
}
|
||||
return foundName;
|
||||
}
|
||||
|
||||
private static int score(int found, Map<Integer, Integer> counts) {
|
||||
String foundName = names.get(found);
|
||||
return (int) (100.0 * Math.min(counts.get(found), foundName.length()) / foundName.length());
|
||||
}
|
||||
|
||||
public String execute(String searchName) {
|
||||
Map<Integer, Integer> counts = new HashMap<>();
|
||||
int found = findIdx(searchName, counts);
|
||||
|
||||
if (found >= 0) {
|
||||
int score = score(found, counts);
|
||||
String foundName = names.get(found);
|
||||
return searchName + " -> " + foundName + " " + score + "%\n";
|
||||
} else {
|
||||
return "nothing found\n";
|
||||
}
|
||||
}
|
||||
|
||||
static {
|
||||
String rangliste = "Mueller Stefan;02:31:14\n" +
|
||||
"Marti Adrian;02:30:09\n" +
|
||||
"Kiptum Daniel;02:11:31\n" +
|
||||
"Ancay Tarcis;02:20:02\n" +
|
||||
"Kreibuhl Christian;02:21:47\n" +
|
||||
"Ott Michael;02:33:48\n" +
|
||||
"Menzi Christoph;02:27:26\n" +
|
||||
"Oliver Ruben;02:32:12\n" +
|
||||
"Elmer Beat;02:33:53\n" +
|
||||
"Kuehni Martin;02:33:36\n";
|
||||
loadNames(rangliste);
|
||||
constructTrigramIndex(names);
|
||||
}
|
||||
}
|
15
app/src/main/java/ch/nuth/zhaw/exbox/Graph.java
Normal file
15
app/src/main/java/ch/nuth/zhaw/exbox/Graph.java
Normal file
|
@ -0,0 +1,15 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
public interface Graph<N, E> {
|
||||
/** füge Knoten hinzu, tue nichts, falls Knoten schon existiert */
|
||||
N addNode (String name) throws Throwable;
|
||||
|
||||
/** finde den Knoten anhand seines Namens */
|
||||
N findNode(String name);
|
||||
|
||||
/** Iterator über alle Knoten des Graphen */
|
||||
Iterable<N> getNodes();
|
||||
|
||||
/** füge gerichtete und gewichtete Kante hinzu */
|
||||
void addEdge(String source, String dest, double weight) throws Throwable ;
|
||||
}
|
88
app/src/main/java/ch/nuth/zhaw/exbox/GraphicPanel.java
Normal file
88
app/src/main/java/ch/nuth/zhaw/exbox/GraphicPanel.java
Normal file
|
@ -0,0 +1,88 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import javax.swing.*;
|
||||
import java.awt.*;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
public class GraphicPanel extends JPanel {
|
||||
String figure;
|
||||
|
||||
public void setFigure(String figure) {
|
||||
this.figure = figure;
|
||||
paint(getGraphics());
|
||||
}
|
||||
|
||||
private void drawRect(Graphics g, double x, double y, double width, double height, String style) {
|
||||
int w = getWidth();
|
||||
int h = getHeight();
|
||||
int ix0 = (int) (w * x);
|
||||
int iy0 = (int) (h * y);
|
||||
int ix1 = (int) (w * (x + width));
|
||||
int iy1 = (int) (h * (y + height));
|
||||
|
||||
if (style.equals("draw")) {
|
||||
g.drawRect(ix0, h - iy1, ix1 - ix0, iy1 - iy0);
|
||||
} else {
|
||||
g.fillRect(ix0, h - iy1, ix1 - ix0, iy1 - iy0);
|
||||
}
|
||||
}
|
||||
|
||||
private void drawFigure(Graphics g) {
|
||||
if (figure != null) {
|
||||
int w = getWidth();
|
||||
int h = getHeight();
|
||||
g.setColor(Color.black);
|
||||
StringTokenizer tok = new StringTokenizer(figure, " <>=/,\"\n");
|
||||
|
||||
while (tok.hasMoreTokens()) {
|
||||
String fig = tok.nextToken();
|
||||
|
||||
if (fig.equals("line")) {
|
||||
tok.nextToken();
|
||||
double x1 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double y1 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double x2 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double y2 = Double.parseDouble(tok.nextToken());
|
||||
|
||||
g.drawLine((int) (x1 * w), h - (int) (y1 * h),
|
||||
(int) (x2 * w), h - (int) (y2 * h));
|
||||
} else if (fig.equals("rect")) {
|
||||
tok.nextToken();
|
||||
double x = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double y = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double width = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double height = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
String style = tok.nextToken();
|
||||
drawRect(g, x, y, width, height, style);
|
||||
} else if (fig.equals("color")) {
|
||||
tok.nextToken();
|
||||
int red = Integer.parseInt(tok.nextToken());
|
||||
tok.nextToken();
|
||||
int green = Integer.parseInt(tok.nextToken());
|
||||
tok.nextToken();
|
||||
int blue = Integer.parseInt(tok.nextToken());
|
||||
g.setColor(new Color(red, green, blue));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void clear(Graphics g) {
|
||||
int w = getWidth();
|
||||
int h = getHeight();
|
||||
g.setColor(new Color(240, 240, 240));
|
||||
g.fillRect(0, 0, w, h);
|
||||
}
|
||||
|
||||
public void paint(Graphics g) {
|
||||
clear(g);
|
||||
drawFigure(g);
|
||||
}
|
||||
}
|
25
app/src/main/java/ch/nuth/zhaw/exbox/HanoiServer.java
Normal file
25
app/src/main/java/ch/nuth/zhaw/exbox/HanoiServer.java
Normal file
|
@ -0,0 +1,25 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/**
|
||||
* Provides the functionality to determine the solution of a hanoi puzzle.
|
||||
*/
|
||||
public class HanoiServer implements CommandExecutor {
|
||||
@Override
|
||||
public String execute(String command) throws Exception {
|
||||
int count = Integer.parseInt(command);
|
||||
return moveDisks(count, 'A', 'B', 'C') + System.lineSeparator();
|
||||
}
|
||||
|
||||
public String moveDisks(int count, char sourcePole, char restPole, char destinationPole) {
|
||||
String start = "";
|
||||
String mid = String.format("Move disk %d from %s to %s", count, sourcePole, destinationPole);
|
||||
String end = "";
|
||||
|
||||
if (count > 1) {
|
||||
start = moveDisks(count - 1, sourcePole, destinationPole, restPole);
|
||||
end = moveDisks(count - 1, restPole, sourcePole, destinationPole);
|
||||
}
|
||||
|
||||
return String.join(System.lineSeparator(), start, mid, end).trim();
|
||||
}
|
||||
}
|
45
app/src/main/java/ch/nuth/zhaw/exbox/HashServer.java
Normal file
45
app/src/main/java/ch/nuth/zhaw/exbox/HashServer.java
Normal file
|
@ -0,0 +1,45 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
|
||||
public class HashServer implements CommandExecutor {
|
||||
private final static int STARTNR = 0;
|
||||
private final static int NAME = 1;
|
||||
private final static int TIME = 2;
|
||||
|
||||
private final Map<MyCompetitor, MyCompetitor> data = new MyHashtable<>(4000);
|
||||
|
||||
private long parseTime(String s) throws Exception {
|
||||
DateFormat sdf = new SimpleDateFormat("HH:mm:ss.S");
|
||||
Date date = sdf.parse(s);
|
||||
return date.getTime();
|
||||
}
|
||||
|
||||
public void load(Map<MyCompetitor, MyCompetitor> data, String list) {
|
||||
String[] lines = list.split("\n");
|
||||
for (String line : lines) {
|
||||
String[] items = line.split(";");
|
||||
MyCompetitor c = new MyCompetitor(Integer.parseInt(items[STARTNR]), // startNr
|
||||
items[NAME], // name
|
||||
items[TIME]); // time
|
||||
data.put(c, c);
|
||||
}
|
||||
}
|
||||
|
||||
public String execute(String arg) {
|
||||
if (arg.toUpperCase().startsWith("GET")) {
|
||||
String[] items = arg.substring(3).trim().split(";");
|
||||
MyCompetitor key = new MyCompetitor(Integer.parseInt(items[1]), items[0], "00:00:00.0");
|
||||
MyCompetitor o = data.get(key);
|
||||
if (o != null) {
|
||||
return items[0] + " " + items[1] + " -> " + o + "\n";
|
||||
}
|
||||
return "not found\n";
|
||||
}
|
||||
load(data, arg);
|
||||
return "" + data.size() + " loaded\n";
|
||||
}
|
||||
}
|
36
app/src/main/java/ch/nuth/zhaw/exbox/HilbertServer.java
Normal file
36
app/src/main/java/ch/nuth/zhaw/exbox/HilbertServer.java
Normal file
|
@ -0,0 +1,36 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/**
|
||||
* Provides the functionality to draw hilbert curves.
|
||||
*/
|
||||
public class HilbertServer implements CommandExecutor {
|
||||
@Override
|
||||
public String execute(String command) {
|
||||
int depth = Integer.parseInt(command);
|
||||
Turtle turtle = Turtle.instance();
|
||||
double dist = 0.8 / (Math.pow(2, depth + 1) - 1);
|
||||
turtle.reset(0.1, 0.1);
|
||||
hilbert(turtle, depth, dist, -90);
|
||||
return turtle.getTrace();
|
||||
}
|
||||
|
||||
private void hilbert(Turtle turtle, int depth, double dist, double angle) {
|
||||
if (depth >= 0) {
|
||||
turtle.turn(-angle);
|
||||
|
||||
hilbert(turtle, depth - 1, dist, -angle);
|
||||
turtle.move(dist);
|
||||
turtle.turn(angle);
|
||||
|
||||
hilbert(turtle, depth - 1, dist, angle);
|
||||
turtle.move(dist);
|
||||
|
||||
hilbert(turtle, depth - 1, dist, angle);
|
||||
turtle.turn(angle);
|
||||
turtle.move(dist);
|
||||
|
||||
hilbert(turtle, depth - 1, dist, -angle);
|
||||
turtle.turn(-angle);
|
||||
}
|
||||
}
|
||||
}
|
25
app/src/main/java/ch/nuth/zhaw/exbox/Ingredient.java
Normal file
25
app/src/main/java/ch/nuth/zhaw/exbox/Ingredient.java
Normal file
|
@ -0,0 +1,25 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
public class Ingredient {
|
||||
private final String name;
|
||||
private final float gramInBakery;
|
||||
private float gramUsedForBaking;
|
||||
|
||||
Ingredient (String name, int gramInBakery) {
|
||||
this.name = name;
|
||||
this.gramInBakery = gramInBakery;
|
||||
}
|
||||
|
||||
void initialiseStockBeforeCooking() {
|
||||
gramUsedForBaking = 0;
|
||||
}
|
||||
|
||||
boolean removeFromStock(float gramToRemove) {
|
||||
gramUsedForBaking += gramToRemove;
|
||||
return gramUsedForBaking <= gramInBakery;
|
||||
}
|
||||
|
||||
String getRemainingStock() {
|
||||
return name + ": " + (gramInBakery - gramUsedForBaking) + ", ";
|
||||
}
|
||||
}
|
39
app/src/main/java/ch/nuth/zhaw/exbox/LCMServer.java
Normal file
39
app/src/main/java/ch/nuth/zhaw/exbox/LCMServer.java
Normal file
|
@ -0,0 +1,39 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.Formatter;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class LCMServer implements CommandExecutor {
|
||||
Formatter formatter = new Formatter();
|
||||
Pattern pattern = Pattern.compile("^([0-9]+),?\\s*([0-9]+)$");
|
||||
|
||||
@Override
|
||||
public String execute(String command) throws Exception {
|
||||
Matcher matcher = pattern.matcher(command);
|
||||
|
||||
if (matcher.find()) {
|
||||
int x = Integer.parseInt(matcher.group(1));
|
||||
int y = Integer.parseInt(matcher.group(2));
|
||||
int result = leastCommonMultiple(x, y);
|
||||
return "Das Resultat ist %d\n".formatted(result);
|
||||
} else {
|
||||
throw new Exception("Der angegebene Befehl \"%s\" ist ungültig!\n".formatted(command));
|
||||
}
|
||||
}
|
||||
|
||||
public int leastCommonMultiple(int x, int y) {
|
||||
return Math.abs(x * y) / greatestCommonDivisor(x, y);
|
||||
}
|
||||
|
||||
public int greatestCommonDivisor(int x, int y) {
|
||||
while (y != 0) {
|
||||
x %= y;
|
||||
x ^= y;
|
||||
y ^= x;
|
||||
x ^= y;
|
||||
}
|
||||
|
||||
return x;
|
||||
}
|
||||
}
|
105
app/src/main/java/ch/nuth/zhaw/exbox/LabyrinthServer.java
Normal file
105
app/src/main/java/ch/nuth/zhaw/exbox/LabyrinthServer.java
Normal file
|
@ -0,0 +1,105 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.io.BufferedReader;
|
||||
import java.io.StringReader;
|
||||
|
||||
public class LabyrinthServer implements CommandExecutor {
|
||||
ServerGraphics g = new ServerGraphics();
|
||||
|
||||
/**
|
||||
* Gets a component for creating graphic content.
|
||||
*
|
||||
* @return A component for creating graphic content.
|
||||
*/
|
||||
public ServerGraphics getGraphics() {
|
||||
return g;
|
||||
}
|
||||
|
||||
public Graph<DijkstraNode, Edge> createGraph(String s) {
|
||||
// TODO implement 8.2
|
||||
Graph<DijkstraNode, Edge> graph = new AdjListGraph<>(DijkstraNode.class, Edge.class);
|
||||
|
||||
try {
|
||||
try (BufferedReader reader = new BufferedReader(new StringReader(s))) {
|
||||
String currentLine;
|
||||
|
||||
while ((currentLine = reader.readLine()) != null) {
|
||||
String[] elements = currentLine.split(" ");
|
||||
|
||||
for (int i = 0; i <= 1; i++) {
|
||||
graph.addEdge(elements[i], elements[1 - i], 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
}
|
||||
|
||||
return graph;
|
||||
}
|
||||
|
||||
public void drawLabyrinth(Graph<DijkstraNode, Edge> graph) {
|
||||
// TODO implement 8.3
|
||||
ServerGraphics graphics = getGraphics();
|
||||
graphics.setColor(Color.GRAY);
|
||||
graphics.fillRect(0, 0, 1, 1);
|
||||
graphics.setColor(Color.WHITE);
|
||||
|
||||
for (DijkstraNode node : graph.getNodes()) {
|
||||
for (Edge edge : node.getEdges()) {
|
||||
if (edge.getDest() instanceof DijkstraNode destination) {
|
||||
graphics.drawPath(node.getName(), destination.getName(), false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean search(DijkstraNode current, DijkstraNode destination) {
|
||||
current.setMark(true);
|
||||
|
||||
if (current == destination) {
|
||||
return true;
|
||||
} else {
|
||||
for (Edge edge : current.getEdges()) {
|
||||
if (edge.getDest() instanceof DijkstraNode node &&
|
||||
!node.getMark()) {
|
||||
node.setPrev(current);
|
||||
|
||||
if (search(node, destination)) {
|
||||
return true;
|
||||
} else {
|
||||
node.setPrev(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// search and draw result
|
||||
public void drawRoute(Graph<DijkstraNode, Edge> graph, String startNode, String destinationNode) {
|
||||
// TODO implement 8.4
|
||||
ServerGraphics graphics = getGraphics();
|
||||
DijkstraNode currentNode = graph.findNode(destinationNode);
|
||||
graphics.setColor(Color.RED);
|
||||
|
||||
if (search(graph.findNode(startNode), currentNode)) {
|
||||
while (currentNode.getPrev() != null) {
|
||||
DijkstraNode previousNode = currentNode.getPrev();
|
||||
graphics.drawPath(previousNode.getName(), currentNode.getName(), true);
|
||||
currentNode = previousNode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public String execute(String s) {
|
||||
Graph<DijkstraNode, Edge> graph;
|
||||
ServerGraphics graphics = getGraphics();
|
||||
graphics.clear();
|
||||
graph = createGraph(s);
|
||||
drawLabyrinth(graph);
|
||||
drawRoute(graph, "0-6", "3-0");
|
||||
return graphics.getTrace();
|
||||
}
|
||||
}
|
56
app/src/main/java/ch/nuth/zhaw/exbox/ListStack.java
Normal file
56
app/src/main/java/ch/nuth/zhaw/exbox/ListStack.java
Normal file
|
@ -0,0 +1,56 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ListStack implements Stack {
|
||||
private List<Object> innerList = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void push(Object x) throws StackOverflowError {
|
||||
try {
|
||||
if (innerList.add(x)) {
|
||||
return;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new StackOverflowError();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object pop() {
|
||||
if (!isEmpty()) {
|
||||
int index = innerList.size() - 1;
|
||||
Object result = innerList.get(index);
|
||||
innerList.remove(index);
|
||||
return result;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return innerList.size() == 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object peek() {
|
||||
if (!isEmpty()) {
|
||||
return innerList.get(innerList.size() - 1);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeAll() {
|
||||
innerList.clear();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isFull() {
|
||||
return innerList.size() == Integer.MIN_VALUE;
|
||||
}
|
||||
|
||||
}
|
82
app/src/main/java/ch/nuth/zhaw/exbox/MyCompetitor.java
Normal file
82
app/src/main/java/ch/nuth/zhaw/exbox/MyCompetitor.java
Normal file
|
@ -0,0 +1,82 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
public class MyCompetitor implements Comparable<MyCompetitor> {
|
||||
private final String name;
|
||||
private final String time;
|
||||
private int rank;
|
||||
|
||||
public MyCompetitor(int rank, String name, String time) {
|
||||
this.rank = rank;
|
||||
this.name = name;
|
||||
this.time = time;
|
||||
}
|
||||
|
||||
public void setRank(int rank) {
|
||||
this.rank = rank;
|
||||
}
|
||||
|
||||
public String getTime() {
|
||||
return time;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
private static long parseTime(String s) {
|
||||
try {
|
||||
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
|
||||
Date date = sdf.parse(s);
|
||||
return date.getTime();
|
||||
} catch (Exception e) {System.err.println(e);}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static String timeToString(int time) {
|
||||
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
|
||||
return df.format(new Date(time));
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return ""+ rank + " "+name+" "+time;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int compareTo(MyCompetitor o) {
|
||||
int result = getName().compareTo(o.getName());
|
||||
|
||||
if (result == 0) {
|
||||
result = getTime().compareTo(o.getTime());
|
||||
|
||||
if (result == 0) {
|
||||
result = rank - o.rank;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
int hashCode = 13;
|
||||
hashCode += getName().hashCode();
|
||||
hashCode *= 17;
|
||||
return hashCode + rank;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals (Object o) {
|
||||
if (o instanceof MyCompetitor c) {
|
||||
return hashCode() == c.hashCode() &&
|
||||
getName().equals(c.getName()) &&
|
||||
getTime().equals(c.getTime()) &&
|
||||
rank == c.rank;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
171
app/src/main/java/ch/nuth/zhaw/exbox/MyHashtable.java
Normal file
171
app/src/main/java/ch/nuth/zhaw/exbox/MyHashtable.java
Normal file
|
@ -0,0 +1,171 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public class MyHashtable<K, V> implements Map<K, V> {
|
||||
private int capacity;
|
||||
private int size;
|
||||
private K[] keys = (K[]) new Object[10];
|
||||
private V[] values = (V[]) new Object[10];
|
||||
|
||||
public MyHashtable(int size) {
|
||||
capacity = size;
|
||||
clear();
|
||||
}
|
||||
|
||||
private boolean keyEquals(Object x, Object y) {
|
||||
if (x == null || y == null) {
|
||||
return x == y;
|
||||
} else {
|
||||
return x.equals(y);
|
||||
}
|
||||
}
|
||||
|
||||
private int hash(Object k) {
|
||||
int h = Math.abs(k.hashCode());
|
||||
return h % keys.length;
|
||||
}
|
||||
|
||||
private int findIndex(Object key) {
|
||||
for (int i = 0; i < keys.length; i++) {
|
||||
if (keyEquals(key, keys[i])) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
private void resize(int size) {
|
||||
int oldSize = this.size;
|
||||
int oldCapacity = capacity;
|
||||
K[] oldKeys = keys;
|
||||
V[] oldValues = values;
|
||||
capacity = size;
|
||||
clear();
|
||||
this.size = oldSize;
|
||||
|
||||
for (int i = 0; i < oldCapacity; i++) {
|
||||
keys[i] = oldKeys[i];
|
||||
values[i] = oldValues[i];
|
||||
}
|
||||
}
|
||||
|
||||
// Removes all mappings from this map (optional operation).
|
||||
public void clear() {
|
||||
size = 0;
|
||||
keys = (K[]) new Object[capacity];
|
||||
values = (V[]) new Object[capacity];
|
||||
}
|
||||
|
||||
// Associates the specified value with the specified key in this map (optional
|
||||
// operation).
|
||||
public V put(K key, V value) {
|
||||
int index = findIndex(key);
|
||||
|
||||
if (index == -1) {
|
||||
size++;
|
||||
|
||||
if (size > capacity) {
|
||||
resize(capacity * 2);
|
||||
}
|
||||
|
||||
int hashCode = hash(key);
|
||||
index = hashCode;
|
||||
|
||||
for (int i = 0; keys[index] != null; i++) {
|
||||
index = hash(hashCode + i);
|
||||
}
|
||||
}
|
||||
|
||||
keys[index] = key;
|
||||
values[index] = value;
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
// Returns the value to which this map maps the specified key.
|
||||
public V get(Object key) {
|
||||
// to be done
|
||||
for (int i = 0; i < keys.length; i++) {
|
||||
if (keyEquals(key, keys[i])) {
|
||||
return values[i];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// Removes the mapping for this key from this map if present (optional
|
||||
// operation).
|
||||
public V remove(Object key) {
|
||||
// to be done (Aufgabe 3)
|
||||
int index = findIndex(key);
|
||||
|
||||
if (index >= 0) {
|
||||
V value = values[index];
|
||||
size--;
|
||||
keys[index] = null;
|
||||
values[index] = null;
|
||||
return value;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the number of key-value mappings in this map.
|
||||
public int size() {
|
||||
return size;
|
||||
}
|
||||
|
||||
// UnsupportedOperationException
|
||||
// ===================================================================
|
||||
// Returns a collection view of the values contained in this map.
|
||||
public Collection<V> values() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
// Returns true if this map contains a mapping for the specified key.
|
||||
public boolean containsKey(Object key) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
// Returns true if this map maps one or more keys to the specified value.
|
||||
public boolean containsValue(Object value) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
// Returns a set view of the mappings contained in this map.
|
||||
public Set<Map.Entry<K, V>> entrySet() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
// Compares the specified object with this map for equality.
|
||||
public boolean equals(Object o) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
// Copies all of the mappings from the specified map to this map (optional
|
||||
// operation).
|
||||
public void putAll(Map<? extends K, ? extends V> t) {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
// Returns the hash code value for this map.
|
||||
public int hashCode() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
// Returns true if this map contains no key-value mappings.
|
||||
public boolean isEmpty() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
|
||||
// Returns a set view of the keys contained in this map.
|
||||
public Set<K> keySet() {
|
||||
throw new UnsupportedOperationException();
|
||||
}
|
||||
}
|
261
app/src/main/java/ch/nuth/zhaw/exbox/MyList.java
Normal file
261
app/src/main/java/ch/nuth/zhaw/exbox/MyList.java
Normal file
|
@ -0,0 +1,261 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.AbstractList;
|
||||
|
||||
/**
|
||||
* Provides the functionality to store a collection of items.
|
||||
*/
|
||||
public class MyList extends AbstractList<Object> {
|
||||
/**
|
||||
* Represents the node of a list.
|
||||
*/
|
||||
protected static interface IListNode {
|
||||
/**
|
||||
* Gets the next node neighbouring this node.
|
||||
*
|
||||
* @return
|
||||
* The next node neighbouring this node.
|
||||
*/
|
||||
IListNode getNextNode();
|
||||
|
||||
/**
|
||||
* Sets the next node neighbouring this node.
|
||||
*
|
||||
* @param nextNode
|
||||
* The value to set.
|
||||
*/
|
||||
void setNextNode(IListNode nextNode);
|
||||
|
||||
/**
|
||||
* Gets the previous node neighbouring this node.
|
||||
*
|
||||
* @return
|
||||
* The previous node neighbouring this node.
|
||||
*/
|
||||
IListNode getPreviousNode();
|
||||
|
||||
/**
|
||||
* Sets the previous node neighbouring this node.
|
||||
*
|
||||
* @param previousNode
|
||||
* The value to set.
|
||||
*/
|
||||
void setPreviousNode(IListNode previousNode);
|
||||
|
||||
/**
|
||||
* Gets the item contained by this node.
|
||||
*
|
||||
* @return
|
||||
* The item contained by this node.
|
||||
*/
|
||||
Object getItem();
|
||||
|
||||
/**
|
||||
* Sets the item contained by this node.
|
||||
*
|
||||
* @param item
|
||||
* The value to set.
|
||||
*/
|
||||
void setItem(Object item);
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the node of a list.
|
||||
*/
|
||||
protected static class ListNode implements IListNode {
|
||||
/**
|
||||
* The next node neighbouring this node.
|
||||
*/
|
||||
private IListNode nextNode;
|
||||
|
||||
/**
|
||||
* The previous node neighbouring this node.
|
||||
*/
|
||||
private IListNode previousNode;
|
||||
|
||||
/**
|
||||
* The item contained by this node.
|
||||
*/
|
||||
private Object item;
|
||||
|
||||
/**
|
||||
* Initializes a new instance of the {@linkplain ListNode `ListNode`} class.
|
||||
*/
|
||||
public ListNode() {
|
||||
this(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes a new instance of the {@linkplain ListNode `ListNode`} class.
|
||||
*
|
||||
* @param item
|
||||
* The item contained by this node.
|
||||
*/
|
||||
public ListNode(Object item) {
|
||||
this.item = item;
|
||||
nextNode = this;
|
||||
previousNode = this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes a new instance of the {@linkplain ListNode `ListNode`} class.
|
||||
*
|
||||
* @param nextNode
|
||||
* The next node neighbouring this node.
|
||||
*
|
||||
* @param previousNode
|
||||
* The previous node neighbouring this node.
|
||||
*/
|
||||
public ListNode(Object item, IListNode nextNode, IListNode previousNode) {
|
||||
this(item);
|
||||
this.nextNode = nextNode;
|
||||
this.previousNode = previousNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the next node neighbouring this node.
|
||||
*
|
||||
* @return
|
||||
* The next node neighbouring this node.
|
||||
*/
|
||||
public IListNode getNextNode() {
|
||||
return nextNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the next node neighbouring this node.
|
||||
*
|
||||
* @param nextNode
|
||||
* The value to set.
|
||||
*/
|
||||
public void setNextNode(IListNode nextNode) {
|
||||
this.nextNode = nextNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the previous node neighbouring this node.
|
||||
*
|
||||
* @return
|
||||
* The previous node neighbouring this node.
|
||||
*/
|
||||
public IListNode getPreviousNode() {
|
||||
return previousNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the previous node neighbouring this node.
|
||||
*
|
||||
* @param previousNode
|
||||
* The value to set.
|
||||
*/
|
||||
public void setPreviousNode(IListNode previousNode) {
|
||||
this.previousNode = previousNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the item contained by this node.
|
||||
*
|
||||
* @return
|
||||
* The item contained by this node.
|
||||
*/
|
||||
public Object getItem() {
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the item contained by this node.
|
||||
*
|
||||
* @param item
|
||||
* The value to set.
|
||||
*/
|
||||
public void setItem(Object item) {
|
||||
this.item = item;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The anchor of the list.
|
||||
*/
|
||||
private IListNode anchor = new ListNode();
|
||||
|
||||
/**
|
||||
* Gets the anchor of the list.
|
||||
*
|
||||
* @return
|
||||
* The anchor of the list.
|
||||
*/
|
||||
protected IListNode getAnchor() {
|
||||
return anchor;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the specified `item` after the specified `node`.
|
||||
*
|
||||
* @param node
|
||||
* The node to insert the `item` after.
|
||||
*
|
||||
* @param item
|
||||
* The item to insert.
|
||||
*/
|
||||
protected void insertAfter(IListNode node, Object item) {
|
||||
IListNode newNode = new ListNode(item, node.getNextNode(), node);
|
||||
node.setNextNode(newNode);
|
||||
newNode.getNextNode().setPreviousNode(newNode);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean add(Object e) {
|
||||
insertAfter(getAnchor().getPreviousNode(), e);
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean remove(Object o) {
|
||||
for (IListNode node = getAnchor().getNextNode(); node != getAnchor(); node = node.getNextNode()) {
|
||||
if (node.getItem().equals(o)) {
|
||||
node.getPreviousNode().setNextNode(node.getNextNode());
|
||||
node.getNextNode().setPreviousNode(node.getPreviousNode());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object get(int index) {
|
||||
IListNode currentNode = getAnchor().getNextNode();
|
||||
|
||||
for (int i = 0; i < index; i++) {
|
||||
currentNode = currentNode.getNextNode();
|
||||
|
||||
if (currentNode == getAnchor()) {
|
||||
throw new IndexOutOfBoundsException();
|
||||
}
|
||||
}
|
||||
|
||||
return currentNode.getItem();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEmpty() {
|
||||
return getAnchor().getNextNode() == getAnchor();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int size() {
|
||||
int result = 0;
|
||||
|
||||
for (IListNode node = getAnchor().getNextNode(); node != getAnchor(); node = node.getNextNode()) {
|
||||
result++;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clear() {
|
||||
getAnchor().setNextNode(getAnchor());
|
||||
getAnchor().setPreviousNode(getAnchor());
|
||||
}
|
||||
}
|
41
app/src/main/java/ch/nuth/zhaw/exbox/MySortedList.java
Normal file
41
app/src/main/java/ch/nuth/zhaw/exbox/MySortedList.java
Normal file
|
@ -0,0 +1,41 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/**
|
||||
* Represents a list with the ability to sort elements.
|
||||
*/
|
||||
public class MySortedList extends MyList {
|
||||
@Override
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public boolean add(Object item) {
|
||||
if (isEmpty()) {
|
||||
return super.add(item);
|
||||
} else {
|
||||
IListNode currentNode = getAnchor().getNextNode();
|
||||
|
||||
while (true) {
|
||||
int comparisonResult;
|
||||
|
||||
try {
|
||||
comparisonResult = ((Comparable) item).compareTo((Comparable) currentNode.getItem());
|
||||
} catch (Exception e) {
|
||||
comparisonResult = 0;
|
||||
}
|
||||
|
||||
if (comparisonResult == 0) {
|
||||
insertAfter(currentNode, item);
|
||||
return true;
|
||||
} else if (comparisonResult < 0) {
|
||||
insertAfter(currentNode.getPreviousNode(), item);
|
||||
return true;
|
||||
} else {
|
||||
currentNode = currentNode.getNextNode();
|
||||
|
||||
if (currentNode == getAnchor()) {
|
||||
insertAfter(currentNode.getPreviousNode(), item);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
20
app/src/main/java/ch/nuth/zhaw/exbox/MyVisitor.java
Normal file
20
app/src/main/java/ch/nuth/zhaw/exbox/MyVisitor.java
Normal file
|
@ -0,0 +1,20 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/**
|
||||
* MyVisitor -- Diese Klasse wird für die Tests verwendet
|
||||
*/
|
||||
class MyVisitor<T> implements Visitor<T> {
|
||||
StringBuilder output;
|
||||
|
||||
MyVisitor() {
|
||||
output = new StringBuilder();
|
||||
}
|
||||
|
||||
public void visit(T s) {
|
||||
output.append(s);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return output.toString();
|
||||
}
|
||||
}
|
34
app/src/main/java/ch/nuth/zhaw/exbox/Node.java
Normal file
34
app/src/main/java/ch/nuth/zhaw/exbox/Node.java
Normal file
|
@ -0,0 +1,34 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
public class Node {
|
||||
protected String name; // Name
|
||||
protected List<Edge> edges; // Kanten
|
||||
|
||||
public Node() {
|
||||
edges = new LinkedList<>();
|
||||
}
|
||||
|
||||
public Node(String name) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Iterable<Edge> getEdges() {
|
||||
return edges;
|
||||
}
|
||||
|
||||
public void addEdge(Edge edge) {
|
||||
edges.add(edge);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,204 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class ParallelQuickerSortServer extends Thread implements CommandExecutor {
|
||||
int[] arr, sourceArr;
|
||||
int left, right;
|
||||
static int dataElems = 100000;
|
||||
static int insertion_threshold = 100;
|
||||
private final int SPLIT_THRESHOLD = 10000;
|
||||
private final int DATARANGE = 10000000;
|
||||
|
||||
public ParallelQuickerSortServer() {}
|
||||
|
||||
public ParallelQuickerSortServer(int[] arr, int left, int right) {
|
||||
this.arr = arr;
|
||||
this.left = left;
|
||||
this.right = right;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
int mid = 0;
|
||||
Thread t1 = null;
|
||||
Thread t2 = null;
|
||||
|
||||
if (left < right) {
|
||||
// TODO Aufgabe 12.3
|
||||
mid = partition(arr, left, right);
|
||||
|
||||
if (mid - left > SPLIT_THRESHOLD) {
|
||||
t1 = new ParallelQuickerSortServer(arr, left, mid - 1);
|
||||
t1.start();
|
||||
} else {
|
||||
quickerSort(arr, left, mid - 1);
|
||||
}
|
||||
|
||||
if (right - mid > SPLIT_THRESHOLD) {
|
||||
t2 = new ParallelQuickerSortServer(arr, mid, right);
|
||||
t2.start();
|
||||
} else {
|
||||
quickerSort(arr, mid, right);
|
||||
}
|
||||
}
|
||||
|
||||
if (t1 != null) {
|
||||
try {
|
||||
t1.join();
|
||||
} catch (InterruptedException e) {}
|
||||
}
|
||||
|
||||
if (t2 != null) {
|
||||
try {
|
||||
t2.join();
|
||||
} catch (InterruptedException e) {}
|
||||
}
|
||||
}
|
||||
|
||||
private void quickerSort(int[] arr, int left, int right) {
|
||||
// TODO Aus Aufgabe 12.1 übernehmen
|
||||
if (right - left < insertion_threshold) {
|
||||
insertionSort(arr, left, right);
|
||||
} else {
|
||||
int l = partition(arr, left, right);
|
||||
quickerSort(arr, left, l - 1);
|
||||
quickerSort(arr, l, right);
|
||||
}
|
||||
}
|
||||
|
||||
private int partition(int[] arr, int left, int right) {
|
||||
// TODO Aus Aufgabe 12.1 übernehmen
|
||||
int pivot = arr[(left + right) / 2];
|
||||
|
||||
while (left <= right) {
|
||||
while (arr[left] < pivot) {
|
||||
left++;
|
||||
}
|
||||
|
||||
while (arr[right] > pivot) {
|
||||
right--;
|
||||
}
|
||||
|
||||
if (left <= right) {
|
||||
swap(arr, left, right);
|
||||
left++;
|
||||
right--;
|
||||
}
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
private void insertionSort(int[] a, int l, int r) {
|
||||
for (int k = l + 1; k < r + 1; k++) {
|
||||
if (a[k] < a[k - 1]) {
|
||||
int x = a[k];
|
||||
int i;
|
||||
for (i = k; ((i > 0) && (a[i - 1] > x)); i--) {
|
||||
a[i] = a[i - 1];
|
||||
}
|
||||
a[i] = x;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int[] randomData() {
|
||||
int[] a = new int[dataElems];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
a[i] = (int) (Math.random() * DATARANGE);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
public int[] ascendingData() {
|
||||
int[] a = new int[dataElems];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
a[i] = i;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
public int[] descendingData() {
|
||||
int[] a = new int[dataElems];
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
a[i] = a.length - i;
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
private void swap(int[] arr, int i, int j) {
|
||||
int swapElement;
|
||||
|
||||
swapElement = arr[i];
|
||||
arr[i] = arr[j];
|
||||
arr[j] = swapElement;
|
||||
}
|
||||
|
||||
private boolean isSorted(int[] a) {
|
||||
for (int i = 0; i < a.length - 1; i++) {
|
||||
if (a[i] > a[i + 1]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private double measureTime(Supplier<int[]> generator) throws Exception {
|
||||
double elapsed = 0;
|
||||
|
||||
sourceArr = generator.get();
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
long endTime = startTime;
|
||||
int count = 0;
|
||||
while (endTime < startTime + 10000) {
|
||||
System.arraycopy(sourceArr, 0, arr, 0, arr.length);
|
||||
Thread rootThread = new ParallelQuickerSortServer(arr, 0, arr.length - 1);
|
||||
rootThread.start();
|
||||
try {
|
||||
rootThread.join();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
count++;
|
||||
endTime = System.currentTimeMillis();
|
||||
}
|
||||
elapsed = (double) (endTime - startTime) / count;
|
||||
|
||||
if (!isSorted(arr)) throw new Exception("ERROR not eorted");
|
||||
return elapsed;
|
||||
}
|
||||
|
||||
public String execute(String arg) {
|
||||
Map<String, Supplier<int[]>> generator = Map.of(
|
||||
"RANDOM", this::randomData,
|
||||
"ASC", this::ascendingData,
|
||||
"DESC", this::descendingData
|
||||
);
|
||||
|
||||
String[] args = arg.toUpperCase().split(" ");
|
||||
dataElems = Integer.parseInt(args[1]);
|
||||
arr = new int[dataElems];
|
||||
sourceArr = new int[dataElems];
|
||||
insertion_threshold = Integer.parseInt(args[2]);
|
||||
try {
|
||||
try {
|
||||
double time = measureTime(generator.get(args[0]));
|
||||
return arg + " " + time + " ms\n";
|
||||
} catch (Exception ex) {
|
||||
return arg + " " + ex.getMessage();
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
return arg + " " + ex.getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ParallelQuickerSortServer sorter = new ParallelQuickerSortServer();
|
||||
String sort;
|
||||
sort = "RANDOM 10000 100"; System.out.println(sorter.execute(sort));
|
||||
sort = "ASC 10000 100"; System.out.println(sorter.execute(sort));
|
||||
sort = "DESC 10000 100"; System.out.println(sorter.execute(sort));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class RankingAVLTreeServer implements CommandExecutor {
|
||||
|
||||
public Tree<Competitor> createTree(String rankingText) {
|
||||
SortedBinaryTree<Competitor> result = new AVLSearchTree<>();
|
||||
List<Competitor> competitors = new RankingListServer().createList(rankingText);
|
||||
|
||||
for (Competitor competitor : competitors) {
|
||||
result.add(competitor);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String createSortedText(Tree<Competitor> competitorTree) {
|
||||
AtomicInteger rank = new AtomicInteger(1);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
competitorTree.traversal().inorder(
|
||||
(competitor) -> {
|
||||
competitor.setRank(rank.getAndIncrement());
|
||||
sb.append(competitor);
|
||||
sb.append(System.lineSeparator());
|
||||
});
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public String execute(String rankingList) {
|
||||
Tree<Competitor> competitorTree = createTree(rankingList);
|
||||
return "Rangliste (Tree)\n" + createSortedText(competitorTree) + "\n\n" +
|
||||
"Height: " + competitorTree.height() + "\nSize: " + competitorTree.size();
|
||||
}
|
||||
}
|
75
app/src/main/java/ch/nuth/zhaw/exbox/RankingListServer.java
Normal file
75
app/src/main/java/ch/nuth/zhaw/exbox/RankingListServer.java
Normal file
|
@ -0,0 +1,75 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.StringReader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class RankingListServer implements CommandExecutor {
|
||||
/**
|
||||
* The delimiter of the data.
|
||||
*/
|
||||
private static final String Delimiter = ";";
|
||||
|
||||
public List<Competitor> createList(String rankingText) {
|
||||
String currentLine;
|
||||
|
||||
try {
|
||||
try (BufferedReader reader = new BufferedReader(new StringReader(rankingText))) {
|
||||
List<Competitor> result = new ArrayList<>();
|
||||
|
||||
while ((currentLine = reader.readLine()) != null) {
|
||||
String[] fields = currentLine.split(Delimiter);
|
||||
|
||||
result.add(
|
||||
new Competitor(
|
||||
0,
|
||||
fields[0],
|
||||
fields[1]));
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("An error occurred");
|
||||
System.out.println(e);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public String createSortedText(List<Competitor> competitorList) {
|
||||
List<Competitor> competitors = competitorList.stream().sorted().collect(Collectors.toList());
|
||||
String previousTime = null;
|
||||
int previousRank = 1;
|
||||
|
||||
for (int i = 0; i < competitors.size(); i++) {
|
||||
Competitor competitor = competitors.get(i);
|
||||
|
||||
if (competitor.getTime() != previousTime) {
|
||||
previousRank = i + 1;
|
||||
previousTime = competitor.getTime();
|
||||
}
|
||||
|
||||
competitor.setRank(previousRank);
|
||||
}
|
||||
|
||||
return String.join(
|
||||
System.lineSeparator(),
|
||||
competitors.stream().map(
|
||||
(competitor) -> competitor.toString()).collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
public String createNameList(List<Competitor> competitorList) {
|
||||
return String.join(
|
||||
System.lineSeparator(),
|
||||
competitorList.stream().sorted(new AlphaComparatorCompetitor()).map(
|
||||
(competitor) -> competitor.toString()).collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
public String execute(String rankingList) {
|
||||
List<Competitor> competitorList = createList(rankingList);
|
||||
return "Rangliste\n" + createSortedText(competitorList);
|
||||
}
|
||||
}
|
38
app/src/main/java/ch/nuth/zhaw/exbox/RankingTreeServer.java
Normal file
38
app/src/main/java/ch/nuth/zhaw/exbox/RankingTreeServer.java
Normal file
|
@ -0,0 +1,38 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
public class RankingTreeServer implements CommandExecutor {
|
||||
|
||||
public Tree<Competitor> createTree(String rankingText) {
|
||||
SortedBinaryTree<Competitor> result = new SortedBinaryTree<>();
|
||||
List<Competitor> competitors = new RankingListServer().createList(rankingText);
|
||||
|
||||
for (Competitor competitor : competitors) {
|
||||
result.add(competitor);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public String createSortedText(Tree<Competitor> competitorTree) {
|
||||
AtomicInteger rank = new AtomicInteger(1);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
competitorTree.traversal().inorder(
|
||||
(competitor) -> {
|
||||
competitor.setRank(rank.getAndIncrement());
|
||||
sb.append(competitor);
|
||||
sb.append(System.lineSeparator());
|
||||
});
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public String execute(String rankingList) {
|
||||
Tree<Competitor> competitorTree = createTree(rankingList);
|
||||
return "Rangliste (Tree)\n" + createSortedText(competitorTree) + "\n\n" +
|
||||
"Height: " + competitorTree.height() + "\nSize: " + competitorTree.size();
|
||||
}
|
||||
}
|
95
app/src/main/java/ch/nuth/zhaw/exbox/RouteServer.java
Normal file
95
app/src/main/java/ch/nuth/zhaw/exbox/RouteServer.java
Normal file
|
@ -0,0 +1,95 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.PriorityQueue;
|
||||
import java.util.Queue;
|
||||
|
||||
public class RouteServer implements CommandExecutor {
|
||||
/**
|
||||
* build the graph given a text file with the topology
|
||||
*/
|
||||
public Graph<DijkstraNode, Edge> createGraph(String topo) throws Exception {
|
||||
// TODO implement
|
||||
Graph<DijkstraNode, Edge> graph = new AdjListGraph<>(DijkstraNode.class, Edge.class);
|
||||
|
||||
for (String line : topo.split("\r?\n")) {
|
||||
String[] attributes = line.split(" ");
|
||||
|
||||
try {
|
||||
for (int i = 0; i <= 1; i++) {
|
||||
graph.addEdge(attributes[i], attributes[1 - i], Double.parseDouble(attributes[2]));
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
throw new Exception(e);
|
||||
}
|
||||
}
|
||||
|
||||
return graph;
|
||||
}
|
||||
|
||||
/**
|
||||
* apply the dijkstra algorithm
|
||||
*/
|
||||
public void dijkstraRoute(Graph<DijkstraNode, Edge> graph, String from, String to) {
|
||||
Queue<DijkstraNode> pendingNodes = new PriorityQueue<>();
|
||||
DijkstraNode start = graph.findNode(from);
|
||||
DijkstraNode end = graph.findNode(to);
|
||||
start.setDist(0);
|
||||
pendingNodes.add(start);
|
||||
|
||||
while (!pendingNodes.isEmpty()) {
|
||||
DijkstraNode current = pendingNodes.poll();
|
||||
current.setMark(true);
|
||||
|
||||
if (current == end) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (Edge edge : current.getEdges()) {
|
||||
if (edge.getDest() instanceof DijkstraNode node &&
|
||||
!node.getMark()) {
|
||||
double dist = current.getDist() + edge.getWeight();
|
||||
|
||||
if (!pendingNodes.contains(node) ||
|
||||
dist < node.getDist()) {
|
||||
node.setDist(dist);
|
||||
node.setPrev(current);
|
||||
|
||||
if (pendingNodes.contains(node)) {
|
||||
pendingNodes.remove(node);
|
||||
}
|
||||
|
||||
pendingNodes.add(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* find the route in the graph after applied dijkstra
|
||||
* the route should be returned with the start town first
|
||||
*/
|
||||
public List<DijkstraNode> getRoute(Graph<DijkstraNode, Edge> graph, String to) {
|
||||
List<DijkstraNode> route = new LinkedList<>();
|
||||
DijkstraNode town = graph.findNode(to);
|
||||
do {
|
||||
route.add(0, town);
|
||||
town = town.getPrev();
|
||||
} while (town != null);
|
||||
return route;
|
||||
}
|
||||
|
||||
public String execute(String topo) throws Exception {
|
||||
Graph<DijkstraNode, Edge> graph = createGraph(topo);
|
||||
dijkstraRoute(graph, "Winterthur", "Lugano");
|
||||
List<DijkstraNode> route = getRoute(graph, "Lugano");
|
||||
// generate result string
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (DijkstraNode rt : route) {
|
||||
builder.append(rt).append("\n");
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
82
app/src/main/java/ch/nuth/zhaw/exbox/ServerFactory.java
Normal file
82
app/src/main/java/ch/nuth/zhaw/exbox/ServerFactory.java
Normal file
|
@ -0,0 +1,82 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
|
||||
/**
|
||||
* Classloader that handles file path of class
|
||||
*/
|
||||
class MyClassLoader extends ClassLoader {
|
||||
private String path;
|
||||
|
||||
MyClassLoader(ClassLoader parent) {
|
||||
super(parent);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param name filename of class
|
||||
* return content of file as array of bytes; if file does not exist
|
||||
* return null
|
||||
*/
|
||||
private byte[] getBytes(String name) {
|
||||
try {
|
||||
System.out.println(name);
|
||||
RandomAccessFile file = new RandomAccessFile(name, "r");
|
||||
byte[] data = new byte[(int) file.length()];
|
||||
file.readFully(data);
|
||||
file.close();
|
||||
return data;
|
||||
} catch (IOException e) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param name filename of class
|
||||
*/
|
||||
public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
|
||||
System.out.println("load:" + name + " " + resolve);
|
||||
Class<?> clazz;
|
||||
byte[] classData = getBytes(name);
|
||||
|
||||
if (classData != null) {
|
||||
clazz = defineClass(null, classData, 0, classData.length);
|
||||
|
||||
path = name.substring(0,
|
||||
name.length() - clazz.getName().length() - ".class".length());
|
||||
|
||||
return clazz;
|
||||
}
|
||||
if (!resolve) {
|
||||
classData = getBytes(
|
||||
path + name.replace(".", File.separator) + ".class");
|
||||
|
||||
if (classData != null) {
|
||||
return defineClass(null, classData, 0, classData.length);
|
||||
}
|
||||
}
|
||||
return findSystemClass(name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ServerFactory -- Praktikum Experimentierkasten --
|
||||
*
|
||||
* @author K. Rege
|
||||
* @version 1.0 -- Factory zur Erstellung von Server Objekten
|
||||
* @version 2.0 -- Dynamisches Nachladen
|
||||
* @version 2.01 -- Fix deprecated Functions
|
||||
*/
|
||||
public class ServerFactory {
|
||||
public static Class<?> loadClass(String name) throws Exception {
|
||||
MyClassLoader myClassLoader = new MyClassLoader(
|
||||
MyClassLoader.class.getClassLoader());
|
||||
|
||||
return myClassLoader.loadClass(name, true);
|
||||
}
|
||||
|
||||
public static CommandExecutor createServer(String name) throws Exception {
|
||||
return (CommandExecutor) loadClass(name).getConstructor(new Class[] {}).newInstance();
|
||||
}
|
||||
}
|
103
app/src/main/java/ch/nuth/zhaw/exbox/ServerGraphics.java
Normal file
103
app/src/main/java/ch/nuth/zhaw/exbox/ServerGraphics.java
Normal file
|
@ -0,0 +1,103 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.awt.Color;
|
||||
|
||||
public class ServerGraphics {
|
||||
|
||||
private StringBuffer b;
|
||||
private static ServerGraphics theGraphics;
|
||||
|
||||
public static ServerGraphics instance() {
|
||||
if (theGraphics == null) {
|
||||
theGraphics = new ServerGraphics();
|
||||
}
|
||||
return theGraphics;
|
||||
}
|
||||
|
||||
public ServerGraphics() {
|
||||
clear();
|
||||
theGraphics = this;
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
b = new StringBuffer();
|
||||
}
|
||||
|
||||
public String getTrace() {
|
||||
return new String(b);
|
||||
}
|
||||
|
||||
private double round(double d) {
|
||||
return Math.round(d * 10000) / 10000.0;
|
||||
}
|
||||
|
||||
public void drawLine(double x1, double y1, double x2, double y2) {
|
||||
b.append("<line x1=\"");
|
||||
b.append(round(x1));
|
||||
b.append("\" y1=\"");
|
||||
b.append(round(y1));
|
||||
b.append("\" x2=\"");
|
||||
b.append(round(x2));
|
||||
b.append("\" y2=\"");
|
||||
b.append(round(y2));
|
||||
b.append("\"/>\n");
|
||||
}
|
||||
|
||||
public void drawRect(double x, double y, double w, double h) {
|
||||
b.append("<rect x=\"");
|
||||
b.append(round(x));
|
||||
b.append("\" y=\"");
|
||||
b.append(round(y));
|
||||
b.append("\" ");
|
||||
b.append("width=\"");
|
||||
b.append(round(w));
|
||||
b.append("\" height=\"");
|
||||
b.append(round(h));
|
||||
b.append("\" style=\"draw\" />\n");
|
||||
}
|
||||
|
||||
public void fillRect(double x, double y, double w, double h) {
|
||||
b.append("<rect x=\"");
|
||||
b.append(round(x));
|
||||
b.append("\" y=\"");
|
||||
b.append(round(y));
|
||||
b.append("\" ");
|
||||
b.append("width=\"");
|
||||
b.append(round(w));
|
||||
b.append("\" height=\"");
|
||||
b.append(round(h));
|
||||
b.append("\" style=\"fill\" />\n");
|
||||
}
|
||||
|
||||
public void setColor(Color c) {
|
||||
b.append("<color red=\"");
|
||||
b.append(c.getRed());
|
||||
b.append("\" green=\"");
|
||||
b.append(c.getGreen());
|
||||
b.append("\" blue=\"");
|
||||
b.append(c.getBlue());
|
||||
b.append("\"/>\n");
|
||||
}
|
||||
|
||||
public void drawPath(String from, String to, boolean line) {
|
||||
double scale = 11;
|
||||
double xh0 = from.charAt(0) - '0';
|
||||
double yh0 = from.charAt(2) - '0';
|
||||
double xh1 = to.charAt(0) - '0';
|
||||
double yh1 = to.charAt(2) - '0';
|
||||
double x0 = Math.min(xh0, xh1) / scale;
|
||||
double y0 = Math.min(yh0, yh1) / scale;
|
||||
double x1 = Math.max(xh0, xh1) / scale;
|
||||
double y1 = Math.max(yh0, yh1) / scale;
|
||||
double w = 1 / scale;
|
||||
if (line) {
|
||||
drawLine(x0 + w / 2, y0 + w / 2, x1 + w / 2, y1 + w / 2);
|
||||
} else {
|
||||
if (Math.abs(y0 - y1) < 1E-10) {
|
||||
fillRect(x0, y0, x1 - x0 + w, w);
|
||||
} else {
|
||||
fillRect(x0, y0, w, y1 - y0 + w);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
39
app/src/main/java/ch/nuth/zhaw/exbox/SnowflakeServer.java
Normal file
39
app/src/main/java/ch/nuth/zhaw/exbox/SnowflakeServer.java
Normal file
|
@ -0,0 +1,39 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/**
|
||||
* Provides the functionality to draw a snowflake.
|
||||
*/
|
||||
public class SnowflakeServer implements CommandExecutor {
|
||||
@Override
|
||||
public String execute(String command) {
|
||||
int recursionLevel = Integer.parseInt(command);
|
||||
Turtle turtle = Turtle.instance();
|
||||
drawSnowflake(turtle, recursionLevel);
|
||||
return turtle.getTrace();
|
||||
}
|
||||
|
||||
public void drawSnowflake(Turtle turtle, int recursionLevel) {
|
||||
turtle.reset(0.1, 0.266);
|
||||
turtle.turn(60);
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
drawLine(turtle, recursionLevel, 0.8);
|
||||
turtle.turn(-120);
|
||||
}
|
||||
}
|
||||
|
||||
public void drawLine(Turtle turtle, int recursionLevel, double destination) {
|
||||
if (recursionLevel == 0) {
|
||||
turtle.move(destination);
|
||||
} else {
|
||||
double distance = destination / 3;
|
||||
|
||||
for (int i = 0; i < 3; i++) {
|
||||
drawLine(turtle, recursionLevel - 1, distance);
|
||||
turtle.turn(i % 2 == 0 ? 60 : -120);
|
||||
}
|
||||
|
||||
drawLine(turtle, recursionLevel - 1, distance);
|
||||
}
|
||||
}
|
||||
}
|
230
app/src/main/java/ch/nuth/zhaw/exbox/SortServer.java
Normal file
230
app/src/main/java/ch/nuth/zhaw/exbox/SortServer.java
Normal file
|
@ -0,0 +1,230 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class SortServer implements CommandExecutor {
|
||||
private final int DATARANGE = 10000000;
|
||||
public int dataElems; // number of data
|
||||
public int insertion_threshold = 50;
|
||||
|
||||
private void swap(int[] a, int i, int j) {
|
||||
int h = a[i];
|
||||
a[i] = a[j];
|
||||
a[j] = h;
|
||||
}
|
||||
|
||||
public void bubbleSort(int[] a) {
|
||||
for (int max = a.length - 1; max >= 0; max--) {
|
||||
boolean isSorted = true;
|
||||
|
||||
for (int i = 0; i < max; i++) {
|
||||
if (a[i] > a[i + 1]) {
|
||||
isSorted = false;
|
||||
swap(a, i, i + 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (isSorted) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void insertionSort(int[] a) {
|
||||
insertionSort(a, 0, a.length - 1);
|
||||
}
|
||||
|
||||
private void insertionSort(int[] a, int min, int max) {
|
||||
for (int k = min; k < max + 1; k++) {
|
||||
int item = a[k];
|
||||
int newIndex;
|
||||
|
||||
for (newIndex = k; newIndex > 0 && a[newIndex - 1] > item; newIndex--) {
|
||||
a[newIndex] = a[newIndex - 1];
|
||||
}
|
||||
|
||||
a[newIndex] = item;
|
||||
}
|
||||
}
|
||||
|
||||
public void selectionSort(int[] a) {
|
||||
// TODO Implement Aufgabe 3
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
int minIndex = i;
|
||||
|
||||
for (int j = i; j < a.length; j++) {
|
||||
if (a[j] < a[minIndex]) {
|
||||
minIndex = j;
|
||||
}
|
||||
}
|
||||
|
||||
if (i != minIndex) {
|
||||
swap(a, i, minIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void streamSort(int[] a) {
|
||||
// zum Vergleichen (falls Sie Zeit und Lust haben)
|
||||
int[] b = Arrays.stream(a).sorted().toArray();
|
||||
System.arraycopy(b, 0, a, 0, a.length);
|
||||
}
|
||||
|
||||
void quickerSort(int[] a){
|
||||
quickerSort(a, 0, a.length-1);
|
||||
}
|
||||
|
||||
private void quickerSort(int[] arr, int left, int right) {
|
||||
// To do Aufgabe 12.1
|
||||
if (right - left < insertion_threshold) {
|
||||
insertionSort(arr, left, right);
|
||||
} else {
|
||||
int l = partition(arr, left, right);
|
||||
quickerSort(arr, left, l - 1);
|
||||
quickerSort(arr, l, right);
|
||||
}
|
||||
}
|
||||
|
||||
private int partition (int[] arr, int left, int right) {
|
||||
// To do Aufgabe 12.1
|
||||
int pivot = arr[(left + right) / 2];
|
||||
|
||||
while (left <= right) {
|
||||
while (arr[left] < pivot) {
|
||||
left++;
|
||||
}
|
||||
|
||||
while (arr[right] > pivot) {
|
||||
right--;
|
||||
}
|
||||
|
||||
if (left <= right) {
|
||||
swap(arr, left, right);
|
||||
left++;
|
||||
right--;
|
||||
}
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
private boolean isSorted(int[] a) {
|
||||
for (int i = a.length - 2; i > 0; i--) {
|
||||
if (a[i] > a[i + 1]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public int[] randomData() {
|
||||
int[] a = new int[dataElems];
|
||||
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
a[i] = (int) (Math.random() * DATARANGE);
|
||||
}
|
||||
|
||||
return a;
|
||||
}
|
||||
|
||||
public int[] ascendingData() {
|
||||
int[] a = new int[dataElems];
|
||||
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
a[i] = i;
|
||||
}
|
||||
|
||||
return a;
|
||||
}
|
||||
|
||||
public int[] descendingData() {
|
||||
int[] a = new int[dataElems];
|
||||
|
||||
for (int i = 0; i < a.length; i++) {
|
||||
a[i] = a.length - i;
|
||||
}
|
||||
|
||||
return a;
|
||||
}
|
||||
|
||||
// measure time of sorting algorithm
|
||||
// generator to generate the data
|
||||
// consumer sorts the data
|
||||
// return elapsed time in ms
|
||||
// if data is not sorted an exception is thrown
|
||||
public double measureTime(Supplier<int[]> generator, Consumer<int[]> sorter) throws Exception {
|
||||
double elapsed = 0;
|
||||
|
||||
int[] a = generator.get();
|
||||
int[] b = new int[dataElems];
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
long endTime = startTime;
|
||||
|
||||
// TODO Implement Aufgabe 1 und 2 (Tipp: siehe Consumer für Aufruf von
|
||||
int count = 0;
|
||||
|
||||
while (endTime < startTime + 10000) {
|
||||
System.arraycopy(a, 0, b, 0, a.length);
|
||||
sorter.accept(b);
|
||||
count++;
|
||||
endTime = System.currentTimeMillis();
|
||||
}
|
||||
// Sortiermethode)
|
||||
|
||||
elapsed = (double) ((endTime - startTime) / count);
|
||||
|
||||
if (!isSorted(b)) {
|
||||
throw new Exception("ERROR not sorted");
|
||||
}
|
||||
|
||||
return elapsed;
|
||||
}
|
||||
|
||||
public String execute(String arg) {
|
||||
Map<String, Consumer<int[]>> sorter = Map.of(
|
||||
"BUBBLE", this::bubbleSort,
|
||||
"INSERTION", this::insertionSort,
|
||||
"SELECTION", this::selectionSort,
|
||||
"STREAM", this::streamSort,
|
||||
"QUICKERSORT", this::quickerSort);
|
||||
Map<String, Supplier<int[]>> generator = Map.of(
|
||||
"RANDOM", this::randomData,
|
||||
"ASC", this::ascendingData,
|
||||
"DESC", this::descendingData);
|
||||
|
||||
String[] args = arg.toUpperCase().split(" ");
|
||||
dataElems = Integer.parseInt(args[2]);
|
||||
|
||||
if (args.length >= 4) {
|
||||
insertion_threshold = Integer.parseInt(args[3]);
|
||||
}
|
||||
|
||||
try {
|
||||
double time = measureTime(generator.get(args[1]), sorter.get(args[0]));
|
||||
return arg + " " + time + " ms\n";
|
||||
} catch (Exception ex) {
|
||||
return arg + " " + ex.getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SortServer sorter = new SortServer();
|
||||
String sort;
|
||||
sort = "BUBBLE RANDOM 10000"; System.out.println(sorter.execute(sort));
|
||||
sort = "SELECTION RANDOM 10000"; System.out.println(sorter.execute(sort));
|
||||
sort = "INSERTION RANDOM 10000"; System.out.println(sorter.execute(sort));
|
||||
sort = "QUICKERSORT RANDOM 10000 100"; System.out.println(sorter.execute(sort));
|
||||
sort = "STREAM RANDOM 10000"; System.out.println(sorter.execute(sort));
|
||||
|
||||
sort = "BUBBLE ASC 10000"; System.out.println(sorter.execute(sort));
|
||||
sort = "SELECTION ASC 10000"; System.out.println(sorter.execute(sort));
|
||||
sort = "INSERTION ASC 10000"; System.out.println(sorter.execute(sort));
|
||||
sort = "QUICKERSORT ASC 10000 100"; System.out.println(sorter.execute(sort));
|
||||
sort = "STREAM ASC 10000"; System.out.println(sorter.execute(sort));
|
||||
}
|
||||
}
|
153
app/src/main/java/ch/nuth/zhaw/exbox/SortedBinaryTree.java
Normal file
153
app/src/main/java/ch/nuth/zhaw/exbox/SortedBinaryTree.java
Normal file
|
@ -0,0 +1,153 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class SortedBinaryTree<T extends Comparable<T>> implements Tree<T> {
|
||||
protected TreeNode<T> root;
|
||||
|
||||
private TreeNode<T> insertAt(TreeNode<T> node, T x) {
|
||||
if (node == null) {
|
||||
return new TreeNode<T>(x);
|
||||
} else {
|
||||
if (x.compareTo(node.getValue()) <= 0) {
|
||||
node.left = insertAt(node.left, x);
|
||||
} else {
|
||||
node.right = insertAt(node.right, x);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
public void add(T x) {
|
||||
root = insertAt(root, x);
|
||||
}
|
||||
|
||||
// find node to replace
|
||||
private TreeNode<T> findRepAt(TreeNode<T> node, TreeNode<T> rep) {
|
||||
if (node.right != null) {
|
||||
node.right = findRepAt(node.right, rep);
|
||||
} else {
|
||||
rep.values = node.values;
|
||||
node = node.left;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
// remove node
|
||||
private TreeNode<T> removeAt(TreeNode<T> node, T x, TreeNode<T> removed) {
|
||||
if (node == null) {
|
||||
return null;
|
||||
} else {
|
||||
if (x.compareTo(node.getValue()) == 0) {
|
||||
// found
|
||||
removed.values = node.values;
|
||||
if (node.left == null) {
|
||||
node = node.right;
|
||||
} else if (node.right == null) {
|
||||
node = node.left;
|
||||
} else {
|
||||
node.left = findRepAt(node.left, node);
|
||||
}
|
||||
} else if (x.compareTo(node.getValue()) < 0) {
|
||||
// search left
|
||||
node.left = removeAt(node.left, x, removed);
|
||||
} else {
|
||||
// search right
|
||||
node.right = removeAt(node.right, x, removed);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
}
|
||||
|
||||
public T remove(T x) {
|
||||
TreeNode<T> removed = new TreeNode<T>(null);
|
||||
root = removeAt(root, x, removed);
|
||||
return removed.getValue();
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return root == null;
|
||||
}
|
||||
|
||||
public Traversal<T> traversal() {
|
||||
return new TreeTraversal<>(root);
|
||||
}
|
||||
|
||||
protected int calcHeight(TreeNode<T> node) {
|
||||
if (node == null) {
|
||||
return 0;
|
||||
} else {
|
||||
int result = 1;
|
||||
|
||||
if (node.left != null || node.right != null) {
|
||||
result += Stream.of(node.left, node.right).filter(
|
||||
(innerNode) -> innerNode != null).mapToInt((innerNode) -> calcHeight(innerNode)).max()
|
||||
.getAsInt();
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public int height() {
|
||||
return calcHeight(root);
|
||||
}
|
||||
|
||||
protected int calcSize(TreeNode<T> p) {
|
||||
int result = 0;
|
||||
|
||||
if (p != null) {
|
||||
result++;
|
||||
|
||||
if (p.left != null) {
|
||||
result += calcSize(p.left);
|
||||
}
|
||||
|
||||
if (p.right != null) {
|
||||
result += calcSize(p.right);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return calcSize(root);
|
||||
}
|
||||
|
||||
public boolean balanced() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// only for testing and debugging: show the structure of the tree
|
||||
public String printTree() {
|
||||
StringBuilder out = new StringBuilder();
|
||||
if (root.right != null) {
|
||||
printTree(root.right, out, true, "");
|
||||
}
|
||||
out.append(root.values).append("\n");
|
||||
if (root.left != null) {
|
||||
printTree(root.left, out, false, "");
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private void printTree(TreeNode<T> node, StringBuilder out, boolean isRight, String indent) {
|
||||
if (node.right != null) {
|
||||
printTree(node.right, out, true,
|
||||
indent + (isRight ? " " : " | "));
|
||||
}
|
||||
out.append(indent);
|
||||
if (isRight) {
|
||||
out.append(" /");
|
||||
} else {
|
||||
out.append(" \\");
|
||||
}
|
||||
out.append("----- ");
|
||||
out.append(node.values).append("\n");
|
||||
if (node.left != null) {
|
||||
printTree(node.left, out, false,
|
||||
indent + (isRight ? " | " : " "));
|
||||
}
|
||||
}
|
||||
}
|
49
app/src/main/java/ch/nuth/zhaw/exbox/Stack.java
Normal file
49
app/src/main/java/ch/nuth/zhaw/exbox/Stack.java
Normal file
|
@ -0,0 +1,49 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/**
|
||||
* Interface für Abstrakten Datentyp (ADT) Stack
|
||||
*/
|
||||
public interface Stack {
|
||||
/**
|
||||
* Legt eine neues Objekt auf den Stack, falls noch nicht voll.
|
||||
*
|
||||
* @param x ist das Objekt, das dazugelegt wird.
|
||||
*/
|
||||
void push(Object x) throws StackOverflowError;
|
||||
|
||||
/**
|
||||
* Entfernt das oberste und damit das zuletzt eingefügte Objekt.
|
||||
* Ist der Stack leer, wird null zurückgegeben.
|
||||
*
|
||||
* @return Gibt das oberste Objekt zurück oder null, falls leer.
|
||||
*/
|
||||
Object pop();
|
||||
|
||||
/**
|
||||
* Testet, ob der Stack leer ist.
|
||||
*
|
||||
* @return Gibt true zurück, falls der Stack leer ist.
|
||||
*/
|
||||
boolean isEmpty();
|
||||
|
||||
/**
|
||||
* Gibt das oberste Objekt zurück, ohne es zu entfernen.
|
||||
* Ist der Stack leer, wird null zurückgegeben.
|
||||
*
|
||||
* @return Gibt das oberste Objekt zurück oder null, falls leer.
|
||||
*/
|
||||
Object peek();
|
||||
|
||||
/**
|
||||
* Entfernt alle Objekte vom Stack. Ein Aufruf von isEmpty()
|
||||
* ergibt nachher mit Sicherheit true.
|
||||
*/
|
||||
void removeAll();
|
||||
|
||||
/**
|
||||
* Testet, ob der Stack voll ist.
|
||||
*
|
||||
* @return Gibt true zurück, falls der Stack voll ist.
|
||||
*/
|
||||
boolean isFull();
|
||||
}
|
188
app/src/main/java/ch/nuth/zhaw/exbox/Storage.java
Normal file
188
app/src/main/java/ch/nuth/zhaw/exbox/Storage.java
Normal file
|
@ -0,0 +1,188 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public class Storage {
|
||||
public static boolean generationalGCActive = true; // in Aufgabe 2 verwendet
|
||||
public static StringBuffer log = new StringBuffer();
|
||||
private static List<Collectable> root;
|
||||
private static List<Collectable> youngHeap;
|
||||
private static List<Collectable> oldHeap;
|
||||
public static boolean youngGenerationOnly = true;
|
||||
|
||||
static {
|
||||
clear();
|
||||
}
|
||||
|
||||
public static void clear() {
|
||||
root = new LinkedList<>();
|
||||
youngHeap = new LinkedList<>();
|
||||
// oldHeap erst in Aufgabe 2 verwenden!
|
||||
oldHeap = new LinkedList<>();
|
||||
}
|
||||
|
||||
/* add root object */
|
||||
public static void addRoot(Collectable obj) {
|
||||
root.add(obj);
|
||||
}
|
||||
|
||||
// create a collectable object of class cls
|
||||
public static Collectable _new(String cls, Object arg) {
|
||||
Collectable obj = null;
|
||||
try {
|
||||
// create an object and call constructor
|
||||
Constructor<?> cst = Class.forName(getPackage() + cls).getConstructor(arg.getClass());
|
||||
obj = (Collectable) cst.newInstance(new Object[] { arg });
|
||||
// add object to heap
|
||||
youngHeap.add(obj);
|
||||
log.append("New: ").append(obj).append("\n");
|
||||
} catch (Exception ex) {
|
||||
log.append("error creating object ").append(cls).append("\n");
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
private static String getPackage() {
|
||||
Package pack = Storage.class.getPackage();
|
||||
if (pack != null && !pack.getName().equals("")) {
|
||||
return pack.getName() + ".";
|
||||
} else {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/* remove object from heap */
|
||||
public static void delete(Collectable obj) {
|
||||
if (youngHeap.remove(obj)) {
|
||||
if (generationalGCActive) {
|
||||
log.append("Delete young heap: ").append(obj).append("\n");
|
||||
} else {
|
||||
log.append("Delete heap: ").append(obj).append("\n");
|
||||
}
|
||||
} else if (oldHeap.remove(obj)) {
|
||||
log.append("Delete old heap: ").append(obj).append("\n");
|
||||
} else {
|
||||
log.append("error trying to delete not existing object ").append(obj).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
/* get all root objects */
|
||||
public static Iterable<Collectable> getRoot() {
|
||||
return new LinkedList<>(root);
|
||||
}
|
||||
|
||||
/* get young heap */
|
||||
public static Iterable<Collectable> getYoungHeap() {
|
||||
return new LinkedList<>(youngHeap);
|
||||
}
|
||||
|
||||
/* get old heap */
|
||||
public static Iterable<Collectable> getOldHeap() {
|
||||
return new LinkedList<>(oldHeap);
|
||||
}
|
||||
|
||||
/* get heap */
|
||||
public static Iterable<Collectable> getHeap() {
|
||||
return new LinkedList<>(youngHeap);
|
||||
}
|
||||
|
||||
/* get references to collectables of an object */
|
||||
public static Iterable<Collectable> getRefs(Collectable obj) {
|
||||
// get all fields of an object
|
||||
List<Collectable> fieldList = new LinkedList<>();
|
||||
for (Field field : obj.getClass().getFields()) {
|
||||
try {
|
||||
Object o = field.get(obj);
|
||||
if (o instanceof Collectable) {
|
||||
fieldList.add((Collectable) o);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
}
|
||||
}
|
||||
return fieldList;
|
||||
}
|
||||
|
||||
/* dump an iterator */
|
||||
public static void dump(String s, Iterable<Collectable> itr) {
|
||||
log.append(s);
|
||||
for (Collectable o : itr) {
|
||||
log.append(" ").append(o);
|
||||
}
|
||||
log.append("\n");
|
||||
}
|
||||
|
||||
public static String getLog() {
|
||||
return log.toString();
|
||||
}
|
||||
|
||||
private static void mark(Collectable cObject) {
|
||||
// TODO Aufgabe 13.1
|
||||
if (!cObject.isMarked()) {
|
||||
cObject.setMark(true);
|
||||
|
||||
for (Collectable item : getRefs(cObject)) {
|
||||
mark(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void sweep() {
|
||||
// TODO Aufgabe 13.1 und Aufgabe 13.2
|
||||
Map<Iterable<Collectable>, Consumer<Collectable>> heaps = new HashMap<>();
|
||||
Consumer<Collectable> noOp = (item) -> {};
|
||||
|
||||
Consumer<Collectable> copy = (item) -> {
|
||||
youngHeap.remove(item);
|
||||
oldHeap.add(item);
|
||||
};
|
||||
|
||||
heaps.put(getYoungHeap(), generationalGCActive ? copy : noOp);
|
||||
|
||||
if (!youngGenerationOnly) {
|
||||
heaps.put(getOldHeap(), noOp);
|
||||
}
|
||||
|
||||
for (Map.Entry<Iterable<Collectable>, Consumer<Collectable>> entry : heaps.entrySet()) {
|
||||
for (Collectable item : entry.getKey()) {
|
||||
if (!item.isMarked()) {
|
||||
delete(item);
|
||||
} else {
|
||||
item.setMark(false);
|
||||
entry.getValue().accept(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void gc() {
|
||||
if (generationalGCActive) {
|
||||
if (youngGenerationOnly) {
|
||||
log.append("\nCollector start young generation only\n");
|
||||
} else {
|
||||
log.append("\nCollector start young and old generation\n");
|
||||
}
|
||||
} else {
|
||||
log.append("\nCollector start\n");
|
||||
}
|
||||
|
||||
// TODO Aufgabe 13.1 und Aufgabe 13.2
|
||||
for (Collectable item : getRoot()) {
|
||||
mark(item);
|
||||
}
|
||||
|
||||
sweep();
|
||||
|
||||
if (generationalGCActive) {
|
||||
youngGenerationOnly = !youngGenerationOnly;
|
||||
}
|
||||
|
||||
log.append("Collector end\n");
|
||||
}
|
||||
}
|
66
app/src/main/java/ch/nuth/zhaw/exbox/TestCObjectServer.java
Normal file
66
app/src/main/java/ch/nuth/zhaw/exbox/TestCObjectServer.java
Normal file
|
@ -0,0 +1,66 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
public class TestCObjectServer implements CommandExecutor {
|
||||
private static CObject new_CObject(Object s) {
|
||||
return (CObject) Storage._new("CObject", s);
|
||||
}
|
||||
|
||||
static CObject a;
|
||||
static CObject e;
|
||||
|
||||
public String execute (String input) {
|
||||
run();
|
||||
return Storage.getLog();
|
||||
}
|
||||
|
||||
private void run() {
|
||||
a = new_CObject("A");
|
||||
CObject b = new_CObject("B");
|
||||
CObject c = new_CObject("C");
|
||||
CObject d = new_CObject("D");
|
||||
e = new_CObject("E");
|
||||
CObject f = new_CObject("F");
|
||||
CObject g = new_CObject("G");
|
||||
Storage.addRoot(a);
|
||||
Storage.addRoot(e);
|
||||
a.next = b; b.next = c; b.down = a; c.down = d;
|
||||
e.next = f; f.next = g; g.next = e;
|
||||
Storage.dump("\nRoots:", Storage.getRoot());
|
||||
if (Storage.generationalGCActive) {
|
||||
Storage.dump("\nYoung heap 1:", Storage.getYoungHeap());
|
||||
Storage.dump("Old heap 1:", Storage.getOldHeap());
|
||||
} else {
|
||||
Storage.dump("Heap 1:", Storage.getYoungHeap());
|
||||
}
|
||||
Storage.gc();
|
||||
if (Storage.generationalGCActive) {
|
||||
Storage.dump("Young heap 2:", Storage.getYoungHeap());
|
||||
Storage.dump("Old heap 2:", Storage.getOldHeap());
|
||||
} else {
|
||||
Storage.dump("Heap 2:", Storage.getYoungHeap());
|
||||
}
|
||||
b.next = f;
|
||||
Storage.gc();
|
||||
if (Storage.generationalGCActive) {
|
||||
Storage.dump("Young heap 3:", Storage.getYoungHeap());
|
||||
Storage.dump("Old heap 3:", Storage.getOldHeap());
|
||||
} else {
|
||||
Storage.dump("Heap 3:", Storage.getYoungHeap());
|
||||
}
|
||||
f.next = null;
|
||||
Storage.gc();
|
||||
if (Storage.generationalGCActive) {
|
||||
Storage.dump("Young heap 4:", Storage.getYoungHeap());
|
||||
Storage.dump("Old heap 4:", Storage.getOldHeap());
|
||||
} else {
|
||||
Storage.dump("Heap 4:", Storage.getYoungHeap());
|
||||
}
|
||||
Storage.gc();
|
||||
if (Storage.generationalGCActive) {
|
||||
Storage.dump("Young heap 5:", Storage.getYoungHeap());
|
||||
Storage.dump("Old heap 5:", Storage.getOldHeap());
|
||||
} else {
|
||||
Storage.dump("Heap 5:", Storage.getYoungHeap());
|
||||
}
|
||||
}
|
||||
}
|
17
app/src/main/java/ch/nuth/zhaw/exbox/TestGraphicServer.java
Normal file
17
app/src/main/java/ch/nuth/zhaw/exbox/TestGraphicServer.java
Normal file
|
@ -0,0 +1,17 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
public class TestGraphicServer implements CommandExecutor {
|
||||
String figure = "<line x1=\"0.1\" y1 = \"0.8\" x2=\"0.9\" y2 = \"0.8\" />\n" +
|
||||
"<line x1=\"0.2\" y1 = \"0.4\" x2=\"0.2\" y2 = \"0.8\" />\n" +
|
||||
"<line x1=\"0.3\" y1 = \"0.4\" x2=\"0.3\" y2 = \"0.8\" />\n" +
|
||||
"<line x1=\"0.3\" y1 = \"0.4\" x2=\"0.7\" y2 = \"0.4\" />\n" +
|
||||
"<line x1=\"0.3\" y1 = \"0.6\" x2=\"0.4\" y2 = \"0.6\" />\n" +
|
||||
"<line x1=\"0.5\" y1 = \"0.8\" x2=\"0.5\" y2 = \"0.6\" />\n" +
|
||||
"<line x1=\"0.5\" y1 = \"0.6\" x2=\"0.7\" y2 = \"0.6\" />\n" +
|
||||
"<line x1=\"0.7\" y1 = \"0.6\" x2=\"0.7\" y2 = \"0.4\" />\n" +
|
||||
"<line x1=\"0.8\" y1 = \"0.4\" x2=\"0.8\" y2 = \"0.8\" />\n";
|
||||
|
||||
public String execute(String command) {
|
||||
return figure;
|
||||
}
|
||||
}
|
15
app/src/main/java/ch/nuth/zhaw/exbox/Traversal.java
Normal file
15
app/src/main/java/ch/nuth/zhaw/exbox/Traversal.java
Normal file
|
@ -0,0 +1,15 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/** interface of Traversal ADT */
|
||||
public interface Traversal<T> {
|
||||
/** traverse elements of tree in preorder */
|
||||
void preorder(Visitor<T> vistor);
|
||||
/** traverse elements of tree in inorder */
|
||||
void inorder(Visitor<T> vistor);
|
||||
/** traverse elements of tree in postorder */
|
||||
void postorder(Visitor<T> vistor);
|
||||
/** traverse elements of tree in levelorder */
|
||||
void levelorder(Visitor<T> vistor);
|
||||
/** traverse elements of tree interval */
|
||||
void interval(T min, T max, Visitor<T> vistor);
|
||||
}
|
25
app/src/main/java/ch/nuth/zhaw/exbox/Tree.java
Normal file
25
app/src/main/java/ch/nuth/zhaw/exbox/Tree.java
Normal file
|
@ -0,0 +1,25 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/** interface of Tree ADT */
|
||||
public interface Tree<T extends Comparable<T>> {
|
||||
/** add an element to the tree */
|
||||
void add(T o);
|
||||
|
||||
/** remove an element; returns the element if found else return null */
|
||||
T remove(T o);
|
||||
|
||||
/** test if tree is empty */
|
||||
boolean isEmpty();
|
||||
|
||||
/** returns instance of class that implements traversal interface */
|
||||
Traversal<T> traversal();
|
||||
|
||||
/** number of elements */
|
||||
int size();
|
||||
|
||||
/** height of the tree */
|
||||
int height();
|
||||
|
||||
/** is the tree balanced */
|
||||
boolean balanced();
|
||||
}
|
22
app/src/main/java/ch/nuth/zhaw/exbox/TreeNode.java
Normal file
22
app/src/main/java/ch/nuth/zhaw/exbox/TreeNode.java
Normal file
|
@ -0,0 +1,22 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
class TreeNode<T extends Comparable<T>> {
|
||||
List<T> values; // implemented as list because of doublette handling in AVL
|
||||
TreeNode<T> left, right;
|
||||
int height; // for AVL
|
||||
|
||||
TreeNode(T value){
|
||||
this.values = new LinkedList<>();
|
||||
this.values.add(value);
|
||||
this.height = 1;
|
||||
}
|
||||
|
||||
TreeNode(T value, TreeNode<T> left, TreeNode<T> right){
|
||||
this(value); this.left = left; this.right = right;
|
||||
}
|
||||
|
||||
T getValue(){return values.get(0);}
|
||||
}
|
93
app/src/main/java/ch/nuth/zhaw/exbox/TreeTraversal.java
Normal file
93
app/src/main/java/ch/nuth/zhaw/exbox/TreeTraversal.java
Normal file
|
@ -0,0 +1,93 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.Deque;
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class TreeTraversal<T extends Comparable<T>> implements Traversal<T> {
|
||||
private final TreeNode<T> root;
|
||||
|
||||
public TreeTraversal(TreeNode<T> root) {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
public void inorder(Visitor<T> vis) {
|
||||
if (root.left != null) {
|
||||
new TreeTraversal<>(root.left).inorder(vis);
|
||||
}
|
||||
|
||||
vis.visit(root.getValue());
|
||||
|
||||
if (root.right != null) {
|
||||
new TreeTraversal<>(root.right).inorder(vis);
|
||||
}
|
||||
}
|
||||
|
||||
public void preorder(Visitor<T> vis) {
|
||||
vis.visit(root.getValue());
|
||||
|
||||
if (root.left != null) {
|
||||
new TreeTraversal<>(root.left).preorder(vis);
|
||||
}
|
||||
|
||||
if (root.right != null) {
|
||||
new TreeTraversal<>(root.right).preorder(vis);
|
||||
}
|
||||
}
|
||||
|
||||
public void postorder(Visitor<T> vis) {
|
||||
if (root.left != null) {
|
||||
new TreeTraversal<>(root.left).postorder(vis);
|
||||
}
|
||||
|
||||
if (root.right != null) {
|
||||
new TreeTraversal<>(root.right).postorder(vis);
|
||||
}
|
||||
|
||||
vis.visit(root.getValue());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void levelorder(Visitor<T> vistor) {
|
||||
Deque<TreeNode<T>> queue = new LinkedList<>();
|
||||
queue.add(root);
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
TreeNode<T> node = queue.pop();
|
||||
|
||||
if (node.left != null) {
|
||||
queue.add(node.left);
|
||||
}
|
||||
|
||||
if (node.right != null) {
|
||||
queue.add(node.right);
|
||||
}
|
||||
|
||||
vistor.visit(node.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void interval(T min, T max, Visitor<T> visitor) {
|
||||
Deque<TreeNode<T>> queue = new LinkedList<>();
|
||||
queue.add(root);
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
TreeNode<T> node = queue.pop();
|
||||
|
||||
if (node != null) {
|
||||
T value = node.getValue();
|
||||
|
||||
if (value.compareTo(min) >= 0 && value.compareTo(max) <= 0) {
|
||||
visitor.visit(value);
|
||||
queue.add(node.left);
|
||||
queue.add(node.right);
|
||||
} else if (value.compareTo(max) > 0) {
|
||||
queue.add(node.left);
|
||||
}
|
||||
else if (value.compareTo(min) < 0) {
|
||||
queue.add(node.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
63
app/src/main/java/ch/nuth/zhaw/exbox/Turtle.java
Normal file
63
app/src/main/java/ch/nuth/zhaw/exbox/Turtle.java
Normal file
|
@ -0,0 +1,63 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
public class Turtle {
|
||||
private static StringBuffer b;
|
||||
private static double x, y;
|
||||
private static double angle;
|
||||
private static Turtle theTurtle;
|
||||
|
||||
public static Turtle instance() {
|
||||
if (theTurtle == null) {
|
||||
theTurtle = new Turtle();
|
||||
}
|
||||
|
||||
return theTurtle;
|
||||
}
|
||||
|
||||
public Turtle() {
|
||||
this(0, 0);
|
||||
}
|
||||
|
||||
public Turtle(double x, double y) {
|
||||
reset(x, y);
|
||||
theTurtle = this;
|
||||
}
|
||||
|
||||
public void reset(double x, double y) {
|
||||
b = new StringBuffer();
|
||||
Turtle.x = x;
|
||||
Turtle.y = y;
|
||||
angle = 0;
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
reset(0, 0);
|
||||
}
|
||||
|
||||
public String getTrace() {
|
||||
return b.toString();
|
||||
}
|
||||
|
||||
private double round(double d) {
|
||||
return Math.round(d * 10000) / 10000.0;
|
||||
}
|
||||
|
||||
public void move(double dist) {
|
||||
b.append("<line x1=\"");
|
||||
b.append(Double.toString(round(x)));
|
||||
b.append("\" y1=\"");
|
||||
b.append(Double.toString(round(y)));
|
||||
b.append("\" ");
|
||||
x += Math.cos(angle) * dist;
|
||||
y += Math.sin(angle) * dist;
|
||||
b.append("x2=\"");
|
||||
b.append(Double.toString(round(x)));
|
||||
b.append("\" y2=\"");
|
||||
b.append(Double.toString(round(y)));
|
||||
b.append("\"/>\n");
|
||||
}
|
||||
|
||||
public void turn(double turnAngle) {
|
||||
angle += turnAngle * Math.PI / 180;
|
||||
}
|
||||
}
|
7
app/src/main/java/ch/nuth/zhaw/exbox/Visitor.java
Normal file
7
app/src/main/java/ch/nuth/zhaw/exbox/Visitor.java
Normal file
|
@ -0,0 +1,7 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
/** interface of visitor ADT */
|
||||
public interface Visitor<T> {
|
||||
/** called for each element in the tree */
|
||||
void visit(T obj);
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import java.util.regex.MatchResult;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class WellformedXmlServer implements CommandExecutor {
|
||||
Pattern tagPattern = Pattern.compile("<(/?)(\\w+)( \\w+=\"[^\"]*\")*>");
|
||||
|
||||
@Override
|
||||
public String execute(String command) throws Exception {
|
||||
return Boolean.toString(checkWellformed(command)) + "\n";
|
||||
}
|
||||
|
||||
public boolean checkWellformed(String code) {
|
||||
ListStack openTags = new ListStack();
|
||||
Iterable<MatchResult> results = () -> tagPattern.matcher(code).results().iterator();
|
||||
|
||||
for (MatchResult result : results) {
|
||||
if (result.group(1).length() == 0) {
|
||||
openTags.push(result.group(2));
|
||||
} else if (result.group(2).equals(openTags.peek())) {
|
||||
openTags.pop();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return openTags.isEmpty();
|
||||
}
|
||||
}
|
68
app/src/test/java/ch/nuth/zhaw/exbox/ADS10_3_test.java
Normal file
68
app/src/test/java/ch/nuth/zhaw/exbox/ADS10_3_test.java
Normal file
|
@ -0,0 +1,68 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS10_3_test {
|
||||
@BeforeEach
|
||||
void init() {
|
||||
FuzzySearchServer.names.clear();
|
||||
FuzzySearchServer.trigrams.clear();
|
||||
String rangliste = "Mueller Stefan;02:31:14\n" +
|
||||
"Marti Adrian;02:30:09\n" +
|
||||
"Kiptum Daniel;02:11:31\n" +
|
||||
"Ancay Tarcis;02:20:02\n" +
|
||||
"Kreibuhl Christian;02:21:47\n" +
|
||||
"Ott Michael;02:33:48\n" +
|
||||
"Menzi Christoph;02:27:26\n" +
|
||||
"Oliver Ruben;02:32:12\n" +
|
||||
"Elmer Beat;02:33:53\n" +
|
||||
"Kuehni Martin;02:33:36\n";
|
||||
FuzzySearchServer.loadNames(rangliste);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLoadNames() {
|
||||
assertEquals(10, FuzzySearchServer.names.size(), "Länge von 'names' Liste");
|
||||
assertEquals("Mueller Stefan", FuzzySearchServer.names.get(0), "Erster Name");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTrigramForName() {
|
||||
List<String> trigList = FuzzySearchServer.trigramForName("Heinz");
|
||||
assertEquals(5, trigList.size(), "Länge von Trigram Liste");
|
||||
String[] good = {" he", "hei", "ein", "inz", "nz "};
|
||||
for (int i = 0; i < good.length; i++) {
|
||||
assertEquals(good[i], trigList.get(i), "trigram [" + i + "]");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAddToTrigrams() {
|
||||
FuzzySearchServer.addToTrigrams(0, "mue");
|
||||
FuzzySearchServer.addToTrigrams(0, "uel");
|
||||
FuzzySearchServer.addToTrigrams(1, "mar");
|
||||
assertEquals(3, FuzzySearchServer.trigrams.size(), "Länge von 'trigram'");
|
||||
assertEquals(0, FuzzySearchServer.trigrams.get("mue").get(0), "mue");
|
||||
assertEquals(0, FuzzySearchServer.trigrams.get("uel").get(0), "uel");
|
||||
assertEquals(1, FuzzySearchServer.trigrams.get("mar").get(0), "mar");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFind() {
|
||||
FuzzySearchServer.constructTrigramIndex(FuzzySearchServer.names);
|
||||
assertEquals("Kiptum Daniel", FuzzySearchServer.find("Kiptum Daniel", 80));
|
||||
assertEquals("Kiptum Daniel", FuzzySearchServer.find("Daniel Kiptum", 80));
|
||||
assertEquals("Kiptum Daniel", FuzzySearchServer.find("Kip Dan", 30));
|
||||
assertEquals("Kiptum Daniel", FuzzySearchServer.find("Dan Kip", 30));
|
||||
}
|
||||
}
|
72
app/src/test/java/ch/nuth/zhaw/exbox/ADS11_2_test.java
Normal file
72
app/src/test/java/ch/nuth/zhaw/exbox/ADS11_2_test.java
Normal file
|
@ -0,0 +1,72 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS11_2_test {
|
||||
final int DATAELEMS = 10000;
|
||||
SortServer sortServer = new SortServer();
|
||||
|
||||
@Test
|
||||
public void testRandomData() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
int[] data = sortServer.randomData();
|
||||
assertEquals(sortServer.dataElems, data.length, "Anzahl Daten");
|
||||
assertTrue(data[0] != data[1], "Distribution");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAscendingData() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
int[] data = sortServer.ascendingData();
|
||||
assertEquals(sortServer.dataElems, data.length, "Anzahl Daten");
|
||||
for (int i = 0; i< sortServer.dataElems-1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "Distribution");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDescendingData() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
int[] data = sortServer.descendingData();
|
||||
assertEquals(sortServer.dataElems, data.length, "Anzahl Daten");
|
||||
for (int i = 0; i< sortServer.dataElems-1; i++) {
|
||||
assertTrue(data[i] >= data[i + 1], "Distribution");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBubbleSort() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
int[] data = sortServer.randomData();
|
||||
sortServer.bubbleSort(data);
|
||||
for (int i = 0; i< sortServer.dataElems-1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "Sorted");
|
||||
}
|
||||
}
|
||||
|
||||
private double testQuadratic(String msg, Consumer<int[]> sorter) throws Exception {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
double time1 = sortServer.measureTime(sortServer::randomData, sorter);
|
||||
|
||||
sortServer.dataElems = DATAELEMS*2;
|
||||
double time2 = sortServer.measureTime(sortServer::randomData, sorter);
|
||||
|
||||
assertTrue(time1 > time2 / 6 && time1 < time2 / 2, msg + " Time O(n^2)");
|
||||
return time1;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMeasureTime() throws Exception {
|
||||
testQuadratic("BUBBLESORT", sortServer::bubbleSort);
|
||||
}
|
||||
}
|
94
app/src/test/java/ch/nuth/zhaw/exbox/ADS11_3_test.java
Normal file
94
app/src/test/java/ch/nuth/zhaw/exbox/ADS11_3_test.java
Normal file
|
@ -0,0 +1,94 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.function.Consumer;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS11_3_test {
|
||||
final int DATAELEMS = 10000;
|
||||
SortServer sortServer = new SortServer();
|
||||
|
||||
@Test
|
||||
public void testRandomData() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
int[] data = sortServer.randomData();
|
||||
assertEquals(sortServer.dataElems, data.length, "Anzahl Daten");
|
||||
assertTrue(data[0] != data[1], "Distribution");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAscendingData() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
int[] data = sortServer.ascendingData();
|
||||
assertEquals(sortServer.dataElems, data.length, "Anzahl Daten");
|
||||
for (int i = 0; i< sortServer.dataElems-1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "Distribution");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDescendingData() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
int[] data = sortServer.descendingData();
|
||||
assertEquals(sortServer.dataElems, data.length, "Anzahl Daten");
|
||||
for (int i = 0; i< sortServer.dataElems-1; i++) {
|
||||
assertTrue(data[i] >= data[i + 1], "Distribution");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBubbleSort() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
int[] data = sortServer.randomData();
|
||||
sortServer.bubbleSort(data);
|
||||
for (int i = 0; i< sortServer.dataElems-1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "Sorted");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInsertionSort() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
int[] data = sortServer.randomData();
|
||||
sortServer.insertionSort(data);
|
||||
for (int i = 0; i< sortServer.dataElems-1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "Sorted");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSelectionSort() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
int[] data = sortServer.randomData();
|
||||
sortServer.selectionSort(data);
|
||||
for (int i = 0; i< sortServer.dataElems-1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "Sorted");
|
||||
}
|
||||
}
|
||||
|
||||
private double testQuadratic(String msg, Consumer<int[]> sorter) throws Exception {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
double time1 = sortServer.measureTime(sortServer::randomData, sorter);
|
||||
|
||||
sortServer.dataElems = DATAELEMS*2;
|
||||
double time2 = sortServer.measureTime(sortServer::randomData, sorter);
|
||||
|
||||
assertTrue(time1 > time2 / 6 && time1 < time2 / 2, msg + " Time O(n^2)");
|
||||
return time1;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMeasureTime() throws Exception {
|
||||
double time1 = testQuadratic("BUBBLESORT", sortServer::bubbleSort);
|
||||
double time2 = testQuadratic("SELECTIONSORT", sortServer::selectionSort);
|
||||
double time3 = testQuadratic("INSERTIONSORT", sortServer::insertionSort);
|
||||
assertTrue(time1 > 1.5 * time2, "BubbleTime > 1.5 * SelectionTime");
|
||||
assertTrue(time2 > 1.5 * time3, "SelectionTime > 1.5 * InsertionTime");
|
||||
}
|
||||
}
|
64
app/src/test/java/ch/nuth/zhaw/exbox/ADS12_1_test.java
Normal file
64
app/src/test/java/ch/nuth/zhaw/exbox/ADS12_1_test.java
Normal file
|
@ -0,0 +1,64 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class ADS12_1_test {
|
||||
SortServer sortServer = new SortServer();
|
||||
final int DATAELEMS = 10000;
|
||||
|
||||
@Test
|
||||
public void testRandomData() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
sortServer.insertion_threshold = 50;
|
||||
int[] data = sortServer.randomData();
|
||||
sortServer.quickerSort(data);
|
||||
for (int i = 0; i< sortServer.dataElems - 1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "Random Data");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAscendingData() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
sortServer.insertion_threshold = 50;
|
||||
int[] data = sortServer.ascendingData();
|
||||
sortServer.quickerSort(data);
|
||||
for (int i = 0; i< sortServer.dataElems - 1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "ASC Data");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDecendingData() {
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
sortServer.insertion_threshold = 50;
|
||||
int[] data = sortServer.descendingData();
|
||||
sortServer.quickerSort(data);
|
||||
for (int i = 0; i< sortServer.dataElems - 1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "DESC Data");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCompleteData() {
|
||||
boolean found;
|
||||
sortServer.dataElems = DATAELEMS;
|
||||
sortServer.insertion_threshold = 50;
|
||||
int[] data = sortServer.randomData();
|
||||
int[] original = new int[data.length];
|
||||
System.arraycopy(data, 0, original, 0, data.length);
|
||||
sortServer.quickerSort(data);
|
||||
for (int i = 0; i <= sortServer.dataElems - 1; i++) {
|
||||
found = false;
|
||||
for (int j = 0; j <= sortServer.dataElems - 1; j++) {
|
||||
if (data[i] == original[j]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertTrue(found, "Data not found after sort");
|
||||
}
|
||||
}
|
||||
}
|
88
app/src/test/java/ch/nuth/zhaw/exbox/ADS12_3_test.java
Normal file
88
app/src/test/java/ch/nuth/zhaw/exbox/ADS12_3_test.java
Normal file
|
@ -0,0 +1,88 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class ADS12_3_test {
|
||||
ParallelQuickerSortServer sortServer = new ParallelQuickerSortServer();
|
||||
final int DATAELEMS = 10000;
|
||||
|
||||
@Test
|
||||
public void testRandomData() {
|
||||
ParallelQuickerSortServer.dataElems = DATAELEMS;
|
||||
ParallelQuickerSortServer.insertion_threshold = 50;
|
||||
int[] data = sortServer.randomData();
|
||||
Thread rootThread = new ParallelQuickerSortServer(data, 0, data.length - 1);
|
||||
rootThread.start();
|
||||
try {
|
||||
rootThread.join();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
for (int i = 0; i< ParallelQuickerSortServer.dataElems - 1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "Sorted");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAscendingData() {
|
||||
ParallelQuickerSortServer.dataElems = DATAELEMS;
|
||||
ParallelQuickerSortServer.insertion_threshold = 50;
|
||||
int[] data = sortServer.ascendingData();
|
||||
Thread rootThread = new ParallelQuickerSortServer(data, 0, data.length - 1);
|
||||
rootThread.start();
|
||||
try {
|
||||
rootThread.join();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
for (int i = 0; i< ParallelQuickerSortServer.dataElems - 1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "Sorted");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDescendingData() {
|
||||
ParallelQuickerSortServer.dataElems = DATAELEMS;
|
||||
ParallelQuickerSortServer.insertion_threshold = 50;
|
||||
int[] data = sortServer.descendingData();
|
||||
Thread rootThread = new ParallelQuickerSortServer(data, 0, data.length - 1);
|
||||
rootThread.start();
|
||||
try {
|
||||
rootThread.join();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
for (int i = 0; i< ParallelQuickerSortServer.dataElems - 1; i++) {
|
||||
assertTrue(data[i] <= data[i + 1], "Sorted");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCompleteData() {
|
||||
boolean found;
|
||||
ParallelQuickerSortServer.dataElems = DATAELEMS;
|
||||
ParallelQuickerSortServer.insertion_threshold = 50;
|
||||
int[] data = sortServer.ascendingData();
|
||||
int[] original = new int[data.length];
|
||||
System.arraycopy(data, 0, original, 0, data.length);
|
||||
Thread rootThread = new ParallelQuickerSortServer(data, 0, data.length - 1);
|
||||
rootThread.start();
|
||||
try {
|
||||
rootThread.join();
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
for (int i = 0; i <= ParallelQuickerSortServer.dataElems - 1; i++) {
|
||||
found = false;
|
||||
for (int j = 0; j <= ParallelQuickerSortServer.dataElems - 1; j++) {
|
||||
if (data[i] == original[j]) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertTrue(found, "Data not found after sort");
|
||||
}
|
||||
}
|
||||
}
|
92
app/src/test/java/ch/nuth/zhaw/exbox/ADS13_1_test.java
Normal file
92
app/src/test/java/ch/nuth/zhaw/exbox/ADS13_1_test.java
Normal file
|
@ -0,0 +1,92 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS13_1_test {
|
||||
private CObject new_CObject(Object s) {
|
||||
return (CObject) Storage._new("CObject", s);
|
||||
}
|
||||
|
||||
static CObject a, d;
|
||||
CObject b, c, e, f, g;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
Storage.generationalGCActive = false;
|
||||
Storage.clear();
|
||||
newObjects();
|
||||
}
|
||||
|
||||
private void testContent(String message, Iterable<Collectable> content, String expected) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
content.forEach(b::append);
|
||||
assertEquals(expected, b.toString(), message);
|
||||
}
|
||||
|
||||
private void newObjects() {
|
||||
a = new_CObject("A");
|
||||
b = new_CObject("B");
|
||||
c = new_CObject("C");
|
||||
d = new_CObject("D");
|
||||
e = new_CObject("E");
|
||||
f = new_CObject("F");
|
||||
g = new_CObject("G");
|
||||
Storage.addRoot(a);
|
||||
Storage.addRoot(d);
|
||||
a.next = b;
|
||||
b.next = c;
|
||||
b.down = a;
|
||||
c.down = d;
|
||||
d.next = e;
|
||||
e.next = f;
|
||||
f.next = g;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRoot() {
|
||||
testContent("ROOT", Storage.getRoot(), "AD");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitialHeap() {
|
||||
testContent("HEAP1", Storage.getHeap(), "ABCDEFG");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAfterFirstGC() {
|
||||
Storage.gc();
|
||||
testContent("HEAP2", Storage.getHeap(), "ABCDEFG");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAfterFirstChangeGC() {
|
||||
Storage.gc();
|
||||
e.next = d;
|
||||
Storage.gc();
|
||||
testContent("HEAP3", Storage.getHeap(), "ABCDE");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAfterSecondChangeGC() {
|
||||
Storage.gc();
|
||||
e.next = d;
|
||||
Storage.gc();
|
||||
a.next = null;
|
||||
Storage.gc();
|
||||
testContent("HEAP4", Storage.getHeap(), "ADE");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFinalHeap() {
|
||||
Storage.gc();
|
||||
e.next = d;
|
||||
Storage.gc();
|
||||
a.next = null;
|
||||
Storage.gc();
|
||||
Storage.gc();
|
||||
testContent("HEAP5", Storage.getHeap(), "ADE");
|
||||
}
|
||||
}
|
130
app/src/test/java/ch/nuth/zhaw/exbox/ADS13_3_test.java
Normal file
130
app/src/test/java/ch/nuth/zhaw/exbox/ADS13_3_test.java
Normal file
|
@ -0,0 +1,130 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS13_3_test {
|
||||
private CObject new_CObject(Object s) {
|
||||
return (CObject) Storage._new("CObject", s);
|
||||
}
|
||||
|
||||
static CObject a, d;
|
||||
CObject b, c, e, f, g, h;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
Storage.generationalGCActive = true;
|
||||
Storage.youngGenerationOnly = true;
|
||||
Storage.clear();
|
||||
newObjects();
|
||||
}
|
||||
|
||||
private void testContent(String message, Iterable<Collectable> content, String expected) {
|
||||
StringBuilder b = new StringBuilder();
|
||||
content.forEach(b::append);
|
||||
assertEquals(expected, b.toString(), message);
|
||||
}
|
||||
|
||||
private void newObjects() {
|
||||
a = new_CObject("A");
|
||||
b = new_CObject("B");
|
||||
c = new_CObject("C");
|
||||
d = new_CObject("D");
|
||||
e = new_CObject("E");
|
||||
f = new_CObject("F");
|
||||
g = new_CObject("G");
|
||||
Storage.addRoot(a);
|
||||
Storage.addRoot(d);
|
||||
a.next = b;
|
||||
b.next = c;
|
||||
b.down = a;
|
||||
c.down = d;
|
||||
d.next = e;
|
||||
e.next = f;
|
||||
f.next = g;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRoot() {
|
||||
testContent("ROOT", Storage.getRoot(), "AD");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInitialHeap() {
|
||||
testContent("YOUNG HEAP1", Storage.getYoungHeap(), "ABCDEFG");
|
||||
testContent("OLD HEAP1", Storage.getOldHeap(), ""); }
|
||||
|
||||
@Test
|
||||
public void testAfterFirstGC() {
|
||||
Storage.gc();
|
||||
Storage.getYoungHeap();
|
||||
Storage.getOldHeap();
|
||||
testContent("YOUNG HEAP2", Storage.getYoungHeap(), "");
|
||||
testContent("OLD HEAP2", Storage.getOldHeap(), "ABCDEFG");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAfterFirstChangeGC() {
|
||||
Storage.gc();
|
||||
e.next = d;
|
||||
Storage.gc();
|
||||
testContent("YOUNG HEAP3", Storage.getYoungHeap(), "");
|
||||
testContent("OLD HEAP3", Storage.getOldHeap(), "ABCDE");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAfterSecondChangeGC() {
|
||||
Storage.gc();
|
||||
e.next = d;
|
||||
Storage.gc();
|
||||
a.next = null;
|
||||
Storage.gc();
|
||||
testContent("YOUNG HEAP4", Storage.getYoungHeap(), "");
|
||||
testContent("OLD HEAP4", Storage.getOldHeap(), "ABCDE");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAfterSecondCallGC() {
|
||||
Storage.gc();
|
||||
e.next = d;
|
||||
Storage.gc();
|
||||
a.next = null;
|
||||
Storage.gc();
|
||||
Storage.gc();
|
||||
testContent("YOUNG HEAP5", Storage.getYoungHeap(), "");
|
||||
testContent("OLD HEAP5", Storage.getOldHeap(), "ADE");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAfterAddObjecthGC() {
|
||||
Storage.gc();
|
||||
e.next = d;
|
||||
Storage.gc();
|
||||
a.next = null;
|
||||
Storage.gc();
|
||||
Storage.gc();
|
||||
h = new_CObject("H");
|
||||
a.next = h;
|
||||
testContent("YOUNG HEAP5", Storage.getYoungHeap(), "H");
|
||||
testContent("OLD HEAP5", Storage.getOldHeap(), "ADE");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFinalHeap() {
|
||||
Storage.gc();
|
||||
e.next = d;
|
||||
Storage.gc();
|
||||
a.next = null;
|
||||
Storage.gc();
|
||||
Storage.gc();
|
||||
h = new_CObject("H");
|
||||
a.next = h;
|
||||
testContent("YOUNG HEAP5", Storage.getYoungHeap(), "H");
|
||||
testContent("OLD HEAP5", Storage.getOldHeap(), "ADE");
|
||||
Storage.gc();
|
||||
testContent("YOUNG HEAP5", Storage.getYoungHeap(), "");
|
||||
testContent("OLD HEAP5", Storage.getOldHeap(), "ADEH");
|
||||
}
|
||||
}
|
23
app/src/test/java/ch/nuth/zhaw/exbox/ADS1_1_test.java
Normal file
23
app/src/test/java/ch/nuth/zhaw/exbox/ADS1_1_test.java
Normal file
|
@ -0,0 +1,23 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS1_1_test {
|
||||
LCMServer server;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
server = new LCMServer();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testKgv() {
|
||||
assertEquals(12, server.leastCommonMultiple(3, 4), "kgv von 3 4");
|
||||
assertEquals(4, server.leastCommonMultiple(2, 4), "kgv von 2 4");
|
||||
assertEquals(35, server.leastCommonMultiple(5, 7), "kgv von 5 7");
|
||||
assertEquals(12, server.leastCommonMultiple(4, 6), "kgv von 4 6");
|
||||
}
|
||||
}
|
52
app/src/test/java/ch/nuth/zhaw/exbox/ADS1_2_test.java
Normal file
52
app/src/test/java/ch/nuth/zhaw/exbox/ADS1_2_test.java
Normal file
|
@ -0,0 +1,52 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
public class ADS1_2_test {
|
||||
ListStack stack;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
stack = new ListStack();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPush1() {
|
||||
stack.push("A");
|
||||
Object o = stack.pop();
|
||||
assertEquals("A", o);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPush2() {
|
||||
stack.push("A");
|
||||
stack.push("B");
|
||||
assertEquals("B", stack.pop());
|
||||
assertEquals("A", stack.pop());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsEmpty() {
|
||||
assertTrue(stack.isEmpty());
|
||||
stack.push("A");
|
||||
assertFalse(stack.isEmpty());
|
||||
stack.pop();
|
||||
assertTrue(stack.isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testIsFull() {
|
||||
assertFalse(stack.isFull());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEmptyPop() {
|
||||
assertNull(stack.pop());
|
||||
}
|
||||
}
|
36
app/src/test/java/ch/nuth/zhaw/exbox/ADS1_3_test.java
Normal file
36
app/src/test/java/ch/nuth/zhaw/exbox/ADS1_3_test.java
Normal file
|
@ -0,0 +1,36 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS1_3_test {
|
||||
BracketServer bs;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
bs = new BracketServer();
|
||||
}
|
||||
|
||||
private void test(String content, boolean expected) {
|
||||
assertEquals(expected, bs.checkBrackets(content), content);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBracket() {
|
||||
test("()", true);
|
||||
test("(()]", false);
|
||||
test("((([([])])))", true);
|
||||
test("[(])", false);
|
||||
test("[(3 +3)* 35 +3]* {3 +2}", true);
|
||||
test("[({3 +3)* 35} +3]* {3 +2}", false);
|
||||
test("(", false);
|
||||
test(")", false);
|
||||
test("<(<>)>", true);
|
||||
test("<(<)>>", false);
|
||||
test("/* hallo */", true);
|
||||
test("/*/* */", false);
|
||||
test("/*", false);
|
||||
}
|
||||
}
|
34
app/src/test/java/ch/nuth/zhaw/exbox/ADS1_4_test.java
Normal file
34
app/src/test/java/ch/nuth/zhaw/exbox/ADS1_4_test.java
Normal file
|
@ -0,0 +1,34 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS1_4_test {
|
||||
WellformedXmlServer xml;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
xml = new WellformedXmlServer();
|
||||
}
|
||||
|
||||
private void test(String content, boolean expected) {
|
||||
assertEquals(expected, xml.checkWellformed(content), content);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testXmlAttributes() {
|
||||
test("<a href=\"sugus\"></a>", true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testXml() {
|
||||
test("<a></a>", true);
|
||||
test("<a>", false);
|
||||
test("</a>", false);
|
||||
test("<a/>", true);
|
||||
test("<a><b></b></a>", true);
|
||||
test("<a><b></a></b>", false);
|
||||
}
|
||||
}
|
103
app/src/test/java/ch/nuth/zhaw/exbox/ADS2_3_test.java
Normal file
103
app/src/test/java/ch/nuth/zhaw/exbox/ADS2_3_test.java
Normal file
|
@ -0,0 +1,103 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* @(#)ListTest.java
|
||||
*
|
||||
*
|
||||
* @author
|
||||
* @version 1.00 2017/8/30
|
||||
*/
|
||||
public class ADS2_3_test {
|
||||
MyList list;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
list = new MyList();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd() {
|
||||
list.clear();
|
||||
list.add("A");
|
||||
assertEquals("A", list.get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd2() {
|
||||
list.clear();
|
||||
list.add("A");
|
||||
list.add("B");
|
||||
assertEquals("A", list.get(0));
|
||||
assertEquals("B", list.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd3() {
|
||||
list.clear();
|
||||
list.add("A");
|
||||
list.add("B");
|
||||
list.add("C");
|
||||
assertEquals("A", list.get(0));
|
||||
assertEquals("B", list.get(1));
|
||||
assertEquals("C", list.get(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSize() {
|
||||
list.clear();
|
||||
assertEquals(0, list.size());
|
||||
testAdd2();
|
||||
assertEquals(2, list.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove() {
|
||||
list.clear();
|
||||
list.add("A");
|
||||
list.remove("A");
|
||||
assertEquals(0, list.size());
|
||||
list.add("A");
|
||||
list.remove("B");
|
||||
assertEquals(1, list.size());
|
||||
list.remove("A");
|
||||
assertEquals(0, list.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMixed() {
|
||||
list.clear();
|
||||
List<Character> list2 = new LinkedList<>();
|
||||
|
||||
for (int i = 0; i < 100; i++) {
|
||||
Character c = (char) ('A' + (Math.random() * 26));
|
||||
int op = (int) (Math.random() * 2);
|
||||
|
||||
switch (op) {
|
||||
case 0:
|
||||
list.add(c);
|
||||
list2.add(c);
|
||||
break;
|
||||
case 1:
|
||||
list.remove(c);
|
||||
list2.remove(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
assertEquals(list2.size(), list.size());
|
||||
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
char c1 = (char) list.get(i);
|
||||
char c2 = (char) list2.get(i);
|
||||
assertEquals(c1, c2);
|
||||
}
|
||||
}
|
||||
}
|
84
app/src/test/java/ch/nuth/zhaw/exbox/ADS2_4_test.java
Normal file
84
app/src/test/java/ch/nuth/zhaw/exbox/ADS2_4_test.java
Normal file
|
@ -0,0 +1,84 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* @(#)ListTest.java
|
||||
*
|
||||
*
|
||||
* @author
|
||||
* @version 1.00 2017/8/30
|
||||
*/
|
||||
public class ADS2_4_test {
|
||||
MySortedList list;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
list = new MySortedList();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd() {
|
||||
list.clear();
|
||||
list.add("A");
|
||||
Object o = list.get(0);
|
||||
assertEquals("A", o);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd2() {
|
||||
list.clear();
|
||||
list.add("B");
|
||||
list.add("A");
|
||||
assertEquals("A", list.get(0));
|
||||
assertEquals("B", list.get(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd3() {
|
||||
list.clear();
|
||||
list.add("C");
|
||||
list.add("B");
|
||||
list.add("A");
|
||||
assertEquals("A", list.get(0));
|
||||
assertEquals("B", list.get(1));
|
||||
assertEquals("C", list.get(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMixed() {
|
||||
List<Character> list2 = new LinkedList<>();
|
||||
|
||||
for (int i = 0; i < 100; i++) {
|
||||
Character c = (char) ('A' + (Math.random() * 26));
|
||||
int op = (int) (Math.random() * 2);
|
||||
|
||||
switch (op) {
|
||||
case 0:
|
||||
list.add(c);
|
||||
list2.add(c);
|
||||
break;
|
||||
case 1:
|
||||
list.remove(c);
|
||||
list2.remove(c);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Collections.sort(list2);
|
||||
assertEquals(list2.size(), list.size());
|
||||
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
char c1 = (char) list.get(i);
|
||||
char c2 = (char) list2.get(i);
|
||||
assertEquals(c1, c2);
|
||||
}
|
||||
}
|
||||
}
|
34
app/src/test/java/ch/nuth/zhaw/exbox/ADS3_1_test.java
Normal file
34
app/src/test/java/ch/nuth/zhaw/exbox/ADS3_1_test.java
Normal file
|
@ -0,0 +1,34 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
public class ADS3_1_test {
|
||||
Competitor c1, c2, c3, c4;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
c1 = new Competitor(0, "Mueller Stefan", "02:31:14");
|
||||
c2 = new Competitor(0, "Marti Adrian", "02:30:09");
|
||||
c3 = new Competitor(0, "Kiptum Daniel", "02:11:31");
|
||||
c4 = new Competitor(0, "Speedy Gonzales", "1:11:31");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEquals() {
|
||||
assertTrue(c3.equals(c3), c3.getTime() + " == " + c3.getTime());
|
||||
assertTrue(!c3.equals(c2), c3.getTime() + " != " + c2.getTime());
|
||||
assertTrue(!c3.equals(null), "equals(null)");
|
||||
assertTrue(!c3.equals(new Object()), "equals(new Object())");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCompare() {
|
||||
assertTrue(c1.compareTo(c2) > 0, c1.getName() + " " + c1.getTime() + " > " + c2.getTime());
|
||||
assertTrue(c2.compareTo(c1) < 0, c2.getName() + " " + c2.getTime() + " < " + c1.getTime());
|
||||
assertTrue(c3.compareTo(c3) == 0, c3.getName() + " " + c3.getTime() + " == " + c3.getTime());
|
||||
assertTrue(c4.compareTo(c2) < 0, c4.getName() + " " + c4.getTime() + " < " + c2.getTime());
|
||||
}
|
||||
}
|
51
app/src/test/java/ch/nuth/zhaw/exbox/ADS3_2_test.java
Normal file
51
app/src/test/java/ch/nuth/zhaw/exbox/ADS3_2_test.java
Normal file
|
@ -0,0 +1,51 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS3_2_test {
|
||||
List<Competitor> rankGood;
|
||||
List<Competitor> rankTest;
|
||||
|
||||
public List<Competitor> createList(String rankingText) {
|
||||
List<Competitor> competitorList = new LinkedList<>();
|
||||
String[] lines = rankingText.split("\n");
|
||||
for (String line : lines) {
|
||||
String name = line.split(";")[0];
|
||||
String time = line.split(";")[1];
|
||||
competitorList.add(new Competitor(0, name, time));
|
||||
}
|
||||
return competitorList;
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
String rangliste = "Mueller Stefan;02:31:14\n" +
|
||||
"Marti Adrian;02:30:09\n" +
|
||||
"Kiptum Daniel;02:11:31\n" +
|
||||
"Ancay Tarcis;02:20:02\n" +
|
||||
"Kreibuhl Christian;02:21:47\n" +
|
||||
"Ott Michael;02:33:48\n" +
|
||||
"Menzi Christoph;02:27:26\n" +
|
||||
"Oliver Ruben;02:32:12\n" +
|
||||
"Elmer Beat;02:33:53\n" +
|
||||
"Kuehni Martin;02:33:36\n";
|
||||
|
||||
rankGood = createList(rangliste);
|
||||
rankTest = new RankingListServer().createList(rangliste);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateList() {
|
||||
assertEquals(rankGood.size(), rankTest.size(), "length");
|
||||
|
||||
for (int i = 0; i < rankGood.size(); i++) {
|
||||
assertEquals(rankGood.get(i).toString(), rankTest.get(i).toString(), "rangliste[" + i + "]");
|
||||
}
|
||||
}
|
||||
}
|
77
app/src/test/java/ch/nuth/zhaw/exbox/ADS3_3_test.java
Normal file
77
app/src/test/java/ch/nuth/zhaw/exbox/ADS3_3_test.java
Normal file
|
@ -0,0 +1,77 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS3_3_test {
|
||||
List<Competitor> rankGood;
|
||||
List<Competitor> rankTest;
|
||||
String textGood;
|
||||
String textTest;
|
||||
|
||||
public List<Competitor> createList(String rankingText) {
|
||||
List<Competitor> competitorList = new LinkedList<>();
|
||||
String[] lines = rankingText.split("\n");
|
||||
|
||||
for (String line : lines) {
|
||||
String name = line.split(";")[0];
|
||||
String time = line.split(";")[1];
|
||||
competitorList.add(new Competitor(0, name, time));
|
||||
}
|
||||
|
||||
return competitorList;
|
||||
}
|
||||
|
||||
public String createSortedText(List<Competitor> competitorList) {
|
||||
Collections.sort(competitorList);
|
||||
int rank = 1;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for (Competitor c : competitorList) {
|
||||
c.setRank(rank++);
|
||||
sb.append(c).append("\n");
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
String rangliste = "Mueller Stefan;02:31:14\n" +
|
||||
"Marti Adrian;02:30:09\n" +
|
||||
"Kiptum Daniel;02:11:31\n" +
|
||||
"Ancay Tarcis;02:20:02\n" +
|
||||
"Kreibuhl Christian;02:21:47\n" +
|
||||
"Ott Michael;02:33:48\n" +
|
||||
"Menzi Christoph;02:27:26\n" +
|
||||
"Oliver Ruben;02:32:12\n" +
|
||||
"Elmer Beat;02:33:53\n" +
|
||||
"Kuehni Martin;02:33:36\n";
|
||||
|
||||
rankGood = createList(rangliste);
|
||||
textGood = createSortedText(rankGood);
|
||||
rankTest = new RankingListServer().createList(rangliste);
|
||||
textTest = new RankingListServer().createSortedText(rankTest);
|
||||
}
|
||||
|
||||
private String clean(String s) {
|
||||
return s.trim();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateText() {
|
||||
String[] good = textGood.split("\n");
|
||||
String[] test = textTest.split("\n");
|
||||
assertEquals(good.length, test.length, "length");
|
||||
|
||||
for (int i = 0; i < good.length; i++) {
|
||||
assertEquals(clean(good[i]), clean(test[i]), "rangliste[" + i + "]");
|
||||
}
|
||||
}
|
||||
}
|
84
app/src/test/java/ch/nuth/zhaw/exbox/ADS3_4_test.java
Normal file
84
app/src/test/java/ch/nuth/zhaw/exbox/ADS3_4_test.java
Normal file
|
@ -0,0 +1,84 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS3_4_test {
|
||||
List<Competitor> rankGood;
|
||||
List<Competitor> rankTest;
|
||||
String textGood;
|
||||
String textTest;
|
||||
|
||||
public List<Competitor> createList(String rankingText) {
|
||||
List<Competitor> competitorList = new LinkedList<>();
|
||||
String[] lines = rankingText.split("\n");
|
||||
|
||||
for (String line : lines) {
|
||||
String name = line.split(";")[0];
|
||||
String time = line.split(";")[1];
|
||||
competitorList.add(new Competitor(0, name, time));
|
||||
}
|
||||
|
||||
return competitorList;
|
||||
}
|
||||
|
||||
public String createSortedText(List<Competitor> competitorList) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
for (Competitor c : competitorList) {
|
||||
sb.append(c).append("\n");
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
String ranglisteOrdered = "Ancay Tarcis;02:20:02\n" +
|
||||
"Elmer Beat;02:33:53\n" +
|
||||
"Kiptum Daniel;02:11:31\n" +
|
||||
"Kreibuhl Christian;02:21:47\n" +
|
||||
"Kuehni Martin;02:33:36\n" +
|
||||
"Marti Adrian;02:30:09\n" +
|
||||
"Menzi Christoph;02:27:26\n" +
|
||||
"Mueller Stefan;02:31:14\n" +
|
||||
"Oliver Ruben;02:32:12\n" +
|
||||
"Ott Michael;02:33:48\n";
|
||||
|
||||
String ranglisteUnordered = "Mueller Stefan;02:31:14\n" +
|
||||
"Marti Adrian;02:30:09\n" +
|
||||
"Kiptum Daniel;02:11:31\n" +
|
||||
"Ancay Tarcis;02:20:02\n" +
|
||||
"Kreibuhl Christian;02:21:47\n" +
|
||||
"Ott Michael;02:33:48\n" +
|
||||
"Menzi Christoph;02:27:26\n" +
|
||||
"Oliver Ruben;02:32:12\n" +
|
||||
"Elmer Beat;02:33:53\n" +
|
||||
"Kuehni Martin;02:33:36\n";
|
||||
|
||||
rankGood = createList(ranglisteOrdered);
|
||||
textGood = createSortedText(rankGood);
|
||||
rankTest = createList(ranglisteUnordered);
|
||||
textTest = new RankingListServer().createNameList(rankTest);
|
||||
}
|
||||
|
||||
private String clean(String s) {
|
||||
return s.trim();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateText() {
|
||||
String[] good = textGood.split("\n");
|
||||
String[] test = textTest.split("\n");
|
||||
assertEquals(good.length, test.length, "length");
|
||||
|
||||
for (int i = 0; i < good.length; i++) {
|
||||
assertEquals(clean(good[i]), clean(test[i]), "rangliste[" + i + "]");
|
||||
}
|
||||
}
|
||||
}
|
101
app/src/test/java/ch/nuth/zhaw/exbox/ADS4_1_test.java
Normal file
101
app/src/test/java/ch/nuth/zhaw/exbox/ADS4_1_test.java
Normal file
|
@ -0,0 +1,101 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS4_1_test {
|
||||
SnowflakeServer sf;
|
||||
Turtle turtle;
|
||||
final double EPS = 1;
|
||||
|
||||
double angle(double x1, double y1, double x2, double y2,
|
||||
double x3, double y3, double x4, double y4) {
|
||||
double ax, ay, bx, by;
|
||||
// https://www.frustfrei-lernen.de/mathematik/schnittwinkel-zweier-geraden.html
|
||||
ax = x2 - x1;
|
||||
ay = y2 - y1;
|
||||
bx = x4 - x3;
|
||||
by = y4 - y3;
|
||||
|
||||
double a = Math.acos(
|
||||
(ax * bx + ay * by)
|
||||
/ (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by)));
|
||||
|
||||
return a / Math.PI * 180;
|
||||
}
|
||||
|
||||
double angle(String line1, String line2) {
|
||||
StringTokenizer tok = new StringTokenizer(line1, " <>=/,\"\n");
|
||||
tok.nextToken(); // line
|
||||
tok.nextToken();
|
||||
double x1 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double y1 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double x2 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double y2 = Double.parseDouble(tok.nextToken());
|
||||
tok = new StringTokenizer(line2, " <>=/,\"\n");
|
||||
tok.nextToken(); // line
|
||||
tok.nextToken();
|
||||
double x3 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double y3 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double x4 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double y4 = Double.parseDouble(tok.nextToken());
|
||||
return angle(x1, y1, x2, y2, x3, y3, x4, y4);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
sf = new SnowflakeServer();
|
||||
turtle = new Turtle();
|
||||
}
|
||||
|
||||
void snowflake(int stufe, double dist) {
|
||||
if (stufe == 0) {
|
||||
turtle.move(dist);
|
||||
} else {
|
||||
stufe--;
|
||||
dist = dist / 3;
|
||||
snowflake(stufe, dist);
|
||||
turtle.turn(60);
|
||||
snowflake(stufe, dist);
|
||||
turtle.turn(-120);
|
||||
snowflake(stufe, dist);
|
||||
turtle.turn(60);
|
||||
snowflake(stufe, dist);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCountEdges() {
|
||||
turtle.clear();
|
||||
snowflake(3, 0.7);
|
||||
String[] linesGood = Turtle.instance().getTrace().split("\n");
|
||||
turtle.clear();
|
||||
sf.execute("3");
|
||||
String[] lines = Turtle.instance().getTrace().split("\n");
|
||||
assertEquals(linesGood.length * 3, lines.length, "Count Edges");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAngles() {
|
||||
turtle.clear();
|
||||
snowflake(3, 0.7);
|
||||
String[] linesGood = Turtle.instance().getTrace().split("\n");
|
||||
turtle.clear();
|
||||
sf.execute("3");
|
||||
String[] lines = Turtle.instance().getTrace().split("\n");
|
||||
|
||||
for (int i = 0; i < linesGood.length - 1; i++) {
|
||||
assertEquals(angle(linesGood[i], linesGood[i + 1]), angle(lines[i], lines[i + 1]), EPS, "Angle " + i);
|
||||
}
|
||||
}
|
||||
}
|
101
app/src/test/java/ch/nuth/zhaw/exbox/ADS4_2_test.java
Normal file
101
app/src/test/java/ch/nuth/zhaw/exbox/ADS4_2_test.java
Normal file
|
@ -0,0 +1,101 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS4_2_test {
|
||||
HilbertServer hlb;
|
||||
Turtle turtle;
|
||||
final double EPS = 1E-1;
|
||||
|
||||
double angle(double x1, double y1, double x2, double y2,
|
||||
double x3, double y3, double x4, double y4) {
|
||||
double ax, ay, bx, by;
|
||||
// https://www.frustfrei-lernen.de/mathematik/schnittwinkel-zweier-geraden.html
|
||||
ax = x2 - x1;
|
||||
ay = y2 - y1;
|
||||
bx = x4 - x3;
|
||||
by = y4 - y3;
|
||||
|
||||
double a = Math.acos(
|
||||
(ax * bx + ay * by)
|
||||
/ (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by)));
|
||||
|
||||
return a / Math.PI * 180;
|
||||
}
|
||||
|
||||
double angle(String line1, String line2) {
|
||||
StringTokenizer tok = new StringTokenizer(line1, " <>=/,\"\n");
|
||||
tok.nextToken(); // line
|
||||
tok.nextToken();
|
||||
double x1 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double y1 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double x2 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double y2 = Double.parseDouble(tok.nextToken());
|
||||
tok = new StringTokenizer(line2, " <>=/,\"\n");
|
||||
tok.nextToken(); // line
|
||||
tok.nextToken();
|
||||
double x3 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double y3 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double x4 = Double.parseDouble(tok.nextToken());
|
||||
tok.nextToken();
|
||||
double y4 = Double.parseDouble(tok.nextToken());
|
||||
return angle(x1, y1, x2, y2, x3, y3, x4, y4);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
hlb = new HilbertServer();
|
||||
turtle = new Turtle();
|
||||
}
|
||||
|
||||
private void hilbert(int depth, double dist, double angle) {
|
||||
if (depth >= 0) {
|
||||
turtle.turn(-angle);
|
||||
hilbert(depth - 1, dist, -angle);
|
||||
turtle.move(dist);
|
||||
turtle.turn(angle);
|
||||
hilbert(depth - 1, dist, angle);
|
||||
turtle.move(dist);
|
||||
hilbert(depth - 1, dist, angle);
|
||||
turtle.turn(angle);
|
||||
turtle.move(dist);
|
||||
hilbert(depth - 1, dist, -angle);
|
||||
turtle.turn(-angle);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCountEdges() {
|
||||
turtle.clear();
|
||||
hilbert(3, .4, -90);
|
||||
String[] linesGood = Turtle.instance().getTrace().split("\n");
|
||||
turtle.clear();
|
||||
hlb.execute("3");
|
||||
String[] lines = Turtle.instance().getTrace().split("\n");
|
||||
assertEquals(linesGood.length, lines.length, "Count Edges");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAngles() {
|
||||
turtle.clear();
|
||||
hilbert(3, .4, -90);
|
||||
String[] linesGood = Turtle.instance().getTrace().split("\n");
|
||||
turtle.clear();
|
||||
hlb.execute("3");
|
||||
String[] lines = Turtle.instance().getTrace().split("\n");
|
||||
|
||||
for (int i = 0; i < linesGood.length - 1; i++) {
|
||||
assertEquals(angle(linesGood[i], linesGood[i + 1]), angle(lines[i], lines[i + 1]), EPS, "Angle " + i);
|
||||
}
|
||||
}
|
||||
}
|
84
app/src/test/java/ch/nuth/zhaw/exbox/ADS5_2_test.java
Normal file
84
app/src/test/java/ch/nuth/zhaw/exbox/ADS5_2_test.java
Normal file
|
@ -0,0 +1,84 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* @(#)TreeTest.java
|
||||
*
|
||||
*
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS5_2_test {
|
||||
Tree<String> tree;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
tree = new SortedBinaryTree<>();
|
||||
tree.add("B");
|
||||
tree.add("A");
|
||||
tree.add("C");
|
||||
tree.add("D");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInorder() {
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().inorder(v);
|
||||
assertEquals("ABCD", v.toString(), "inorder");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPreorder() {
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().preorder(v);
|
||||
assertEquals("BACD", v.toString(), "preorder");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostorder() {
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().postorder(v);
|
||||
assertEquals("ADCB", v.toString(), "postorder");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLevelorder() {
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().levelorder(v);
|
||||
assertEquals("BACD", v.toString(), "levelorder");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMixed() {
|
||||
Tree<String> tree = new SortedBinaryTree<>();
|
||||
List<String> list = new LinkedList<>();
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
char c = (char) ('A' + (Math.random() * 26));
|
||||
int op = (int) (Math.random() * 2);
|
||||
switch (op) {
|
||||
case 0:
|
||||
list.add(Character.toString(c));
|
||||
tree.add(Character.toString(c));
|
||||
break;
|
||||
case 1:
|
||||
list.remove(Character.toString(c));
|
||||
tree.remove(Character.toString(c));
|
||||
break;
|
||||
}
|
||||
}
|
||||
Collections.sort(list);
|
||||
String expected = String.join("", list);
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().inorder(v);
|
||||
assertEquals(expected, v.toString(), "mixed");
|
||||
}
|
||||
}
|
61
app/src/test/java/ch/nuth/zhaw/exbox/ADS5_3_test.java
Normal file
61
app/src/test/java/ch/nuth/zhaw/exbox/ADS5_3_test.java
Normal file
|
@ -0,0 +1,61 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS5_3_test {
|
||||
Tree<Competitor> rankGood;
|
||||
Tree<Competitor> rankTest;
|
||||
String textGood;
|
||||
String textTest;
|
||||
|
||||
public Tree<Competitor> createTree(String rankingText) {
|
||||
Tree<Competitor> competitorTree = new SortedBinaryTree<>();
|
||||
String[] lines = rankingText.split("\n");
|
||||
for (String line : lines) {
|
||||
String name = line.split(";")[0];
|
||||
String time = line.split(";")[1];
|
||||
competitorTree.add(new Competitor(0, name, time));
|
||||
}
|
||||
return competitorTree;
|
||||
}
|
||||
|
||||
public String createSortedText(Tree<Competitor> competitorTree) {
|
||||
AtomicInteger rank = new AtomicInteger(1);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
competitorTree.traversal().inorder(c -> {c.setRank(rank.getAndIncrement()); sb.append(c).append("\n");});
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
String rangliste = "Mueller Stefan;02:31:14\n" +
|
||||
"Marti Adrian;02:30:09\n" +
|
||||
"Kiptum Daniel;02:11:31\n" +
|
||||
"Ancay Tarcis;02:20:02\n" +
|
||||
"Kreibuhl Christian;02:21:47\n" +
|
||||
"Ott Michael;02:33:48\n" +
|
||||
"Menzi Christoph;02:27:26\n" +
|
||||
"Oliver Ruben;02:32:12\n" +
|
||||
"Elmer Beat;02:33:53\n" +
|
||||
"Kuehni Martin;02:33:36\n";
|
||||
rankGood = createTree(rangliste);
|
||||
textGood = createSortedText(rankGood);
|
||||
rankTest = new RankingTreeServer().createTree(rangliste);
|
||||
textTest = new RankingTreeServer().createSortedText(rankTest);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateText() {
|
||||
String[] good = textGood.split("[\r\n]*");
|
||||
String[] test = textTest.split("[\r\n]*");
|
||||
assertEquals(good.length, test.length, "length");
|
||||
for (int i = 0; i < good.length;i++) {
|
||||
assertEquals(good[i], test[i], "rangliste["+i+"]");
|
||||
}
|
||||
}
|
||||
}
|
61
app/src/test/java/ch/nuth/zhaw/exbox/ADS5_4_test.java
Normal file
61
app/src/test/java/ch/nuth/zhaw/exbox/ADS5_4_test.java
Normal file
|
@ -0,0 +1,61 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* @(#)TreeTest.java
|
||||
*
|
||||
*
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS5_4_test {
|
||||
Tree<String> tree;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
tree = new SortedBinaryTree<>();
|
||||
tree.add("B");
|
||||
tree.add("A");
|
||||
tree.add("C");
|
||||
tree.add("D");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHeight() {
|
||||
assertEquals(3, tree.height(), "height");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSize() {
|
||||
assertEquals(4, tree.size(), "size");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSizeMixed() {
|
||||
Tree<String> tree = new SortedBinaryTree<>();
|
||||
List<String> list = new LinkedList<>();
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
char c = (char) ('A' + (Math.random() * 26));
|
||||
int op = (int) (Math.random() * 2);
|
||||
switch (op) {
|
||||
case 0:
|
||||
list.add(Character.toString(c));
|
||||
tree.add(Character.toString(c));
|
||||
break;
|
||||
case 1:
|
||||
list.remove(Character.toString(c));
|
||||
tree.remove(Character.toString(c));
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertEquals(list.size(), tree.size());
|
||||
}
|
||||
}
|
56
app/src/test/java/ch/nuth/zhaw/exbox/ADS5_5_test.java
Normal file
56
app/src/test/java/ch/nuth/zhaw/exbox/ADS5_5_test.java
Normal file
|
@ -0,0 +1,56 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* @(#)TreeTest.java
|
||||
*
|
||||
*
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS5_5_test {
|
||||
Tree<String> tree;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
tree = new SortedBinaryTree<>();
|
||||
tree.add("B");
|
||||
tree.add("A");
|
||||
tree.add("C");
|
||||
tree.add("D");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInterval() {
|
||||
char left = 'K';
|
||||
char right = 'O';
|
||||
|
||||
for (int i = 0; i < 200; i++) {
|
||||
char c = (char) ('A' + (Math.random() * 26));
|
||||
tree.add(Character.toString(c));
|
||||
}
|
||||
// get all elements with inorder
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().inorder(v);
|
||||
int count = 0;
|
||||
String s = v.toString();
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
if (s.charAt(i) >= left && s.charAt(i) <= right) count++;
|
||||
}
|
||||
// now interval
|
||||
v = new MyVisitor<>();
|
||||
tree.traversal().interval(Character.toString(left), Character.toString(right), v);
|
||||
s = v.toString();
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
assertTrue(c >= left && c <= right, c + " in interval "+left+" "+right);
|
||||
}
|
||||
assertEquals(count, s.length(), "size");
|
||||
}
|
||||
}
|
84
app/src/test/java/ch/nuth/zhaw/exbox/ADS6_2_test.java
Normal file
84
app/src/test/java/ch/nuth/zhaw/exbox/ADS6_2_test.java
Normal file
|
@ -0,0 +1,84 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* @(#)TreeTest.java
|
||||
*
|
||||
*
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS6_2_test {
|
||||
Tree<String> tree;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
tree = new AVLSearchTree<>();
|
||||
tree.add("B");
|
||||
tree.add("A");
|
||||
tree.add("C");
|
||||
tree.add("D");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInorder() {
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().inorder(v);
|
||||
assertEquals("ABCD", v.toString(), "inorder");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPreorder() {
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().preorder(v);
|
||||
assertEquals("BACD", v.toString(), "preorder");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testPostorder() {
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().postorder(v);
|
||||
assertEquals("ADCB", v.toString(), "postorder");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLevelorder() {
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().levelorder(v);
|
||||
assertEquals("BACD", v.toString(), "levelorder");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInterval() {
|
||||
char left = 'K';
|
||||
char right = 'O';
|
||||
|
||||
for (int i = 0; i < 200; i++) {
|
||||
char c = (char) ('A' + (Math.random() * 26));
|
||||
tree.add(Character.toString(c));
|
||||
}
|
||||
// get all elements with inorder
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().inorder(v);
|
||||
int count = 0;
|
||||
String s = v.toString();
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
if (s.charAt(i) >= left && s.charAt(i) <= right) count++;
|
||||
}
|
||||
// now interval
|
||||
v = new MyVisitor<>();
|
||||
tree.traversal().interval(((Character)left).toString(), Character.toString(right), v);
|
||||
s = v.toString();
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
assertTrue(c >= left && c <= right, c + " in interval " + left + " " + right);
|
||||
}
|
||||
assertEquals(count, s.length(), "size");
|
||||
}
|
||||
}
|
43
app/src/test/java/ch/nuth/zhaw/exbox/ADS6_4_test.java
Normal file
43
app/src/test/java/ch/nuth/zhaw/exbox/ADS6_4_test.java
Normal file
|
@ -0,0 +1,43 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* @(#)TreeTest.java
|
||||
*
|
||||
*
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS6_4_test {
|
||||
MyTree<String> tree;
|
||||
|
||||
static class MyTree<T extends Comparable<T>> extends AVLSearchTree<T> {
|
||||
TreeNode<T> getRoot () {
|
||||
return root;
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
tree = new MyTree<>();
|
||||
tree.add("B");
|
||||
tree.add("A");
|
||||
tree.add("C");
|
||||
tree.add("D");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testBalanced() {
|
||||
assertTrue(tree.balanced(), "should be balanced");
|
||||
TreeNode<String> n = tree.getRoot();
|
||||
n.right.right.right = new TreeNode<>("Z");
|
||||
assertFalse(tree.balanced(), "should not be balanced");
|
||||
|
||||
}
|
||||
}
|
50
app/src/test/java/ch/nuth/zhaw/exbox/ADS6_5_test.java
Normal file
50
app/src/test/java/ch/nuth/zhaw/exbox/ADS6_5_test.java
Normal file
|
@ -0,0 +1,50 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* @(#)TreeTest.java
|
||||
*
|
||||
*
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS6_5_test {
|
||||
Tree<String> tree;
|
||||
|
||||
@Test
|
||||
public void testMixed() {
|
||||
tree = new AVLSearchTree<>();
|
||||
List<String> list = new LinkedList<>();
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
char c = (char) ('A' + (Math.random() * 26));
|
||||
int op = (int) (Math.random() * 2);
|
||||
switch (op) {
|
||||
case 0:
|
||||
list.add(Character.toString(c));
|
||||
tree.add(Character.toString(c));
|
||||
break;
|
||||
case 1:
|
||||
list.remove(Character.toString(c));
|
||||
tree.remove(Character.toString(c));
|
||||
break;
|
||||
}
|
||||
}
|
||||
assertEquals(list.size(), tree.size());
|
||||
Collections.sort(list);
|
||||
String expected = String.join("", list);
|
||||
Visitor<String> v = new MyVisitor<>();
|
||||
tree.traversal().inorder(v);
|
||||
assertEquals(expected, v.toString(), "mixed");
|
||||
|
||||
assertTrue(tree.balanced(), "balanced");
|
||||
}
|
||||
}
|
76
app/src/test/java/ch/nuth/zhaw/exbox/ADS7_3_test.java
Normal file
76
app/src/test/java/ch/nuth/zhaw/exbox/ADS7_3_test.java
Normal file
|
@ -0,0 +1,76 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* @(#)TreeTest.java
|
||||
*
|
||||
*
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS7_3_test {
|
||||
RouteServer routeServer;
|
||||
Graph<DijkstraNode, Edge> graph;
|
||||
String fileToTest = "RouteServer.java";
|
||||
|
||||
@BeforeEach
|
||||
void init() throws Exception {
|
||||
String swiss = "Winterthur Zürich 25\n" +
|
||||
"Zürich Bern 126\n" +
|
||||
"Zürich Genf 277\n" +
|
||||
"Zürich Luzern 54\n" +
|
||||
"Zürich Chur 121\n" +
|
||||
"Zürich Berikon 16\n" +
|
||||
"Bern Genf 155\n" +
|
||||
"Genf Lugano 363\n" +
|
||||
"Lugano Luzern 206\n" +
|
||||
"Lugano Chur 152\n" +
|
||||
"Chur Luzern 146\n" +
|
||||
"Luzern Bern 97\n" +
|
||||
"Bern Berikon 102\n" +
|
||||
"Luzern Berikon 41\n";
|
||||
routeServer = new RouteServer();
|
||||
graph = routeServer.createGraph(swiss);
|
||||
}
|
||||
|
||||
private void testDest(DijkstraNode start, String destName, double dist) {
|
||||
for (Edge road: start.getEdges()) {
|
||||
DijkstraNode destTown = (DijkstraNode) road.getDest();
|
||||
if (destName.equals(destTown.getName())) {
|
||||
assertEquals(dist, road.getWeight(), 1E-10, start.getName() + " to " + destName);
|
||||
return;
|
||||
}
|
||||
}
|
||||
fail(destName + " not connected to " + start.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateGrasphEdges() {
|
||||
DijkstraNode town = graph.findNode("Luzern");
|
||||
assertNotNull(town, "Luzern");
|
||||
testDest(town, "Bern", 97);
|
||||
testDest(town, "Berikon", 41);
|
||||
testDest(town, "Chur", 146);
|
||||
testDest(town, "Lugano", 206);
|
||||
testDest(town, "Zürich", 54);
|
||||
testDest(town, "Berikon", 41);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateGrasphNodes() {
|
||||
DijkstraNode town = graph.findNode("Luzern");
|
||||
assertNotNull(town, "Luzern");
|
||||
town = graph.findNode("Winterthur");
|
||||
assertNotNull(town, "Winterthur");
|
||||
town = graph.findNode("Paris");
|
||||
assertNull(town, "Paris");
|
||||
}
|
||||
}
|
73
app/src/test/java/ch/nuth/zhaw/exbox/ADS7_4_test.java
Normal file
73
app/src/test/java/ch/nuth/zhaw/exbox/ADS7_4_test.java
Normal file
|
@ -0,0 +1,73 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* @(#)TreeTest.java
|
||||
*
|
||||
*
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS7_4_test {
|
||||
RouteServer routeServer;
|
||||
Graph<DijkstraNode, Edge> graph;
|
||||
String fileToTest = "RouteServer.java";
|
||||
|
||||
@BeforeEach
|
||||
public void init() throws Exception {
|
||||
String swiss = "Winterthur Zürich 25\n" +
|
||||
"Zürich Bern 126\n" +
|
||||
"Zürich Genf 277\n" +
|
||||
"Zürich Luzern 54\n" +
|
||||
"Zürich Chur 121\n" +
|
||||
"Zürich Berikon 16\n" +
|
||||
"Bern Genf 155\n" +
|
||||
"Genf Lugano 363\n" +
|
||||
"Lugano Luzern 206\n" +
|
||||
"Lugano Chur 152\n" +
|
||||
"Chur Luzern 146\n" +
|
||||
"Luzern Bern 97\n" +
|
||||
"Bern Berikon 102\n" +
|
||||
"Luzern Berikon 41\n";
|
||||
routeServer = new RouteServer();
|
||||
graph = routeServer.createGraph(swiss);
|
||||
}
|
||||
|
||||
private void testDest(List<DijkstraNode> route, String startName, String destName, double dist) {
|
||||
for (DijkstraNode town : route) {
|
||||
if (destName.equals(town.getName())) {
|
||||
assertEquals(dist, town.getDist(), 1E-10, startName + " to " + destName);
|
||||
return;
|
||||
}
|
||||
}
|
||||
fail(startName + " not connected to " + destName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testWinterthurLugano() {
|
||||
routeServer.dijkstraRoute(graph, "Winterthur", "Lugano");
|
||||
List<DijkstraNode> route = routeServer.getRoute(graph, "Lugano");
|
||||
testDest(route, "Winterthur", "Winterthur", 0);
|
||||
testDest(route, "Winterthur", "Zürich", 25);
|
||||
testDest(route, "Winterthur", "Luzern", 79);
|
||||
testDest(route, "Winterthur", "Lugano", 285);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testLuganoWinterthur() {
|
||||
routeServer.dijkstraRoute(graph, "Lugano", "Winterthur");
|
||||
List<DijkstraNode> route = routeServer.getRoute(graph, "Winterthur");
|
||||
testDest(route, "Lugano", "Winterthur", 285);
|
||||
testDest(route, "Lugano", "Zürich", 260);
|
||||
testDest(route, "Lugano", "Luzern", 206);
|
||||
testDest(route, "Lugano", "Lugano", 0);
|
||||
}
|
||||
}
|
43
app/src/test/java/ch/nuth/zhaw/exbox/ADS8_2_test.java
Normal file
43
app/src/test/java/ch/nuth/zhaw/exbox/ADS8_2_test.java
Normal file
|
@ -0,0 +1,43 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS8_2_test {
|
||||
LabyrinthServer labyrinthServer;
|
||||
Graph<DijkstraNode, Edge> graph;
|
||||
|
||||
@BeforeEach
|
||||
public void init() {
|
||||
String labyrinth = "0-6 4-6\n4-6 7-6\n7-6 9-6\n7-6 7-4\n7-4 6-4\n7-4 9-4\n9-4 9-1\n" +
|
||||
"7-4 7-1\n7-1 5-1\n4-6 4-4\n4-4 4-3\n4-4 1-4\n1-4 1-1\n1-1 3-1\n3-1 3-2\n3-1 3-0\n";
|
||||
labyrinthServer = new LabyrinthServer();
|
||||
graph = labyrinthServer.createGraph(labyrinth);
|
||||
}
|
||||
|
||||
private void testEdge(String startName, String destName) {
|
||||
DijkstraNode node = graph.findNode(startName);
|
||||
for (Edge edge : node.getEdges()) {
|
||||
if (edge.getDest().getName().equals(destName)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
fail(startName + " not connected to " + destName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateGraph() {
|
||||
testEdge("0-6", "4-6");
|
||||
testEdge("4-6", "0-6");
|
||||
testEdge("1-4", "1-1");
|
||||
testEdge("3-1", "3-0");
|
||||
testEdge("3-0", "3-1");
|
||||
}
|
||||
}
|
57
app/src/test/java/ch/nuth/zhaw/exbox/ADS8_3_test.java
Normal file
57
app/src/test/java/ch/nuth/zhaw/exbox/ADS8_3_test.java
Normal file
|
@ -0,0 +1,57 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS8_3_test {
|
||||
LabyrinthServer labyrinthServer;
|
||||
Graph<DijkstraNode, Edge> graph;
|
||||
|
||||
@BeforeEach
|
||||
public void init() {
|
||||
String labyrinth = "0-6 4-6\n4-6 7-6\n7-6 9-6\n7-6 7-4\n7-4 6-4\n7-4 9-4\n9-4 9-1\n" +
|
||||
"7-4 7-1\n7-1 5-1\n4-6 4-4\n4-4 4-3\n4-4 1-4\n1-4 1-1\n1-1 3-1\n3-1 3-2\n3-1 3-0\n";
|
||||
labyrinthServer = new LabyrinthServer();
|
||||
graph = labyrinthServer.createGraph(labyrinth);
|
||||
}
|
||||
|
||||
private void testEdge(String startName, String destName) {
|
||||
DijkstraNode node = graph.findNode(startName);
|
||||
for (Edge edge : node.getEdges()) {
|
||||
if (edge.getDest().getName().equals(destName)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
fail(startName + " not connected to " + destName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateGraph() {
|
||||
testEdge("0-6", "4-6");
|
||||
testEdge("4-6", "0-6");
|
||||
testEdge("1-4", "1-1");
|
||||
testEdge("3-1", "3-0");
|
||||
testEdge("3-0", "3-1");
|
||||
}
|
||||
|
||||
private void testPath(String trace, String path) {
|
||||
if (!trace.contains(path)) {
|
||||
fail(path + " not found");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDrawLabyrinth() {
|
||||
labyrinthServer.drawLabyrinth(graph);
|
||||
String trace = ServerGraphics.instance().getTrace();
|
||||
testPath(trace, "<rect x=\"0.5455\" y=\"0.3636\" width=\"0.1818\" height=\"0.0909\"");
|
||||
testPath(trace, "<rect x=\"0.2727\" y=\"0.0909\" width=\"0.0909\" height=\"0.1818\"");
|
||||
}
|
||||
}
|
69
app/src/test/java/ch/nuth/zhaw/exbox/ADS8_4_test.java
Normal file
69
app/src/test/java/ch/nuth/zhaw/exbox/ADS8_4_test.java
Normal file
|
@ -0,0 +1,69 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS8_4_test {
|
||||
LabyrinthServer labyrinthServer;
|
||||
Graph<DijkstraNode, Edge> graph;
|
||||
|
||||
@BeforeEach
|
||||
public void init() {
|
||||
String labyrinth = "0-6 4-6\n4-6 7-6\n7-6 9-6\n7-6 7-4\n7-4 6-4\n7-4 9-4\n9-4 9-1\n" +
|
||||
"7-4 7-1\n7-1 5-1\n4-6 4-4\n4-4 4-3\n4-4 1-4\n1-4 1-1\n1-1 3-1\n3-1 3-2\n3-1 3-0\n";
|
||||
labyrinthServer = new LabyrinthServer();
|
||||
graph = labyrinthServer.createGraph(labyrinth);
|
||||
}
|
||||
|
||||
private void testEdge(String startName, String destName) {
|
||||
DijkstraNode node = graph.findNode(startName);
|
||||
for (Edge edge : node.getEdges()) {
|
||||
if (edge.getDest().getName().equals(destName)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
fail(startName + " not connected to " + destName);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateGraph() {
|
||||
testEdge("0-6", "4-6");
|
||||
testEdge("4-6", "0-6");
|
||||
testEdge("1-4", "1-1");
|
||||
testEdge("3-1", "3-0");
|
||||
testEdge("3-0", "3-1");
|
||||
}
|
||||
|
||||
private void testPath(String trace, String path) {
|
||||
if (!trace.contains(path)) {
|
||||
fail(path + " not found");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDrawLabyrinth() {
|
||||
labyrinthServer.drawLabyrinth(graph);
|
||||
String trace = ServerGraphics.instance().getTrace();
|
||||
testPath(trace, "<rect x=\"0.5455\" y=\"0.3636\" width=\"0.1818\" height=\"0.0909\"");
|
||||
testPath(trace, "<rect x=\"0.2727\" y=\"0.0909\" width=\"0.0909\" height=\"0.1818\"");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDrawRoute() {
|
||||
labyrinthServer.drawRoute(graph, "0-6", "3-0");
|
||||
String trace = ServerGraphics.instance().getTrace();
|
||||
testPath(trace, "<line x1=\"0.3182\" y1=\"0.0455\" x2=\"0.3182\" y2=\"0.1364\"/>");
|
||||
testPath(trace, "<line x1=\"0.1364\" y1=\"0.1364\" x2=\"0.3182\" y2=\"0.1364\"/>");
|
||||
testPath(trace, "<line x1=\"0.1364\" y1=\"0.1364\" x2=\"0.1364\" y2=\"0.4091\"/>");
|
||||
testPath(trace, "<line x1=\"0.1364\" y1=\"0.4091\" x2=\"0.4091\" y2=\"0.4091\"/>");
|
||||
testPath(trace, "<line x1=\"0.4091\" y1=\"0.4091\" x2=\"0.4091\" y2=\"0.5909\"/>");
|
||||
testPath(trace, "<line x1=\"0.0455\" y1=\"0.5909\" x2=\"0.4091\" y2=\"0.5909\"/>");
|
||||
}
|
||||
}
|
35
app/src/test/java/ch/nuth/zhaw/exbox/ADS9_2_test.java
Normal file
35
app/src/test/java/ch/nuth/zhaw/exbox/ADS9_2_test.java
Normal file
|
@ -0,0 +1,35 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
|
||||
/**
|
||||
* @author K Rege
|
||||
* @version 1.00 2018/3/17
|
||||
* @version 1.01 2021/8/1
|
||||
*/
|
||||
public class ADS9_2_test {
|
||||
MyCompetitor c1 = new MyCompetitor(1, "Kiptum Daniel", "02:11:31");
|
||||
MyCompetitor c2 = new MyCompetitor(1, "Kiptum Daniel", "02:11:31");
|
||||
MyCompetitor c3 = new MyCompetitor(2, "Ancay Tarcis", "02:20:02");
|
||||
|
||||
@Test
|
||||
public void testEquals() {
|
||||
assertEquals(c1, c2);
|
||||
assertNotEquals(c1, c3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCompareTo() {
|
||||
assertEquals(0, c1.compareTo(c2));
|
||||
assertNotEquals(0, c1.compareTo(c3));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHashcode() {
|
||||
assertEquals(c1.hashCode(), c2.hashCode());
|
||||
assertNotEquals(c1.hashCode(), c3.hashCode());
|
||||
}
|
||||
}
|
144
app/src/test/java/ch/nuth/zhaw/exbox/ADS9_3_test.java
Normal file
144
app/src/test/java/ch/nuth/zhaw/exbox/ADS9_3_test.java
Normal file
|
@ -0,0 +1,144 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class Town {
|
||||
int hashCode;
|
||||
String name;
|
||||
String nb;
|
||||
Town (int hashCode, String name, String nb) {
|
||||
this.name = name; this.hashCode = hashCode; this.nb = nb;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (!(o instanceof Town)) return false;
|
||||
return ((Town)o).name.equals(this.name);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return hashCode;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return name + " " + hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
public class ADS9_3_test {
|
||||
Map<Town, Town> hashmap;
|
||||
List<Town> towns;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
towns = List.of(
|
||||
new Town(5, "Bari", "BA"),
|
||||
new Town(8, "Bologna", "BO"),
|
||||
new Town(3, "Catania", "CA"),
|
||||
new Town(9, "Firenze", "FI"),
|
||||
new Town(0, "Genova", "GV"),
|
||||
new Town(12, "Milano", "MI"),
|
||||
new Town(7, "Napoli", "NA"),
|
||||
new Town(7, "Palermo", "PA"),
|
||||
new Town(7, "Roma", "RM"),
|
||||
new Town(5, "Torino", "TO")
|
||||
);
|
||||
|
||||
hashmap = new MyHashtable<>(100);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd() {
|
||||
hashmap.clear();
|
||||
Town t0 = towns.get(0);
|
||||
hashmap.put(t0, t0);
|
||||
Town t1 = hashmap.get(t0);
|
||||
assertEquals(t0, t1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd2() {
|
||||
hashmap.clear();
|
||||
Town t0 = towns.get(0);
|
||||
Town t1 = towns.get(1);
|
||||
hashmap.put(t0, t0);
|
||||
hashmap.put(t1, t1);
|
||||
Town t2 = hashmap.get(t0);
|
||||
assertEquals(t0, t2);
|
||||
t2 = hashmap.get(t1);
|
||||
assertEquals(t1, t2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd3() {
|
||||
hashmap.clear();
|
||||
Town t0 = towns.get(0);
|
||||
hashmap.remove(t0);
|
||||
hashmap.put(t0, t0);
|
||||
hashmap.put(t0, t0);
|
||||
assertEquals(1, hashmap.size());
|
||||
Town t1 = hashmap.get(t0);
|
||||
assertEquals(t0, t1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd4() {
|
||||
hashmap.clear();
|
||||
Town t0 = towns.get(0);
|
||||
hashmap.put(t0, t0);
|
||||
hashmap.put(t0, t0);
|
||||
assertEquals(1, hashmap.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSize() {
|
||||
hashmap.clear();
|
||||
assertEquals(0, hashmap.size());
|
||||
testAdd2();
|
||||
assertEquals(2, hashmap.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove() {
|
||||
hashmap.clear();
|
||||
Town t0 = towns.get(0);
|
||||
Town t1 = towns.get(1);
|
||||
hashmap.put(t0, t0);
|
||||
hashmap.remove(t0);
|
||||
assertEquals(0, hashmap.size());
|
||||
hashmap.put(t0, t0);
|
||||
hashmap.remove(t1);
|
||||
assertEquals(1, hashmap.size());
|
||||
hashmap.remove(t0);
|
||||
assertEquals(0, hashmap.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMixed() {
|
||||
hashmap.clear();
|
||||
Map<Town, Town> hashmap2 = new HashMap<>();
|
||||
for (int i = 0; i < 10000; i++) {
|
||||
Town c = towns.get((int)(Math.random() * towns.size()));
|
||||
int op = (int)(Math.random() * 2);
|
||||
switch (op) {
|
||||
case 0: hashmap.put(c, c); hashmap2.put(c, c); break;
|
||||
case 1: hashmap.remove(c); hashmap2.remove(c); break;
|
||||
}
|
||||
}
|
||||
assertEquals(hashmap2.size(), hashmap.size());
|
||||
for (Town t : towns) {
|
||||
Town c1 = hashmap.get(t);
|
||||
Town c2 = hashmap2.get(t);
|
||||
assertEquals(c1, c2);
|
||||
}
|
||||
}
|
||||
}
|
119
app/src/test/java/ch/nuth/zhaw/exbox/ADS9_4_test.java
Normal file
119
app/src/test/java/ch/nuth/zhaw/exbox/ADS9_4_test.java
Normal file
|
@ -0,0 +1,119 @@
|
|||
package ch.nuth.zhaw.exbox;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
public class ADS9_4_test {
|
||||
Map<Town, Town> hashmap;
|
||||
List<Town> towns;
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
towns = List.of(
|
||||
new Town(5, "Bari", "BA"),
|
||||
new Town(8, "Bologna", "BO"),
|
||||
new Town(3, "Catania", "CA"),
|
||||
new Town(9, "Firenze", "FI"),
|
||||
new Town(0, "Genova", "GV"),
|
||||
new Town(12, "Milano", "MI"),
|
||||
new Town(7, "Napoli", "NA"),
|
||||
new Town(7, "Palermo", "PA"),
|
||||
new Town(7, "Roma", "RM"),
|
||||
new Town(5, "Torino", "TO")
|
||||
);
|
||||
|
||||
hashmap = new MyHashtable<>(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd() {
|
||||
hashmap.clear();
|
||||
Town t0 = towns.get(0);
|
||||
hashmap.put(t0, t0);
|
||||
Town t1 = hashmap.get(t0);
|
||||
assertEquals(t0, t1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd2() {
|
||||
hashmap.clear();
|
||||
Town t0 = towns.get(0);
|
||||
Town t1 = towns.get(1);
|
||||
hashmap.put(t0, t0);
|
||||
hashmap.put(t1, t1);
|
||||
Town t2 = hashmap.get(t0);
|
||||
assertEquals(t0, t2);
|
||||
t2 = hashmap.get(t1);
|
||||
assertEquals(t1, t2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd3() {
|
||||
hashmap.clear();
|
||||
Town t0 = towns.get(0);
|
||||
hashmap.remove(t0);
|
||||
hashmap.put(t0, t0);
|
||||
hashmap.put(t0, t0);
|
||||
assertEquals(1, hashmap.size());
|
||||
Town t1 = hashmap.get(t0);
|
||||
assertEquals(t0, t1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAdd4() {
|
||||
hashmap.clear();
|
||||
Town t0 = towns.get(0);
|
||||
hashmap.put(t0, t0);
|
||||
hashmap.put(t0, t0);
|
||||
assertEquals(1, hashmap.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSize() {
|
||||
hashmap.clear();
|
||||
assertEquals(0, hashmap.size());
|
||||
testAdd2();
|
||||
assertEquals(2, hashmap.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRemove() {
|
||||
hashmap.clear();
|
||||
Town t0 = towns.get(0);
|
||||
Town t1 = towns.get(1);
|
||||
hashmap.put(t0, t0);
|
||||
hashmap.remove(t0);
|
||||
assertEquals(0, hashmap.size());
|
||||
hashmap.put(t0, t0);
|
||||
hashmap.remove(t1);
|
||||
assertEquals(1, hashmap.size());
|
||||
hashmap.remove(t0);
|
||||
assertEquals(0, hashmap.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMixed() {
|
||||
hashmap.clear();
|
||||
Map<Town, Town> hashmap2 = new HashMap<>();
|
||||
for (int i = 0; i < 1000; i++) {
|
||||
Town c = towns.get((int)(Math.random() * towns.size()));
|
||||
int op = (int)(Math.random() * 2);
|
||||
switch (op) {
|
||||
case 0: hashmap.put(c, c); hashmap2.put(c, c); break;
|
||||
case 1: hashmap.remove(c); hashmap2.remove(c); break;
|
||||
}
|
||||
}
|
||||
assertEquals(hashmap2.size(), hashmap.size());
|
||||
for (Town t : towns) {
|
||||
Town c1 = hashmap.get(t);
|
||||
Town c2 = hashmap2.get(t);
|
||||
assertEquals(c1, c2);
|
||||
}
|
||||
}
|
||||
}
|
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
5
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
|
@ -0,0 +1,5 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-7.5.1-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
240
gradlew
vendored
Normal file
240
gradlew
vendored
Normal file
|
@ -0,0 +1,240 @@
|
|||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015-2021 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# Gradle start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh Gradle
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=${0##*/}
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command;
|
||||
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
|
||||
# shell script including quotes and variable substitutions, so put them in
|
||||
# double quotes to make sure that they get re-expanded; and
|
||||
# * put everything else in single quotes, so that it's not re-expanded.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
91
gradlew.bat
vendored
Normal file
91
gradlew.bat
vendored
Normal file
|
@ -0,0 +1,91 @@
|
|||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
set EXIT_CODE=%ERRORLEVEL%
|
||||
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||
exit /b %EXIT_CODE%
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue