Compare commits

...

9 commits

27 changed files with 529 additions and 97 deletions

View file

@ -13,6 +13,7 @@ public class BracketServer implements CommandExecutor {
public BracketServer() {
super();
bracketPairs = new HashMap<>() {
{
put("(", ")");
@ -37,8 +38,7 @@ public class BracketServer implements CommandExecutor {
for (MatchResult result : results) {
if (bracketPairs.keySet().contains(result.group())) {
openBrackets.push(result.group());
} else if (
!openBrackets.isEmpty() &&
} else if (!openBrackets.isEmpty() &&
result.group().equals(bracketPairs.get(openBrackets.peek()))) {
openBrackets.pop();
} else {

View file

@ -37,13 +37,11 @@ public class Competitor implements Comparable<Competitor> {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date date = sdf.parse(s);
return date.getTime();
} catch (Exception e) {System.err.println(e);}
return 0;
} catch (Exception e) {
System.err.println(e);
}
private static String timeToString(int time) {
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
return df.format(new Date(time));
return 0;
}
public String toString() {
@ -70,8 +68,7 @@ public class Competitor implements Comparable<Competitor> {
if (o instanceof Competitor) {
Competitor c = (Competitor) o;
return compareTo(c) == 0;
}
else {
} else {
return false;
}
}
@ -91,8 +88,7 @@ class AlphaComparatorCompetitor implements Comparator<Competitor> {
if (result == 0) {
return Long.compare(o1.getTimeValue(), o2.getTimeValue());
}
else {
} else {
return result;
}
}

View file

@ -48,9 +48,11 @@ public class ExBoxFrame extends JFrame implements ActionListener, ItemListener {
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);
@ -132,9 +134,11 @@ public class ExBoxFrame extends JFrame implements ActionListener, ItemListener {
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);
@ -150,11 +154,11 @@ public class ExBoxFrame extends JFrame implements ActionListener, ItemListener {
} 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)));
setSize(new Dimension((int) (400 * scaleFaktor), (int) (400 * scaleFaktor)));
setTitle("ExBox");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
@ -174,14 +178,17 @@ public class ExBoxFrame extends JFrame implements ActionListener, ItemListener {
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 {
@ -214,8 +221,10 @@ public class ExBoxFrame extends JFrame implements ActionListener, ItemListener {
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());
if (pattern != null)
fd.setFile(pattern);
if (startDirectory != null)
fd.setDirectory(startDirectory.toString());
fd.setVisible(true);
return fd.getDirectory() + fd.getFile();
}
@ -224,6 +233,7 @@ public class ExBoxFrame extends JFrame implements ActionListener, ItemListener {
if (!retest) {
lastTestFile = openFileDialog(getPathCompiled(), "*test.class");
}
if (lastTestFile == null) {
output.append("ERROR no Test spezified\n");
} else if (unitTest != null) {
@ -236,8 +246,7 @@ public class ExBoxFrame extends JFrame implements ActionListener, ItemListener {
command = ServerFactory.createServer(name);
lastServer = name;
String fullClassName = command.getClass().getName();
String simpleClassName = fullClassName.substring(
fullClassName.lastIndexOf('.') + 1);
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);
setTitle("ExBox connected to " + simpleClassName);
}
@ -246,14 +255,15 @@ public class ExBoxFrame extends JFrame implements ActionListener, ItemListener {
String name = openFileDialog(null, null);
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(name), STANDARDENCODING)))
{
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());
}
}

View file

@ -19,9 +19,7 @@ public class ExBoxJUnit implements CommandExecutor {
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()
@ -30,6 +28,7 @@ public class ExBoxJUnit implements CommandExecutor {
Launcher launcher = LauncherFactory.create();
launcher.discover(request);
launcher.registerTestExecutionListeners(new TestExecutionListener() {
@Override
public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
@ -45,21 +44,27 @@ public class ExBoxJUnit implements CommandExecutor {
}
}
});
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();
}
@ -80,6 +85,7 @@ public class ExBoxJUnit implements CommandExecutor {
if (throwable == null) {
return "";
}
try (StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter)) {
throwable.printStackTrace(printWriter);

View file

@ -19,6 +19,7 @@ public class GraphicPanel extends JPanel {
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 {
@ -32,8 +33,10 @@ public class GraphicPanel extends JPanel {
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());
@ -43,6 +46,7 @@ public class GraphicPanel extends JPanel {
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")) {

View 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();
}
}

View file

@ -0,0 +1,40 @@
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);
} else {
turtle.turn(-angle);
turtle.move(dist);
turtle.turn(angle);
turtle.move(dist);
turtle.turn(angle);
turtle.move(dist);
turtle.turn(-angle);
}
}
}

View file

@ -17,8 +17,7 @@ public class LCMServer implements CommandExecutor {
int y = Integer.parseInt(matcher.group(2));
int result = leastCommonMultiple(x, y);
return "Das Resultat ist %d\n".formatted(result);
}
else {
} else {
throw new Exception("Der angegebene Befehl \"%s\" ist ungültig!\n".formatted(command));
}
}

View file

@ -12,8 +12,7 @@ public class ListStack implements Stack {
if (innerList.add(x)) {
return;
}
}
catch (Exception e) {
} catch (Exception e) {
throw new StackOverflowError();
}
}

View file

@ -4,6 +4,7 @@ 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 {
/**
@ -39,7 +40,7 @@ public class RankingListServer implements CommandExecutor {
}
public String createSortedText(List<Competitor> competitorList) {
List<Competitor> competitors = competitorList.stream().sorted().toList();
List<Competitor> competitors = competitorList.stream().sorted().collect(Collectors.toList());
String previousTime = null;
int previousRank = 1;
@ -56,13 +57,15 @@ public class RankingListServer implements CommandExecutor {
return String.join(
System.lineSeparator(),
competitors.stream().map((competitor) -> competitor.toString()).toList());
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()).toList());
competitorList.stream().sorted(new AlphaComparatorCompetitor()).map(
(competitor) -> competitor.toString()).collect(Collectors.toList()));
}
public String execute(String rankingList) {

View file

@ -16,7 +16,8 @@ class MyClassLoader extends ClassLoader {
/**
* @param name filename of class
* return content of file as array of bytes; if file does not exist return null
* return content of file as array of bytes; if file does not exist
* return null
*/
private byte[] getBytes(String name) {
try {
@ -38,15 +39,19 @@ class MyClassLoader extends ClassLoader {
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);
}
@ -67,6 +72,7 @@ public class ServerFactory {
public static Class<?> loadClass(String name) throws Exception {
MyClassLoader myClassLoader = new MyClassLoader(
MyClassLoader.class.getClassLoader());
return myClassLoader.loadClass(name, true);
}

View 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);
}
}
}

View 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;
}
}

View 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;
}
}

View file

@ -75,9 +75,11 @@ public class ADS2_3_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);
@ -89,7 +91,9 @@ public class ADS2_3_test {
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);

View file

@ -55,9 +55,11 @@ public class ADS2_4_test {
@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);
@ -69,8 +71,10 @@ public class ADS2_4_test {
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);

View file

@ -35,6 +35,7 @@ public class ADS3_2_test {
"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);
}
@ -42,6 +43,7 @@ public class ADS3_2_test {
@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 + "]");
}

View file

@ -18,11 +18,13 @@ public class ADS3_3_test {
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;
}
@ -30,10 +32,12 @@ public class ADS3_3_test {
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();
}
@ -49,11 +53,13 @@ public class ADS3_3_test {
"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();
}
@ -63,6 +69,7 @@ public class ADS3_3_test {
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 + "]");
}

View file

@ -17,26 +17,29 @@ public class ADS3_4_test {
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" +
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" +
@ -46,6 +49,7 @@ public class ADS3_4_test {
"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" +
@ -56,6 +60,7 @@ public class ADS3_4_test {
"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);
@ -71,6 +76,7 @@ public class ADS3_4_test {
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 + "]");
}

View 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);
}
}
}

View 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);
}
}
}