initial commit

This commit is contained in:
schrom01 2022-10-25 10:03:22 +02:00
commit 78f5531067
27 changed files with 5005 additions and 0 deletions

26
build.gradle Normal file
View File

@ -0,0 +1,26 @@
plugins {
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
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'
}
application {
mainClass = 'ch.zhaw.ads.ExBox'
}
sourceSets {
main.java.srcDirs = ['src']
test.java.srcDirs = ['src']
}
tasks.named('test') {
useJUnitPlatform()
}

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -0,0 +1,234 @@
#!/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 \
"$@"
# 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" "$@"

89
gradlew.bat vendored Normal file
View File

@ -0,0 +1,89 @@
@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%" == "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%"=="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!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

10
settings.gradle Normal file
View File

@ -0,0 +1,10 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
*
* Detailed information about configuring a multi-project build in Gradle can be found
* in the user manual at https://docs.gradle.org/7.4.2/userguide/multi_project_builds.html
*/
rootProject.name = 'ADS Praktikum 6'

View File

@ -0,0 +1,100 @@
package ch.zhaw.ads;
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");
}
}
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();
}
}

View File

@ -0,0 +1,43 @@
package ch.zhaw.ads;
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");
}
}

View File

@ -0,0 +1,50 @@
package ch.zhaw.ads;
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");
}
}

View File

@ -0,0 +1,199 @@
package ch.zhaw.ads;
/**
* 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) {
// TODO Implement (6.4)
return true;
}
public boolean balanced() {
return balanced(root);
}
@Override
protected int calcSize(TreeNode<T> p) {
// TODO Implement (6.2)
}
/**
* 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)) {
// TODO Implement (6.2)
} else {
// TODO Implement (6.2)
}
} else if (height(p.right) - height(p.left) == 2) {
if (height(p.right.right) >= height(p.right.left)) {
// TODO Implement (6.2)
} else {
// TODO Implement (6.2)
}
}
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);
}
// TODO Implement (6.5)
return 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);
}
}

View File

@ -0,0 +1,88 @@
package ch.zhaw.ads;
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);
}
}

View File

@ -0,0 +1,15 @@
package ch.zhaw.ads;
/**
* AnyServer -- Praktikum Experimentierkasten -- ADS
*
* @author E. Mumprecht
* @version 1.0 -- Geruest fuer irgendeinen Server
*/
public class AnyServer implements CommandExecutor {
//----- Dies implementiert das CommandExecutor Interface.
@Override
public String execute(String command) {
return "Die Eingabe ist \"" + command + "\"\n";
}
}

View File

@ -0,0 +1,20 @@
package ch.zhaw.ads;
/**
* 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;
}

View File

@ -0,0 +1,67 @@
package ch.zhaw.ads;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
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 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(Competitor o) {
if (o == this) return 0;
return (int) (parseTime(this.getTime()) - parseTime(o.getTime()));
}
@Override
public boolean equals (Object o) {
if (!(o instanceof Competitor)) return false;
return compareTo((Competitor)o) == 0;
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + (name == null ? 0 : name.hashCode());
hash = 31 * hash + (time == null ? 0 : time.hashCode());
return hash;
}
}

View File

@ -0,0 +1,13 @@
package ch.zhaw.ads;
/**
* @author K. Rege
* @version 1.0 -- Experimentierkasten
*/
public class ExBox {
public static void main(String[] args) {
ExBoxFrame f = new ExBoxFrame();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

View File

@ -0,0 +1,294 @@
package ch.zhaw.ads;
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 int UHDTHRESHOLD = 1920;
private final String STANDARDENCODING = "ISO-8859-1";
private JMenuItem connect, 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);
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 scaleFaktor = (screenSize.getWidth() <= UHDTHRESHOLD) ? 1 : 2;
setFontSize((int) (11 * scaleFaktor));
setSize(
new Dimension((int) (400 * scaleFaktor), (int) (400 * scaleFaktor)));
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 (lastServer != null) {
command = ServerFactory.createServer(lastServer);
}
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");
command = ServerFactory.createServer(name);
lastServer = name;
String fullClassName = command.getClass().getName();
String simpleClassName = fullClassName.substring(
fullClassName.lastIndexOf('.') + 1);
setTitle("ExBox connected to " + simpleClassName);
}
private void openFile() throws Exception {
String name = openFileDialog(null, null);
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() == 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());
}
}
}

View File

@ -0,0 +1,92 @@
package ch.zhaw.ads;
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);
}
}
}
}

View File

@ -0,0 +1,84 @@
package ch.zhaw.ads;
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);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,44 @@
package ch.zhaw.ads;
import java.util.concurrent.atomic.AtomicInteger;
public class RankingTreeServer implements CommandExecutor {
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();
}
public String execute(String rankingList) {
Tree<Competitor> competitorTree = createTree(rankingList);
return "Rangliste (Tree)\n" + createSortedText(competitorTree);
}
public static void main(String[] args) {
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";
RankingTreeServer server = new RankingTreeServer();
System.out.println(server.execute(rangliste));
}
}

View File

@ -0,0 +1,76 @@
package ch.zhaw.ads;
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();
}
}

View File

@ -0,0 +1,133 @@
package ch.zhaw.ads;
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<T>(root);
}
protected int calcHeight(TreeNode<T> node) {
if (node == null) {
return 0;
} else {
return 1 + Math.max(calcHeight(node.left), calcHeight(node.right));
}
}
public int height() {
return calcHeight(root);
}
protected int calcSize(TreeNode<T> p) {
if (p == null) {
return 0;
} else {
return 1 + calcSize(p.left) + calcSize(p.right);
}
}
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 ? " | " : " "));
}
}
}

View File

@ -0,0 +1,15 @@
package ch.zhaw.ads;
/** 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
src/ch/zhaw/ads/Tree.java Normal file
View File

@ -0,0 +1,25 @@
package ch.zhaw.ads;
/** 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();
}

View File

@ -0,0 +1,22 @@
package ch.zhaw.ads;
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);}
}

View File

@ -0,0 +1,88 @@
package ch.zhaw.ads;
import java.util.LinkedList;
import java.util.Queue;
public class TreeTraversal<T extends Comparable<T>> implements Traversal<T> {
private final TreeNode<T> root;
public TreeTraversal(TreeNode<T> root) {
this.root = root;
}
private void inorder(TreeNode<T> node, Visitor<T> vis) {
if (node != null) {
inorder(node.left, vis);
vis.visit(node.getValue());
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) {
vis.visit(node.getValue());
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);
vis.visit(node.getValue());
}
}
public void postorder(Visitor<T> vis) {
postorder(root, vis);
}
void levelorder(TreeNode<T> node, Visitor<T> visitor) {
Queue<TreeNode<T>> q = new LinkedList<TreeNode<T>>();
if (node != null) {
q.add(node);
}
while (!q.isEmpty()) {
node = q.remove();
visitor.visit(node.getValue());
if (node.left != null) {
q.add(node.left);
}
if (node.right != null) {
q.add(node.right);
}
}
}
public void levelorder(Visitor<T> vis) {
levelorder(root, vis);
}
private void interval(T min, T max, Visitor<T> v, TreeNode<T> node) {
if (node != null) {
if (0 > node.getValue().compareTo(min)) {
interval(min, max, v, node.right);
} else if (0 < node.getValue().compareTo(max)) {
interval(min, max, v, node.left);
} else {
v.visit(node.getValue());
interval(min, max, v, node.left);
interval(min, max, v, node.right);
}
}
}
@Override
public void interval(T min, T max, Visitor<T> v) {
interval(min, max, v, this.root);
}
}

View File

@ -0,0 +1,7 @@
package ch.zhaw.ads;
/** interface of visitor ADT */
public interface Visitor<T> {
/** called for each element in the tree */
void visit(T obj);
}