This commit is contained in:
2025-07-21 16:03:34 +02:00
parent a1cafb3b58
commit f92ac33890
43 changed files with 84817 additions and 0 deletions
+45
View File
@@ -0,0 +1,45 @@
/**
* A simple linked list that stores strings.
*
* @author Marcus
*
*/
public class LinkedList {
/**
* The reference to the fist list element.
*/
private ListItem head;
/**
* Adds the value at the beginning of the list.
*
* @param value The value to add.
*/
public void prepend(String value) {
// TODO: implement
}
/**
* Returns the value at the specified index.
*
* @param index The index.
* @return The value at the index.
* @throws IllegalArgumentException Thrown if index < 0 or index > size() - 1.
*/
public String get(int index) {
// TODO: implement
return null;
}
/**
* Returns the number of items that are in the list.
*
* @return The number of items in the list.
*/
public int size() {
// TODO: implement
return -1;
}
}
+54
View File
@@ -0,0 +1,54 @@
/**
* An item in a linked list.
*
* @author Marcus
*/
public class ListItem {
/**
* The value.
*/
private String value;
/**
* The next list item.
*/
private ListItem next;
/**
* Creates a list item with a value.
*
* @param value The value.
*/
public ListItem(String value) {
this.value = value;
}
/**
* Returns the value of the item.
*
* @return The value.
*/
public String getValue() {
return value;
}
/**
* Returns the next list item.
*
* @return The next list item.
*/
public ListItem getNext() {
return next;
}
/**
* Sets the next list item.
*
* @param next The next list item.
*/
public void setNext(ListItem next) {
this.next = next;
}
}
+78
View File
@@ -0,0 +1,78 @@
/**
* Tests the tasks.
*
* @author Marcus
*/
public class Main {
public static void main(String[] args) {
// test the student class
Person student1 = new Student("Schweinsteiger", 33);
Person student2 = new Student("Mueller", 7);
Person student3 = new Student("Ronaldo", 7);
System.out.println("getName(): Schweinsteiger");
System.out.println("Your code: " + student1.getName());
System.out.println();
System.out.println(" getId(): 33");
System.out.println("Your code: " + student1.getId());
System.out.println();
System.out.println(" equals(): true");
System.out.println("Your code: " + student1.equals(student1));
System.out.println(" equals(): true");
System.out.println("Your code: " + student2.equals(student3));
System.out.println(" equals(): false");
System.out.println("Your code: " + student1.equals(student3));
// test the average operation
double[] values = new double[] { 1, 2, 3 };
System.out.println();
System.out.println("average(): 2.0");
System.out.println("Your code: " + Operation.average(values));
System.out.println("average(): IllegalArgumentException");
try {
Operation.average(null);
System.out.println("Your code: no exception" );
} catch (Exception e) {
System.out.println("Your code: " + e.getClass().getSimpleName());
}
System.out.println("average(): IllegalArgumentException");
try {
Operation.average(new double[0]);
System.out.println("Your code: no exception" );
} catch (Exception e) {
System.out.println("Your code: " + e.getClass().getSimpleName());
}
// test the list implementation
System.out.println();
LinkedList list = new LinkedList();
String[] entries = new String[] { "a", "b", "c" };
for (int i = entries.length - 1; i >= 0; i--) {
list.prepend(entries[i]);
System.out.println("prepend(): " + entries[i]);
System.out.println(" size(): " + (entries.length - i));
System.out.println("Your code: " + list.size());
}
for (int i = 0; i < entries.length; i++) {
System.out.println(" get(" + i + "): " + entries[i]);
System.out.println("Your code: " + list.get(i));
}
System.out.println(" get(-1): IllegalArgumentException");
try {
list.get(-1);
System.out.println("Your code: no exception" );
} catch (Exception e) {
System.out.println("Your code: " + e.getClass().getSimpleName());
}
System.out.println(" get(10): IllegalArgumentException");
try {
list.get(10);
System.out.println("Your code: no exception" );
} catch (Exception e) {
System.out.println("Your code: " + e.getClass().getSimpleName());
}
}
}
+22
View File
@@ -0,0 +1,22 @@
/**
* A class containing an operation on an array.
*
* @author Marcus
*/
public class Operation {
/**
* Computes the average of the values.
*
* @param values The values.
* @return The average of the values.
* @throws IllegalArgumentException Thrown if the values are null or
* if there are no values in the array.
*/
public static double average(double[] values) {
// TODO: implement
return -1;
}
}
+22
View File
@@ -0,0 +1,22 @@
/**
* An interface for persons that have a name and an id.
*
* @author Marcus
*/
public interface Person {
/**
* The id of the person.
*
* @return The id.
*/
long getId();
/**
* The name of the person.
*
* @return The name.
*/
String getName();
}
+43
View File
@@ -0,0 +1,43 @@
/**
* Represents a student with an id and a name.
*
* @author Marcus
*/
public class Student { // TODO: change type hierarchy
/**
* The student name.
*/
// TODO: field
/**
* The student id.
*/
// TODO: field
/**
* Creates a new student with a specified name and id.
*
* @param name The name of the student.
* @param id The id of the student.
*/
// TODO: constructor
/**
* Returns the name of the student.
*
* @return The name of the student.
*/
// TODO: getter
/**
* Returns the id of the student.
*
* @return The id of the student.
*/
// TODO: getter
// TODO: override equals
}
+365
View File
@@ -0,0 +1,365 @@
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test;
public class Tests {
public static void main(String[] args) {
Tests test = new Tests();
System.out.println(test.getClass().getName());
System.out.println();
for (Method method : test.getClass().getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
int size = test.points.size();
try {
method.invoke(test);
if (test.points.size() != size + 1) {
System.err.println("Der Test " + method.getAnnotation(Test.class).name()
+ " lieferte kein oder mehrere Ergebnisse.");
} else {
System.out.println("Punkte: " + test.points.get(test.points.size() - 1) + " ("
+ method.getAnnotation(Test.class).name() + ")");
}
} catch (Exception e) {
System.err.println(
"Der Test " + method.getAnnotation(Test.class).name() + " lieferte ein Exception.");
e.printStackTrace();
}
}
}
System.out.println();
System.out.println("Summe: " + test.getResult());
}
@Test(name = "Student - Interface - 10")
public void testStudentInterface() {
int points = 0;
if (implementsInterface(Student.class, Person.class)) {
points += 10;
} else {
TracingFramework.printError("Student does not implement Person.");
}
addPoints(points);
}
@Test(name = "Student - Variables - 10")
public void testStudentVariables() {
int points = 0;
if (hasVariableOfType(Student.class, "name", String.class)) {
points += 3;
if (hasPrivateVariable(Student.class, "name")) {
points += 2;
} else {
TracingFramework.printError("Student.name should be private.");
}
} else {
TracingFramework.printError("Student should contain String field name.");
}
if (hasVariableOfType(Student.class, "id", long.class)) {
points += 3;
if (hasPrivateVariable(Student.class, "id")) {
points += 2;
} else {
TracingFramework.printError("Student.id should be private.");
}
} else {
TracingFramework.printError("Student should contain long field id.");
}
addPoints(points);
}
@Test(name = "Student - Getters - 10")
public void testStudentGetters() {
int points = 0;
Student s = new Student("Max Mustermann", 42);
if (s.getId() == 42) {
points += 5;
} else {
TracingFramework.printError("Student.getId() does not return the value passed into the constructor.");
}
if ("Max Mustermann".equals(s.getName())) {
points += 5;
} else {
TracingFramework.printError("Student.getName() does not return the value passed into the constructor.");
}
addPoints(points);
}
@Test(name = "Student - Equals - 10")
public void testStudentEquals() {
int points = 0;
Student a = new Student("a", 1);
Student b = new Student("b", 2);
Student c = new Student("c", 1);
if (a.equals(a) && a.equals(c) && !a.equals(b)) {
points += 7;
} else {
TracingFramework.printError("Student.equals() does not work right.");
}
try {
if (!a.equals("hello")) {
points += 3;
} else {
TracingFramework.printError("Student.equals() does not work for string.");
}
} catch (Exception e) {
TracingFramework
.printError("Student.equals() throws an exception for string: " + e.getClass().getSimpleName());
}
addPoints(points);
}
@Test(name = "Operation - average - 10")
public void testOperationAverage() {
int points = 0;
double[] values = new double[] { 1, 2, 3, 4, 5 };
double expect = 3;
double actual = Operation.average(values);
if (expect == actual) {
points += 10;
} else {
TracingFramework.printError("average([1, 2, 3, 4, 5]) should be 3 but was " + actual);
}
addPoints(points);
}
@Test(name = "Operation - average - null - 5")
public void testOperationAverageNull() {
int points = 0;
try {
Operation.average(null);
TracingFramework.printError("average(null) should throw IllegalArgumentException but did not.");
} catch (IllegalArgumentException e) {
points += 5;
} catch (Exception e) {
TracingFramework.printError(
"average(null) should throw IllegalArgumentException but threw: " + e.getClass().getSimpleName());
}
addPoints(points);
}
@Test(name = "Operation - average - empty - 5")
public void testOperationAverageEmpty() {
int points = 0;
try {
Operation.average(new double[] {});
TracingFramework.printError("average(new double[]{}) should throw IllegalArgumentException but did not.");
} catch (IllegalArgumentException e) {
points += 5;
} catch (Exception e) {
TracingFramework.printError(
"average(new double[]{}) should throw IllegalArgumentException but threw: "
+ e.getClass().getSimpleName());
}
addPoints(points);
}
@Test(name = "LinkedList - size - 10")
public void testLinkedListSize() {
int points = 0;
LinkedList list = new LinkedList() { // Added to not penalise students having only implemented size
public void prepend(String value) {
try {
Field f = LinkedList.class.getDeclaredField("head");
f.setAccessible(true);
ListItem head = (ListItem) f.get(this);
ListItem item = new ListItem(value);
item.setNext(head);
f.set(this, item);
} catch (Exception e) {
e.printStackTrace();
}
}
};
for (int i = 0; i < 10; i++) {
int size = list.size();
if (size == i) {
points += 1;
} else {
TracingFramework.printError("Size should be " + i + " but was " + size + ".");
}
list.prepend("xx");
}
addPoints(points);
}
@Test(name = "LinkedList - prepend - 10")
public void testLinkedListPrepend() {
int points = 0;
LinkedList list = new LinkedList() { // Added to not penalise students having only implemented prepend
public int size() {
try {
Field f = LinkedList.class.getDeclaredField("head");
f.setAccessible(true);
ListItem current = (ListItem) f.get(this);
int size = 0;
while (current != null) {
current = current.getNext();
size += 1;
}
return size;
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
};
for (int i = 0; i < 10; i++) {
int size = list.size();
if (size == i) {
points += 1;
} else {
TracingFramework.printError("Size should be " + i + " but was " + size + ".");
}
list.prepend("xx");
}
addPoints(points);
}
@Test(name = "LinkedList - get - 10")
public void testLinkedListGet() {
int points = 0;
LinkedList list = new LinkedList() { // Added to not penalise students having only implemented get
public void prepend(String value) {
try {
Field f = LinkedList.class.getDeclaredField("head");
f.setAccessible(true);
ListItem head = (ListItem) f.get(this);
ListItem item = new ListItem(value);
item.setNext(head);
f.set(this, item);
} catch (Exception e) {
e.printStackTrace();
}
}
};
for (int i = 9; i >= 0; i--) {
list.prepend("test" + i);
}
for (int i = 0; i < 10; i++) {
try {
String s = list.get(i);
if (s == null || !s.equals("test" + i)) {
TracingFramework.printError("Get is not test" + i + " but " + s);
} else {
points += 1;
}
} catch (Exception e) {
TracingFramework.printError("Get throws exception: " + e.getClass().getSimpleName());
}
}
addPoints(points);
}
@Test(name = "LinkedList - get - Exceptions - 10")
public void testLinkedListGetExceptions() {
int points = 0;
LinkedList list = new LinkedList();
try {
list.get(-1);
TracingFramework.printError("Get -1 does not throw an exception.");
} catch (IllegalArgumentException e) {
points += 5;
} catch (Exception e) {
TracingFramework.printError("Get -1 does not throw the right exception: " + e.getClass().getSimpleName());
}
try {
list.get(10);
TracingFramework.printError("Get 10 does not throw an exception.");
} catch (IllegalArgumentException e) {
points += 5;
} catch (Exception e) {
TracingFramework.printError("Get 10 does not throw the right exception: " + e.getClass().getSimpleName());
}
addPoints(points);
}
/**
* The points of each test case.
*/
private List<Integer> points = new ArrayList<>();
/**
* This method will be called by jack after all
* test have been executed to get the resulting
* points.
*
* @return The points resulting from the test.
*/
public int getResult() {
int sum = 0;
for (Integer p : points) {
sum += p;
}
return sum;
}
/**
* Adds points for a test case. This class assumes
* that the method is called <b>exactly</b> once
* per test case.
*
* @param value The points to add.
*/
protected void addPoints(int value) {
points.add(value);
}
public static boolean implementsInterface(Class<?> clazz, Class<?> interfaceClass) {
Class<?>[] interfaces = clazz.getInterfaces();
return Arrays.stream(interfaces).anyMatch(interfaceClass::equals);
}
public static boolean hasVariableOfType(Class<?> clazz, String fieldName, Class<?> fieldType) {
try {
Field field = clazz.getDeclaredField(fieldName);
return field.getType().equals(fieldType);
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public static boolean hasPrivateVariable(Class<?> clazz, String fieldName) {
try {
Field field = clazz.getDeclaredField(fieldName);
return Modifier.isPrivate(field.getModifiers());
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
+58
View File
@@ -0,0 +1,58 @@
public class Book
{
private String title;
private Person author;
private int yearOfPublication;
public Book (String title, Person author, int yearOfPublication) {
this.title = title;
this.author = author;
this.yearOfPublication = yearOfPublication;
}
public String getInfo() {
// --> Hier die Lösung zu Aufgabe 1 eintragen. <--
return "Hier muss was geändert werden.";
}
public int getAge() {
// --> Hier die Lösung zu Aufgabe 2 eintragen. <--
return 0;
}
// Diese Methode ist für Euch zum Testen eures Codes gedacht.
public static void main(String[] args) {
// Hier werden zunächst zwei Personen erzeugt:
Person adams = new Person("Douglas", "Adams");
Person tolkien = new Person("J. R. R.", "Tolkien");
// Dann werden zwei Bücher mit den obigen Personen als Autoren erzeugt.
Book hitchhikersGuide = new Book("The Hitchhiker's Guide to the Galaxy", adams, 1979);
Book lordOfTheRings = new Book("The Lord of the Rings",tolkien,1954);
// Und hier werden die beiden Bücher auf der Konsole ausgegeben.
System.out.println("--- Test der Methode getInfo() ---");
System.out.println("- The Hitchhiker's Guide to the Galaxy");
System.out.println(" Erwartete Ausgabe: Douglas Adams: The Hitchhiker's Guide to the Galaxy (1979)");
System.out.println(" Deine Ausgabe: " + hitchhikersGuide.getInfo());
System.out.println();
System.out.println("- Lord of the Rings ---");
System.out.println(" Erwartete Ausgabe: J. R. R. Tolkien: The Lord of the Rings (1954)");
System.out.println(" Deine Ausgabe: " + lordOfTheRings.getInfo());
System.out.println();
// Zum Schluss wird noch das Berechnen des Alters getestet.
System.out.println("--- Test der Methode getAge() ---");
System.out.println("- The Hitchhiker's Guide to the Galaxy");
System.out.println(" Erwartete Ausgabe: 37");
System.out.println(" Deine Ausgabe: " + hitchhikersGuide.getAge());
System.out.println();
System.out.println("- Lord of the Rings");
System.out.println(" Erwartete Ausgabe: 62");
System.out.println(" Deine Ausgabe: " + lordOfTheRings.getAge());
System.out.println();
}
}
+27
View File
@@ -0,0 +1,27 @@
public class Person
{
private String firstName;
private String surname;
public Person(String firstName, String surname) {
this.firstName = firstName;
this.surname = surname;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
+76
View File
@@ -0,0 +1,76 @@
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test;
public class Tests {
private int points = 0;
public int getResult() {
return points;
}
private int testBook(String title, Person author, int yearOfPublication) {
Book b = new Book(title, author, yearOfPublication);
final String firstName = author.getFirstName();
final String surname = author.getSurname();
final String info = b.getInfo();
final String perfectMatch = firstName + " " + surname + ": " + title + " (" + yearOfPublication + ")";
if (info != null && perfectMatch.equals(info))
return 40;
TracingFramework.printError("Die erwartete Ausgabe ist: " + perfectMatch
+ " , aber deine Ausgabe ist: " + info);
if (info == null)
return 0;
String whiteSpaceMessed = "\s*" + firstName + "\s*" + surname + "\s*\:\s*" + title + "\s*\(\s*"
+ yearOfPublication + "\s*\)\s*";
if (info.matches(whiteSpaceMessed)) {
TracingFramework.printError("Die Ausgabe hat eine fehlerhafte Anzahl von whitespaces");
return 39;
}
String rightOrderWithoutSpecialChars = ".*" + firstName + ".*" + surname + ".*" + title + ".*"
+ yearOfPublication + ".*\).*";
if (info.matches(rightOrderWithoutSpecialChars)) {
TracingFramework.printError("Die Ausgabe gibt die gewollten Eigenschaften nur in der richtigen Reihenfolge aus.");
return 30;
}
return (info.contains(firstName) ? 5 : 0) +
(info.contains(surname) ? 5 : 0) +
(info.contains(title) ? 5 : 0) +
(info.contains(Integer.toString(yearOfPublication)) ? 5 : 0);
}
@Test(name = "Testfall 1")
public void test1() {
points += testBook(
"The Hitchhiker's Guide to the Galaxy",
new Person("Douglas", "Adams"),
1979);
}
@Test(name = "Testfall 2")
public void test2() {
points += testBook(
"Romeo and Juliet",
new Person("William", "Shakespeare"),
1597);
}
@Test(name = "Testfall 3")
public void test3() {
Person author = new Person("A", "B");
final int yearOfPublication = 1981;
Book b = new Book("Title", author, yearOfPublication);
if (b.getAge() == 2016 - yearOfPublication)
points += 20;
else
TracingFramework.printError("Die getAge() Methode errechnet nicht das korrekte Alter. Sie gibt "
+ b.getAge() + " für ein " + yearOfPublication + " erschienenes Buch zurück.");
}
}
+85
View File
@@ -0,0 +1,85 @@
import java.util.Arrays;
public class Testat1A {
public static int computeWithSwitch(int value) {
switch (value) {
case 1:
case 2:
case 4:
return value;
default:
return 0;
}
}
public static int computeWithIf(int value) {
// TODO: implement Aufgabe 1
return 0;
}
public static void fillWithFor(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = i * 2;
}
}
public static void fillWithWhile(int[] array) {
// TODO: implement Aufgabe 2
}
public static int minArray(int[] array) {
// TODO: implement Aufgabe 3
return 0;
}
public static int[] sumRows(int[][] array) {
// TODO: implement Aufgabe 4
return new int[0];
}
public static void main(String[] args) {
System.out.println("Aufgabe 1");
System.out.println("-----");
System.out.println("Eingabewert: 1\tErwartete Ausgabe: 1\tIhre Ausgabe: " + computeWithIf(1));
System.out.println("Eingabewert: 2\tErwartete Ausgabe: 2\tIhre Ausgabe: " + computeWithIf(2));
System.out.println("Eingabewert: 3\tErwartete Ausgabe: 0\tIhre Ausgabe: " + computeWithIf(3));
System.out.println("Eingabewert: 4\tErwartete Ausgabe: 4\tIhre Ausgabe: " + computeWithIf(4));
System.out.println("Eingabewert: 5\tErwartete Ausgabe: 0\tIhre Ausgabe: " + computeWithIf(5));
System.out.println();
System.out.println("Aufgabe 2");
System.out.println("-----");
int[] array = new int[] {7, 2, 5};
fillWithWhile(array);
System.out.println("Eingabearray: [7, 2, 5]");
System.out.println("Erwartete Ausgabe: [0, 2, 4]");
System.out.println("Ihre Ausgabe: " + Arrays.toString(array));
System.out.println();
array = new int[] {9, 1, 0, 7, 9};
fillWithWhile(array);
System.out.println("Eingabearray: [9, 1, 0, 7, 9]");
System.out.println("Erwartete Ausgabe: [0, 2, 4, 6, 8]");
System.out.println("Ihre Ausgabe: " + Arrays.toString(array));
System.out.println();
System.out.println("Aufgabe 3");
System.out.println("-----");
array = new int[] {5, 2, 4, 7, 1, 9};
System.out.println("Eingabearray: [5, 2, 4, 7, 1, 9]");
System.out.println("Erwartete Ausgabe: 1");
System.out.println("Ihre Ausgabe: " + minArray(array));
System.out.println();
System.out.println("Aufgabe 4");
System.out.println("-----");
int[][] array2 = new int[][] { {5, 2, 4}, {7, 1, 9}, {3, 0, 6}};
System.out.println("Eingabearray:\n[5, 7, 3]\n[2, 1, 0]\n[4, 9, 6]");
System.out.println("Erwartete Ausgabe:\n[15, 3, 19]");
System.out.println("Ihre Ausgabe:\n" + Arrays.toString(sumRows(array2)));
System.out.println();
}
}
File diff suppressed because it is too large Load Diff
+82
View File
@@ -0,0 +1,82 @@
import java.util.Arrays;
public class Testat1B {
public static int computeWithIf(int value) {
if (value == 1 || value == 2 || value == 4) {
return value;
} else {
return 0;
}
}
public static int computeWithSwitch(int value) {
// TODO: implement Aufgabe 1
return 0;
}
public static void fillWithWhile(int[] array) {
int i = 0;
while (i < array.length) {
array[i] = i * 2;
i += 1;
}
}
public static void fillWithFor(int[] array) {
// TODO: implement Aufgabe 2
}
public static int maxArray(int[] array) {
// TODO: implement Aufgabe 3
return 0;
}
public static int[] sumColumns(int[][] array) {
// TODO: implement Aufgabe 4
return new int[0];
}
public static void main(String[] args) {
System.out.println("Aufgabe 1");
System.out.println("-----");
System.out.println("Eingabewert: 1\tErwartete Ausgabe: 1\tIhre Ausgabe: " + computeWithSwitch(1));
System.out.println("Eingabewert: 2\tErwartete Ausgabe: 2\tIhre Ausgabe: " + computeWithSwitch(2));
System.out.println("Eingabewert: 3\tErwartete Ausgabe: 0\tIhre Ausgabe: " + computeWithSwitch(3));
System.out.println("Eingabewert: 4\tErwartete Ausgabe: 4\tIhre Ausgabe: " + computeWithSwitch(4));
System.out.println("Eingabewert: 5\tErwartete Ausgabe: 0\tIhre Ausgabe: " + computeWithSwitch(5));
System.out.println();
System.out.println("Aufgabe 2");
System.out.println("-----");
int[] array = new int[] {7, 2, 5};
fillWithFor(array);
System.out.println("Eingabearray: [7, 2, 5]");
System.out.println("Erwartete Ausgabe: [0, 2, 4]");
System.out.println("Ihre Ausgabe: " + Arrays.toString(array));
System.out.println();
array = new int[] {9, 1, 0, 7, 9};
fillWithFor(array);
System.out.println("Eingabearray: [9, 1, 0, 7, 9]");
System.out.println("Erwartete Ausgabe: [0, 2, 4, 6, 8]");
System.out.println("Ihre Ausgabe: " + Arrays.toString(array));
System.out.println();
System.out.println("Aufgabe 3");
System.out.println("-----");
array = new int[] {5, 2, 4, 7, 9, 1};
System.out.println("Eingabearray: [5, 2, 4, 7, 9, 1]");
System.out.println("Erwartete Ausgabe: 9");
System.out.println("Ihre Ausgabe: " + maxArray(array));
System.out.println();
System.out.println("Aufgabe 4");
System.out.println("-----");
int[][] array2 = new int[][] { {5, 2, 4}, {7, 1, 9}, {3, 0, 6}};
System.out.println("Eingabearray:\n[5, 7, 3]\n[2, 1, 0]\n[4, 9, 6]");
System.out.println("Erwartete Ausgabe:\n[11, 17, 9]");
System.out.println("Ihre Ausgabe:\n" + Arrays.toString(sumColumns(array2)));
System.out.println();
}
}
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
public class Cheese { // TODO: change
/**
* Creates a new cheese with the weight, name and color.
*
* @param weight The weight.
* @param name The name.
* @param color The color.
*/
// TODO: constructor
// TODO: toString
}
+143
View File
@@ -0,0 +1,143 @@
public class Fridge { // TODO: change
/**
* The current items in the fridge.
*/
private FridgeItem[] items = new FridgeItem[0];
/**
* The maximum items to place in the fridge.
*/
private int maxItems;
/**
* The maximum weight of the items in the fridge.
* The sum of the weights of the items in the
* fridge must not be higher than this.
*/
private double maxWeight;
/**
* Creates a fridge that can support the specified
* number of items with the specified total
* maximum weight.
*
* @param maxItems The maximum number of items that
* the fridge can hold.
* @param maxWeight The total maximum weight that
* the current items in the fridge may have.
*/
public Fridge(int maxItems, double maxWeight) {
this.maxItems = maxItems;
this.maxWeight = maxWeight;
}
/**
* Determines whether an item is in the fridge.
*
* @param item The item to check.
* @return True if it is in the fridge, false otherwise.
*/
public boolean containsItem(FridgeItem item) {
for (int i = 0; i < items.length; i++) {
if (items[i] == item) {
return true;
}
}
return false;
}
/**
* Adds a non-null item that is not in the fridge to
* the fridge unless there is no more space.
*
* @param item The item to add.
* @return True if the item has been added, false if
* the item is null or if there is no more space or
* if the item is already in the fridge.
*/
public boolean addItem(FridgeItem item) { // TODO: add more checks
// check invalid states
if (item == null) { // Cannot add null item, sorry
return false;
}
if (items.length == maxItems) { // Cannot add more items to the fridge
return false;
}
// all checks ok, add the item
FridgeItem[] newItems = new FridgeItem[items.length + 1];
for (int j = 0; j < items.length; j++) {
newItems[j] = items[j];
}
newItems[items.length] = item;
items = newItems;
return true;
}
/**
* Recursively searches an item with a specified name in
* the item array (from startIndex to items.length - 1)
* and if present, returns the lowest index of such an item.
* If no such item exists, the method returns -1.
*
* @param name The name of the item to search.
* @param startIndex The index to start from (0 <= startIndex < items.length).
* @return If found, the index of the first item in the items
* array with the specified name when starting to search from
* startIndex to items.length - 1. If no such item exists, the
* method returns -1.
*/
public int indexOf(String name, int startIndex) {
// TODO: implement
return -2;
}
// Other helper methods, not needed for this task.
/**
* Removes an item from the fridge and returns if something
* has actually been removed.
*
* @param item The item to remove.
* @return True if the item was removed, false if the item was
* not in the fridge.
*/
public boolean removeItem(FridgeItem item) {
// search for the item on the fridge
for (int i = 0; i < items.length; i++) {
if (items[i] == item) {
// if found, create a copy of the items without it
FridgeItem[] newItems = new FridgeItem[items.length - 1];
for (int j = 0; j < newItems.length; j++) {
if (j < i) {
newItems[j] = items[i];
} else {
newItems[j] = items[i + 1];
}
}
// and replace the old items with the new ones
items = newItems;
return true;
}
}
return false;
}
@Override
public String toString() {
String result = "";
for (int i = 0; i < items.length; i++) {
result += items[i].toString() + "\n";
}
if (this instanceof Weightful) {
result += "Weigth: " + ((Weightful) this).getWeight() + " kg";
}
return result;
}
}
+53
View File
@@ -0,0 +1,53 @@
public abstract class FridgeItem { // TODO: change
/**
* The weight of the item.
*/
// TODO: add variable
/**
* The name of the item.
*/
// TODO: add variable
/**
* The color of the item.
*/
// TODO: add variable
/**
* Creates a fridge item with the specified weight, name and color.
*
* @param weight The weight of the item.
* @param name The name of the item.
* @param color The color of the item.
*/
public FridgeItem(double weight, String name, String color) {
// TODO: assign member variables
}
/**
* Returns the name of the item.
*
* @return The name of the item.
*/
public String getName() {
return name;
}
/**
* Returns the color of the item.
*
* @return The color of the item.
*/
public String getColor() {
return color;
}
// TODO: toString
}
+81
View File
@@ -0,0 +1,81 @@
/**
* A class with a main method to test the results.
*
* DOESN'T include all tests executed by JACK!
*/
public class Main {
public static void main(String[] args) {
// create items
FridgeItem gouda = new Cheese(500.5, "Gouda", "yellow");
FridgeItem cheddar = new Cheese(1123.75, "Cheddar", "orange");
FridgeItem cherryYoghurt = new Yoghurt(250, "Cherry", "red");
FridgeItem vanillaYoghurt = new Yoghurt(500, "Vanilla", "light yellow");
// create fridge
Fridge fridge = new Fridge(4, 2000.0);
fridge.addItem(cheddar);
fridge.addItem(vanillaYoghurt);
// toString - Aufgabe 1
System.out.println("Expected (Cheese.toString()): Cheese: Cheddar (orange 1123.75 g)");
System.out.println("Your code (Cheese.toString()): " + cheddar.toString());
System.out.println();
System.out.println("Expected (Yoghurt.toString()): Yoghurt: Vanilla (light yellow 500.0 g)");
System.out.println("Your code (Yoghurt.toString()): " + vanillaYoghurt.toString());
System.out.println();
// getWeight - Aufgabe 2
System.out.println("Expected (Fridge.getWeight()): 1623.75");
System.out.print("Your code (Fridge.getWeight()): ");
if (fridge instanceof Weightful) {
System.out.println(((Weightful) fridge).getWeight());
} else {
System.out.println("Missing.");
}
System.out.println();
// addItem - Aufgabe 2
System.out.println("Testing Fridge.addItem()");
boolean addCheddarAgain = fridge.addItem(cheddar);
if (addCheddarAgain) {
System.out.println("Failure: The cheddar should not be added twice.");
} else {
System.out.println("Success: The cheddar was not added again.");
}
boolean addGouda = fridge.addItem(gouda);
if (addGouda) {
System.out.println("Failure: The gouda should be too heavy.");
} else {
System.out.println("Success: The gouda is too heavy.");
}
if (fridge.containsItem(gouda)) {
System.out.println("Failure: The gouda should not be added.");
} else {
System.out.println("Success: The fridge does not contain the gouda.");
}
boolean addCherryYoghurt = fridge.addItem(cherryYoghurt);
if (addCherryYoghurt) {
System.out.println("Success: The cherry yoghurt fits in the fridge.");
} else {
System.out.println("Failure: The cherry yoghurt should fit in the fridge.");
}
if (fridge.containsItem(cherryYoghurt)) {
System.out.println("Success: The fridge contains the cherry yoghurt.");
} else {
System.out.println("Failure: The fridge does not contain the cherry yoghurt.");
}
System.out.println();
// indexOf - Aufgabe 2
System.out.println("Testing: Fridge.indexOf()");
System.out.println("Fridge.indexOf(cheddar.getName(), 0) Expected: 0, Your code: " + fridge.indexOf(cheddar.getName(), 0));
System.out.println("Fridge.indexOf(cheddar.getName(), 1) Expected: -1, Your code: " + fridge.indexOf(cheddar.getName(), 1));
System.out.println("Fridge.indexOf(cheddar.getName(), 2) Expected: -1, Your code: " + fridge.indexOf(cheddar.getName(), 2));
System.out.println("Fridge.indexOf(cherryYoghurt.getName(), 0) Expected: 2, Your code: " + fridge.indexOf(cherryYoghurt.getName(), 0));
fridge.addItem(new Yoghurt(50.5, "Cherry", "red")); // add same name to check ordering
System.out.println("Fridge.indexOf(cherryYoghurt.getName(), 0) Expected: 2, Your code: " + fridge.indexOf(cherryYoghurt.getName(), 0));
}
}
File diff suppressed because it is too large Load Diff
+10
View File
@@ -0,0 +1,10 @@
public interface Weightful {
/**
* The weight of the object.
*
* @return The weight of the object.
*/
double getWeight();
}
+15
View File
@@ -0,0 +1,15 @@
public class Yoghurt { // TODO: change
/**
* Creates a new yoghurt with the weight, name and color.
*
* @param weight The weight.
* @param name The name.
* @param color The color.
*/
// TODO: constructor
// TODO: toString
}
+10
View File
@@ -0,0 +1,10 @@
public interface Lasting {
/**
* The duration of the object.
*
* @return The duration of the object.
*/
int getDuration();
}
+88
View File
@@ -0,0 +1,88 @@
/**
* A class with a main method to test the results.
*
* DOESN'T include all tests executed by JACK!
*/
public class Main {
/**
* Runs some test cases against the media library.
*
* @param args Ignored.
*/
public static void main(String[] args) {
// create items
MediaItem longMovie = new Movie(241, "The Lord of the Rings", 5);
MediaItem shortMovie = new Movie(109, "Deadpool", 42);
MediaItem shortSeries = new Series(1230, "SpongeBob", 7);
MediaItem longSeries = new Series(2930, "Breaking Bad", 4);
// create media library
MediaLibrary mediaLibrary = new MediaLibrary(4, 2000);
mediaLibrary.addItem(shortSeries);
mediaLibrary.addItem(longMovie);
// toString - Aufgabe 1
System.out.println("Expected (Movie.toString()): Movie: The Lord of the Rings (5 241 min)");
System.out.println("Your code (Movie.toString()): " + longMovie.toString());
System.out.println();
System.out.println("Expected (Series.toString()): Series: SpongeBob (7 1230 min)");
System.out.println("Your code (Series.toString()): " + shortSeries.toString());
System.out.println();
// getWeight - Aufgabe 2
System.out.println("Expected (MediaLibrary.getDuration()): 1471");
System.out.print("Your code (MediaLibrary.getDuration()): ");
if (mediaLibrary instanceof Lasting) {
System.out.println(((Lasting) mediaLibrary).getDuration());
} else {
System.out.println("Missing.");
}
System.out.println();
// addItem - Aufgabe 2
System.out.println("Testing MediaLibrary.addItem()");
boolean addLongMovieAgain = mediaLibrary.addItem(longMovie);
if (addLongMovieAgain) {
System.out.println("Failure: The long movie should not be added twice.");
} else {
System.out.println("Success: The long movie was not added again.");
}
boolean addLongSeries = mediaLibrary.addItem(longSeries); // add item (241 + 1230 + 2930) --> too long
if (addLongSeries) {
System.out.println("Failure: The long series should be too long to add.");
} else {
System.out.println("Success: The long series is too long to add.");
}
if (mediaLibrary.containsItem(longSeries)) {
System.out.println("Failure: The long series should not be added.");
} else {
System.out.println("Success: The media library does not contain the long series.");
}
boolean addShortMovie = mediaLibrary.addItem(shortMovie); // add item --> should fit
if (addShortMovie) {
System.out.println("Success: The short movie was added.");
} else {
System.out.println("Failure: The short movie should fit into the media library.");
}
if (mediaLibrary.containsItem(shortMovie)) {
System.out.println("Success: The media library contains the short movie.");
} else {
System.out.println("Failure: The media library does not contain the short movie.");
}
System.out.println();
// lastIndexOf - Aufgabe 2
System.out.println("Testing MediaLibrary.lastIndexOf()");
System.out.println("MediaLibrary.lastIndexOf(longMovie.getTitle(), 0) Expected: -1, Your code: " + mediaLibrary.lastIndexOf(longMovie.getTitle(), 0));
System.out.println("MediaLibrary.lastIndexOf(longMovie.getTitle(), 1) Expected: 1, Your code: " + mediaLibrary.lastIndexOf(longMovie.getTitle(), 1));
System.out.println("MediaLibrary.lastIndexOf(longMovie.getTitle(), 2) Expected: 1, Your code: " + mediaLibrary.lastIndexOf(longMovie.getTitle(), 2));
System.out.println("MediaLibrary.lastIndexOf(shortMovie.getTitle(), 2) Expected: 2, Your code: " + mediaLibrary.lastIndexOf(shortMovie.getTitle(), 2));
mediaLibrary.addItem(new Movie(100, "Deadpool", 42)); // add same title to check ordering
System.out.println("MediaLibrary.lastIndexOf(shortMovie.getTitle(), 3) Expected: 3, Your code: " + mediaLibrary.lastIndexOf(shortMovie.getTitle(), 3));
}
}
+53
View File
@@ -0,0 +1,53 @@
public abstract class MediaItem { // TODO: change
/**
* The duration of the item.
*/
// TODO: add variable
/**
* The title of the item.
*/
// TODO: add variable
/**
* The views of the item.
*/
// TODO: add variable
/**
* Creates a media library item.
*
* @param title The title of the item.
* @param duration The duration of the item.
*/
public MediaItem(int duration, String title, int views) {
// TODO: assign member variables
}
/**
* Returns the title of the item.
*
* @return The title of the item.
*/
public String getTitle() {
return title;
}
/**
* Returns the views of the item.
*
* @return The views of the item.
*/
public int getViews() {
return views;
}
// TODO: toString
}
+138
View File
@@ -0,0 +1,138 @@
public class MediaLibrary { // TODO: change
/**
* The current items in the media library.
*/
private MediaItem[] items = new MediaItem[0];
/**
* The maximum number of items enforced by the media library.
*/
private int maxItems;
/**
* The maximum duration enforced by the media library.
*/
private int maxDuration;
/**
* Creates a media library that can support the specified
* number of items with the specified total
* maximum duration.
*
* @param maxItems The maximum number of items that
* the media library can handle.
* @param maxDuration The total maximum duration that
* the current items may have.
*/
public MediaLibrary(int maxItems, int maxDuration) {
this.maxItems = maxItems;
this.maxDuration = maxDuration;
}
/**
* Determines whether an item is in the media library.
*
* @param item The item to check.
* @return True if it is in the media library, false otherwise.
*/
public boolean containsItem(MediaItem item) {
for (int i = 0; i < items.length; i++) {
if (items[i] == item) {
return true;
}
}
return false;
}
/**
* Adds a non-null item that is not in the media library to
* the media library unless there is no more space.
*
* @param item The item to add.
* @return True if the item has been added, false if
* the item is null or if there is no more space or
* if the item is already in the media library.
*/
public boolean addItem(MediaItem item) { // TODO: add more checks
// check invalid states
if (item == null) { // Cannot add null item, sorry
return false;
}
if (items.length == maxItems) { // Cannot add more items to the media library
return false;
}
// all checks ok, add the item
MediaItem[] newItems = new MediaItem[items.length + 1];
for (int j = 0; j < items.length; j++) {
newItems[j] = items[j];
}
newItems[items.length] = item;
items = newItems;
return true;
}
/**
* Recursively searches an item with a specified name in
* the item array (from startIndex to 0)
* and if present, returns the highest index of such an item.
* If no such item exists, the method returns -1.
*
* @param name The name of the item to search.
* @param startIndex The index to start from (0 <= startIndex < items.length).
* @return If found, the index of the last item in the array when
* starting to search from startIndex to 0.
* If no such item exists, the method returns -1.
*/
public int lastIndexOf(String title, int startIndex) {
// TODO: implement
return -2;
}
// Other helper methods, not needed for this task.
/**
* Removes an item from the media libraty and returns if something
* has actually been removed.
*
* @param item The item to remove.
* @return True if the item was removed, false if the item was
* not in the media library.
*/
public boolean removeItem(MediaItem item) {
// search for the item in the media library
for (int i = 0; i < items.length; i++) {
if (items[i] == item) {
// if found, create a copy of the items without it
MediaItem[] newItems = new MediaItem[items.length - 1];
for (int j = 0; j < newItems.length; j++) {
if (j < i) {
newItems[j] = items[i];
} else {
newItems[j] = items[i + 1];
}
}
// and replace the old items with the new ones
items = newItems;
return true;
}
}
return false;
}
@Override
public String toString() {
String result = "";
for (int i = 0; i < items.length; i++) {
result += items[i].toString() + "\n";
}
if (this instanceof Lasting) {
result += "Duration: " + ((Lasting) this).getDuration() + " s";
}
return result;
}
}
+16
View File
@@ -0,0 +1,16 @@
public class Movie { // TODO: change
/**
* Creates a new movie with the duration, title and views.
*
* @param duration The duration.
* @param title The title.
* @param views The views.
*/
// TODO: constructor
// TODO: toString
}
+16
View File
@@ -0,0 +1,16 @@
public class Series { // TODO: change
/**
* Creates a new series with the duration, title and views.
*
* @param duration The duration.
* @param title The title.
* @param views The views.
*/
// TODO: constructor
// TODO: toString
}
File diff suppressed because it is too large Load Diff
+8
View File
@@ -0,0 +1,8 @@
/**
* An (optional) class for list items.
*
* @author Marcus
*/
public class Item {
}
+47
View File
@@ -0,0 +1,47 @@
/**
* A list of strings.
*
* @author Marcus
*/
public class List {
/**
* Creates a new empty list.
*/
public List() {
super();
}
/**
* Appends a string at the end of the list.
*
* @param string The string to append.
*/
public void addLast(String string) {
// TODO: implement
}
/**
* Removes and returns the last string of
* the list. If the list is empty, the method
* returns null.
*
* @return The last string of the list or null,
* if the list ist empty.
*/
public String removeLast() {
// TODO: implement
return "ABCDEFG";
}
/**
* The number of strings in the list.
*
* @return The number of strings in the list.
*/
public int size() {
// TODO: implement
return -1;
}
}
+47
View File
@@ -0,0 +1,47 @@
import java.util.Arrays;
/**
* Runs a number of simple tests.
*
* @author Marcus
*/
public class Main {
/**
* Runs some tests.
*
* @param args Ignored.
*/
public static void main(String[] args) {
// test list
System.out.println("Creating empty list.");
List list = new List();
String[] test = new String[] { "A", "B", "C" };
for (int i = 0; i < test.length; i++) {
System.out.println("Size is " + list.size() + " should be " + i);
System.out.println("Adding " + test[i]);
list.addLast(test[i]);
}
for (int i = 0; i < test.length; i++) {
System.out.println("Size is " + list.size() + " should be " + (test.length - i));
System.out.println("Removing last element.");
String last = list.removeLast();
System.out.println("Result should be " + test[test.length - 1 - i] + " and was " + last);
}
System.out.println();
// test tree
System.out.println("Creating tree with 4 nodes: 2, 1, 3, 1");
Tree tree = new Tree();
tree.insert(2);
tree.insert(1);
tree.insert(3);
tree.insert(1);
System.out.println("Node count of 2 should be 1 and was " + tree.count(2));
System.out.println("Node count of 1 should be 2 and was " + tree.count(1));
System.out.println("Visiting all nodes in pre-order.");
TreeVisitor v = new TreeVisitor();
tree.traverse(v);
System.out.println("Sequence should be [2.0, 1.0, 1.0, 3.0] and was " + Arrays.toString(v.toArray()));
}
}
+321
View File
@@ -0,0 +1,321 @@
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test;
public class Tests {
@Test(name = "List - addLast - size - 15")
public void testListAdd() {
int points = 0;
List list = new List();
int size = list.size();
if (size != 0) {
TracingFramework.printError("A new list should have size 0 but was " + size);
} else {
points += 3;
}
try {
list.addLast("A");
size = list.size();
if (size != 1) {
TracingFramework.printError("add(\"A\") should add one element to the list");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("add(\"A\") should not throw an Exception. " + e.getClass().getName());
}
try {
list.addLast(null);
size = list.size();
if (size != 1) {
TracingFramework.printError("add(null) should not change the list");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("add(null) should not throw an Exception. " + e.getClass().getName());
}
try {
list.addLast("B");
size = list.size();
if (size != 2) {
TracingFramework.printError("add(\"B\") should add one element to the list");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("add(\"B\") should not throw an Exception. " + e.getClass().getName());
}
try {
list.addLast("");
size = list.size();
if (size != 2) {
TracingFramework.printError("add(\"\") should not add elements to the list");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("add(\"\") should not throw an Exception. " + e.getClass().getName());
}
addPoints(points);
}
@Test(name = "List - removeLast - 5")
public void testListRemoveLastEmpty() {
int points = 0;
List list = new List();
try {
String value = list.removeLast();
if (value == null) {
points += 5;
} else {
points += 2;
TracingFramework
.printError("removeLast from empty list should return null, but was: \"" + value + "\"");
}
} catch (Exception e) {
TracingFramework
.printError("removeLast from empty list should not throw an Exception. " + e.getClass().getName());
}
addPoints(points);
}
@Test(name = "List - addLast - removeLast - size - 30")
public void testList() {
int points = 0;
List list = new List();
list.addLast("A");
list.addLast("B");
list.addLast("C");
String value = list.removeLast();
int size = list.size();
if (size == 2) {
points += 5;
} else {
TracingFramework.printError("A list with 2 elements should have size 2 but was " + size);
}
if ("C".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove last of A,B,C should return C but was " + value);
}
value = list.removeLast();
size = list.size();
if (size == 1) {
points += 5;
} else {
TracingFramework.printError("A list with 1 element should have size 1 but was " + size);
}
if ("B".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove last of A,B should return B but was " + value);
}
value = list.removeLast();
size = list.size();
if (size == 0) {
points += 5;
} else {
TracingFramework.printError("A list with 0 elements should have size 0 but was " + size);
}
if ("A".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove last of A should return A but was " + value);
}
addPoints(points);
}
@Test(name = "Tree - traverse")
public void testTreeTraverse() {
int points = 0;
double[] values = new double[] { 3, 1, 5, 0, 2, 4, 6 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
double[] expect = new double[] { 3, 1, 0, 2, 5, 4, 6 };
TreeVisitor visitor = new TreeVisitor();
tree.traverse(visitor);
double[] actual = visitor.toArray();
if (Arrays.equals(actual, expect)) {
points += 25;
} else {
double[] expectSort = expect.clone();
double[] actualSort = actual.clone();
Arrays.sort(expectSort);
Arrays.sort(actualSort);
if (Arrays.equals(expectSort, actualSort)) {
points += 15;
TracingFramework.printError(
"Traversal " + Arrays.toString(actual) + " is not pre-order (point deduction) but complete.");
} else {
TracingFramework.printError("Traversal " + Arrays.toString(actual) + " is incomplete (no points).");
}
}
addPoints(points);
}
@Test(name = "Tree - count")
public void testTreeCount() {
int points = 0;
// non-sorted tree
double[] values = new double[] { 3, 1, 5, 1, 2, 4, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
// 5 should be found once
int count = tree.count(5);
if (count == 1) {
points += 6;
} else {
TracingFramework.printError("Count(5) should return 1 , but was " + count);
}
// 7 should not be found
count = tree.count(7);
if (count == 0) {
points += 6;
} else {
TracingFramework.printError("Count(7) should return 0 , but was " + count);
}
// 1 should only be found 2 (if search is efficient)
count = tree.count(1);
if (count == 2) {
points += 13;
} else if (count == 3) {
points += 5;
TracingFramework.printError("Count(1) should return 2 with efficient implementation, but was " + count);
} else {
TracingFramework.printError("Count(1) should return 2 , but was " + count);
}
addPoints(points);
}
/**
* Builds a binary tree from an array from top to bottom and left to right.
*
* @param values The values.
* @return The tree node representing the root.
*/
private TreeNode buildTree(double[] values) {
TreeNode root = new TreeNode(values[0]);
java.util.List<TreeNode> nodes = new ArrayList<>();
nodes.add(root);
for (int i = 1; i < values.length; i++) {
TreeNode parent = nodes.get(0);
TreeNode child = new TreeNode(values[i]);
nodes.add(child);
if (i % 2 == 1) {
parent.setLeft(child);
} else {
parent.setRight(child);
nodes.remove(0);
}
}
return root;
}
/**
* Sets the root in the tree.
*
* @param tree The tree.
* @param root The root to set in the tree.
*/
private void setRoot(Tree tree, TreeNode root) {
try {
Field field = Tree.class.getDeclaredField("root");
field.setAccessible(true);
field.set(tree, root);
} catch (Exception e) {
throw new RuntimeException("Failed to set root.");
}
}
/**
* The points of each test case.
*/
private java.util.List<Integer> points = new ArrayList<>();
/**
* This method will be called by jack after all test have been executed to get
* the resulting points.
*
* @return The points resulting from the test.
*/
public int getResult() {
int sum = 0;
for (Integer p : points) {
sum += p;
}
return sum;
}
/**
* Adds points for a test case. This class assumes that the method is called
* <b>exactly</b> once per test case.
*
* @param value The points to add.
*/
protected void addPoints(int value) {
points.add(value);
}
/**
* A utility method to execute any test driver class extending abstract test
* locally without going through Jack.
*
* @param test The test driver to execute.
* @throws Exception Thrown if something fails.
*/
public static void runAll() throws Exception {
Tests test = new Tests();
System.out.println(test.getClass().getName());
System.out.println();
for (Method method : test.getClass().getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
int size = test.points.size();
try {
method.invoke(test);
if (test.points.size() != size + 1) {
System.err.println("Der Test " + method.getAnnotation(Test.class).name()
+ " lieferte kein oder mehrere Ergebnisse.");
} else {
System.out.println("Punkte: " + test.points.get(test.points.size() - 1) + " ("
+ method.getAnnotation(Test.class).name() + ")");
}
} catch (Exception e) {
System.err.println(
"Der Test " + method.getAnnotation(Test.class).name() + " lieferte ein Exception.");
e.printStackTrace();
}
}
}
System.out.println();
System.out.println("Summe: " + test.getResult());
}
public static void main(String[] args) {
try {
runAll();
} catch (Exception e) {
e.printStackTrace();
}
}
}
+113
View File
@@ -0,0 +1,113 @@
/**
* An ordered binary tree.
*
* @author Marcus
*/
public class Tree {
/**
* The root node of the tree.
*/
private TreeNode root;
/**
* Creates a new and empty tree.
*/
public Tree() {
super();
}
/**
* Traverses the tree and calls the visitor's
* visit(TreeNode) method in pre-order.
*
* @param visitor The visitor whose visit method
* shall be called in pre-order.
*/
public void traverse(TreeVisitor visitor) {
traverse(visitor, root);
}
/**
* Traverses the subtree starting at current
* and calls the visitor's visit(TreeNode)
* method in pre-order.
*
* @param visitor The visitor.
* @param current The subtree to visit, may be null.
*/
private void traverse(TreeVisitor visitor, TreeNode current) {
if (current == null) return;
// TODO: implement
}
/**
* Inserts a new value into the true.
*
* @param value The value to insert.
*/
public void insert(double value) {
if (root == null) {
root = new TreeNode(value);
} else {
insert(value, root);
}
}
/**
* Recursively finds the right node to insert the
* value and inserts it.
*
* @param value The value to insert.
* @param current The current value.
*/
private void insert(double value, TreeNode current) {
if (value <= current.getValue()) {
// smaller or equal values go left
if (current.getLeft() == null) {
current.setLeft(new TreeNode(value));
} else {
insert(value, current.getLeft());
}
} else {
// larger values go right
if (current.getRight() == null) {
current.setRight(new TreeNode(value));
} else {
insert(value, current.getRight());
}
}
}
/**
* Efficiently counts the number of nodes in the
* tree that have a particular value by considering
* the order that is defined by the tree's insert
* method.
*
* @param value The value to search from.
* @return The number of nodes with the value.
*/
public int count(double value) {
return count(value, root);
}
/**
* Efficiently counts the number of nodes in the
* subtree starting at current that have a particular
* value by considering the order that is defined
* by the tree's insert method.
*
* @param value The value to search from.
* @param current The subtree to search in, may be null.
* @return The number of nodes with the value.
*/
private int count(double value, TreeNode current) {
if (current == null) return 0;
// TODO: implement
return -1;
}
}
+81
View File
@@ -0,0 +1,81 @@
/**
* A node of a binary tree.
*
* @author Marcus
*/
public class TreeNode {
/**
* The value of the node.
*/
private double value;
/**
* The left child, or null.
*/
private TreeNode left;
/**
* The right child, or null.
*/
private TreeNode right;
/**
* Creates a new tree node with
* the specified value and no
* children.
*
* @param value The value to set.
*/
public TreeNode(double value) {
this.value = value;
}
/**
* Returns the node value.
*
* @return The value of the node.
*/
public double getValue() {
return value;
}
/**
* Returns the left child or null.
*
* @return The left child or null.
*/
public TreeNode getLeft() {
return left;
}
/**
* Returns the right child or null.
*
* @return The right child or null.
*/
public TreeNode getRight() {
return right;
}
/**
* Sets the left child.
*
* @param left The new left child.
*/
public void setLeft(TreeNode left) {
this.left = left;
}
/**
* Sets the right child.
*
* @param right The new right child.
*/
public void setRight(TreeNode right) {
this.right = right;
}
}
+72
View File
@@ -0,0 +1,72 @@
import java.util.ArrayList;
import java.util.List;
/**
* A visitor to test the implementation.
*
* @author Marcus
*/
public class TreeVisitor {
/**
* The list of visited tree nodes.
*/
private List<TreeNode> visited = new ArrayList<>();
/**
* Creates a new visitor with an empty list of nodes.
*/
public TreeVisitor() {
super();
}
/**
* Returns the list with the visited nodes.
*
* @return The visited nodes.
*/
public List<TreeNode> getVisited() {
return visited;
}
/**
* Visits the tree node and adds it to the list
* of visited nodes.
*
* @param node The node to visit.
*/
public void visit(TreeNode node) {
visited.add(node);
}
/**
* Converts the visited node list into an int
* array containing the values of the nodes.
*
* @return The array with the node values.
*/
public double[] toArray() {
double[] result = new double[visited.size()];
for (int i = 0; i < result.length; i++) {
//Added null check - otherwise Jack test crash
if(visited.get(i) == null) result[i] = Integer.MAX_VALUE;
else result[i] = visited.get(i).getValue();
}
return result;
}
@Override
public String toString() {
String result = "";
for (int i = 0; i < visited.size(); i++) {
//Added null check - otherwise Jack test crash
if(visited.get(i) == null) result += "[NULL]";
else result += visited.get(i).getValue();
if (i != visited.size() - 1) {
result += ", ";
}
}
return result;
}
}
+8
View File
@@ -0,0 +1,8 @@
/**
* An (optional) class for stack items.
*
* @author Marcus
*/
public class Item {
}
+47
View File
@@ -0,0 +1,47 @@
import java.util.Arrays;
/**
* Runs a number of simple tests.
*
* @author Marcus
*/
public class Main {
/**
* Runs some tests.
*
* @param args Ignored.
*/
public static void main(String[] args) {
// test stack
System.out.println("Creating empty stack.");
Stack stack = new Stack();
String[] test = new String[] { "A", "B", "C" };
for (int i = 0; i < test.length; i++) {
System.out.println("Size is " + stack.size() + " should be " + i);
System.out.println("Adding " + test[i]);
stack.addToTop(test[i]);
}
for (int i = 0; i < test.length; i++) {
System.out.println("Size is " + stack.size() + " should be " + (test.length - i));
System.out.println("Removing element.");
String last = stack.removeFromTop();
System.out.println("Result should be " + test[test.length - 1 - i] + " and was " + last);
}
System.out.println();
// test tree
System.out.println("Creating tree with 4 nodes: 2, 1, 3, 1");
Tree tree = new Tree();
tree.insert(2);
tree.insert(1);
tree.insert(3);
tree.insert(1);
System.out.println("Node count of 2 should be 1 and was " + tree.count(2));
System.out.println("Node count of 1 should be 2 and was " + tree.count(1));
System.out.println("Visiting all nodes in post-order.");
TreeVisitor v = new TreeVisitor();
tree.traverse(v);
System.out.println("Sequence should be [3.0, 1.0, 1.0, 2.0] and was " + Arrays.toString(v.toArray()));
}
}
+51
View File
@@ -0,0 +1,51 @@
/**
* A stack of strings.
*
* @author Marcus
*/
public class Stack {
/**
* Creates a new empty stack.
*/
public Stack() {
super();
}
/**
* Adds the specified string on top
* of the stack.
*
* @param string The string to add.
*/
public void addToTop(String string) {
// TODO: implement
}
/**
* Removes and returns the string on
* top of the stack or null, if the
* stack is empty.
*
* @return The last item that has been
* pushed onto the stack or null, if
* the stack is empty.
*/
public String removeFromTop() {
// TODO: implement
return "ABCDEFG";
}
/**
* Returns the current number of
* strings on the stack.
*
* @return The current number of strings
* on the stack.
*/
public int size() {
// TODO: implement
return -1;
}
}
+326
View File
@@ -0,0 +1,326 @@
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework;
import de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework.TracingFramework.Test;
public class Tests {
@Test(name = "Stack - add - size - 15")
public void testStackAdd() {
int points = 0;
Stack stack = new Stack();
int size = stack.size();
if (size != 0) {
TracingFramework.printError("A new Stack should have size 0 but was " + size);
} else {
points += 3;
}
try {
stack.addToTop("A");
size = stack.size();
if (size != 1) {
TracingFramework.printError("addToTop(\"A\") should add one element to the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(\"A\") should not throw an Exception. " + e.getClass().getName());
}
try {
stack.addToTop(null);
size = stack.size();
if (size != 1) {
TracingFramework.printError("addToTop(null) should not change the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(null) should not throw an Exception. " + e.getClass().getName());
}
try {
stack.addToTop("B");
size = stack.size();
if (size != 2) {
TracingFramework.printError("addToTop(\"B\") should add one element to the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(\"B\") should not throw an Exception. " + e.getClass().getName());
}
try {
stack.addToTop("");
size = stack.size();
if (size != 2) {
TracingFramework.printError("addToTop(\"\") should not add elements to the stack");
} else {
points += 3;
}
} catch (Exception e) {
TracingFramework.printError("addToTop(\"\") should not throw an Exception. " + e.getClass().getName());
}
addPoints(points);
}
@Test(name = "Stack - remove - 5")
public void testStackRemove() {
int points = 0;
Stack stack = new Stack();
try {
String value = stack.removeFromTop();
if (value == null) {
points += 5;
} else {
points += 2;
TracingFramework
.printError("removeFromTop from empty stack should return null, but was: \"" + value + "\"");
}
} catch (Exception e) {
TracingFramework
.printError("removeFromTop from empty stack should not throw an Exception. " + e.getClass().getName());
}
addPoints(points);
}
@Test(name = "Stack - add - remove - size - 30")
public void testStack() {
int points = 0;
Stack stack = new Stack();
stack.addToTop("A");
stack.addToTop("B");
stack.addToTop("C");
String value = stack.removeFromTop();
int size = stack.size();
if (size == 2) {
points += 5;
} else {
TracingFramework.printError("A stack with 2 elements should have size 2 but was " + size);
}
if ("C".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove top of A,B,C should return C but was " + value);
}
value = stack.removeFromTop();
size = stack.size();
if (size == 1) {
points += 5;
} else {
TracingFramework.printError("A stack with 1 element should have size 1 but was " + size);
}
if ("B".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove top of A,B should return B but was " + value);
}
value = stack.removeFromTop();
size = stack.size();
if (size == 0) {
points += 5;
} else {
TracingFramework.printError("A stack with 0 elements should have size 0 but was " + size);
}
if ("A".equals(value)) {
points += 5;
} else {
TracingFramework.printError("Remove top of A should return A but was " + value);
}
addPoints(points);
}
@Test(name = "Tree - traverse - 25")
public void testTreeTraverse() {
int points = 0;
double[] values = new double[] { 3, 5, 1, 6, 4, 2, 0 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
double[] expect = new double[] { 6, 4, 5, 2, 0, 1, 3 };
TreeVisitor visitor = new TreeVisitor();
tree.traverse(visitor);
double[] actual = visitor.toArray();
if (Arrays.equals(actual, expect)) {
points += 25;
} else {
double[] expectSort = expect.clone();
double[] actualSort = actual.clone();
Arrays.sort(expectSort);
Arrays.sort(actualSort);
if (Arrays.equals(expectSort, actualSort)) {
points += 15;
TracingFramework.printError("Traversal " + Arrays.toString(actual)
+ " is not post-order (point deduction) but complete.");
} else {
TracingFramework.printError(
"Traversal " + Arrays.toString(actual) + " is incomplete (no points).");
}
}
addPoints(points);
}
@Test(name = "Tree - count - 25")
public void testTreeCount() {
int points = 0;
// non-sorted tree
double[] values = new double[] { 3, 5, 1, 1, 4, 2, 1 };
Tree tree = new Tree();
setRoot(tree, buildTree(values));
// 5 should be found once
int count = tree.count(5);
if (count == 1) {
points += 6;
} else {
TracingFramework.printError("Count(5) should return 1 , but was " + count);
}
// 7 should not be found
count = tree.count(7);
if (count == 0) {
points += 6;
} else {
TracingFramework.printError("Count(7) should return 0 , but was " + count);
}
// 1 should only be found 2 (if search is efficient)
count = tree.count(1);
if (count == 2) {
points += 13;
} else if (count == 3) {
points += 5;
TracingFramework.printError("Count(1) should return 2 with efficient implementation, but was " + count);
} else {
TracingFramework.printError("Count(1) should return 2 , but was " + count);
}
addPoints(points);
}
/**
* Builds a binary tree from an array from
* top to bottom and left to right.
*
* @param values The values.
* @return The tree node representing the root.
*/
private TreeNode buildTree(double[] values) {
TreeNode root = new TreeNode(values[0]);
java.util.List<TreeNode> nodes = new ArrayList<>();
nodes.add(root);
for (int i = 1; i < values.length; i++) {
TreeNode parent = nodes.get(0);
TreeNode child = new TreeNode(values[i]);
nodes.add(child);
if (i % 2 == 1) {
parent.setLeft(child);
} else {
parent.setRight(child);
nodes.remove(0);
}
}
return root;
}
/**
* Sets the root in the tree.
*
* @param tree The tree.
* @param root The root to set in the tree.
*/
private void setRoot(Tree tree, TreeNode root) {
try {
Field field = Tree.class.getDeclaredField("root");
field.setAccessible(true);
field.set(tree, root);
} catch (Exception e) {
throw new RuntimeException("Failed to set root.");
}
}
/**
* The points of each test case.
*/
private List<Integer> points = new ArrayList<>();
/**
* This method will be called by jack after all
* test have been executed to get the resulting
* points.
*
* @return The points resulting from the test.
*/
public int getResult() {
int sum = 0;
for (Integer p : points) {
sum += p;
}
return sum;
}
/**
* Adds points for a test case. This class assumes
* that the method is called <b>exactly</b> once
* per test case.
*
* @param value The points to add.
*/
protected void addPoints(int value) {
points.add(value);
}
/**
* A utility method to execute any test driver class extending
* abstract test locally without going through Jack.
*
* @param test The test driver to execute.
* @throws Exception Thrown if something fails.
*/
public static void runAll() throws Exception {
Tests test = new Tests();
System.out.println(test.getClass().getName());
System.out.println();
for (Method method : test.getClass().getMethods()) {
if (method.isAnnotationPresent(Test.class)) {
int size = test.points.size();
try {
method.invoke(test);
if (test.points.size() != size + 1) {
System.err.println("Der Test " + method.getAnnotation(Test.class).name()
+ " lieferte kein oder mehrere Ergebnisse.");
} else {
System.out.println("Punkte: " + test.points.get(test.points.size() - 1) + " ("
+ method.getAnnotation(Test.class).name() + ")");
}
} catch (Exception e) {
System.err.println(
"Der Test " + method.getAnnotation(Test.class).name() + " lieferte ein Exception.");
e.printStackTrace();
}
}
}
System.out.println();
System.out.println("Summe: " + test.getResult());
}
public static void main(String[] args) {
try {
runAll();
} catch (Exception e) {
e.printStackTrace();
}
}
}
+113
View File
@@ -0,0 +1,113 @@
/**
* An (inverse) ordered binary tree.
*
* @author Marcus
*/
public class Tree {
/**
* The root node of the tree.
*/
private TreeNode root;
/**
* Creates a new and empty tree.
*/
public Tree() {
super();
}
/**
* Traverses the tree and calls the visitor's
* visit(TreeNode) method in post-order.
*
* @param visitor The visitor whose visit method
* shall be called in post-order.
*/
public void traverse(TreeVisitor visitor) {
traverse(visitor, root);
}
/**
* Traverses the subtree starting at current
* and calls the visitor's visit(TreeNode)
* method in post-order.
*
* @param visitor The visitor.
* @param current The subtree to visit, may be null.
*/
private void traverse(TreeVisitor visitor, TreeNode current) {
if (current == null) return;
// TODO: implement
}
/**
* Inserts a new value into the true.
*
* @param value The value to insert.
*/
public void insert(double value) {
if (root == null) {
root = new TreeNode(value);
} else {
insert(value, root);
}
}
/**
* Recursively finds the right node to insert the
* value and inserts it.
*
* @param value The value to insert.
* @param current The current value.
*/
private void insert(double value, TreeNode current) {
if (value > current.getValue()) {
// larger values go left
if (current.getLeft() == null) {
current.setLeft(new TreeNode(value));
} else {
insert(value, current.getLeft());
}
} else {
// smaller or equal values go right
if (current.getRight() == null) {
current.setRight(new TreeNode(value));
} else {
insert(value, current.getRight());
}
}
}
/**
* Efficiently counts the number of nodes in the
* tree that have a particular value by considering
* the order that is defined by the tree's insert
* method.
*
* @param value The value to search from.
* @return The number of nodes with the value.
*/
public int count(double value) {
return count(value, root);
}
/**
* Efficiently counts the number of nodes in the
* subtree starting at current that have a particular
* value by considering the order that is defined
* by the tree's insert method.
*
* @param value The value to search from.
* @param current The subtree to search in, may be null.
* @return The number of nodes with the value.
*/
private int count(double value, TreeNode current) {
if (current == null) return 0;
// TODO: implement
return -1;
}
}
+81
View File
@@ -0,0 +1,81 @@
/**
* A node of a binary tree.
*
* @author Marcus
*/
public class TreeNode {
/**
* The value of the node.
*/
private double value;
/**
* The left child, or null.
*/
private TreeNode left;
/**
* The right child, or null.
*/
private TreeNode right;
/**
* Creates a new tree node with
* the specified value and no
* children.
*
* @param value The value to set.
*/
public TreeNode(double value) {
this.value = value;
}
/**
* Returns the node value.
*
* @return The value of the node.
*/
public double getValue() {
return value;
}
/**
* Returns the left child or null.
*
* @return The left child or null.
*/
public TreeNode getLeft() {
return left;
}
/**
* Returns the right child or null.
*
* @return The right child or null.
*/
public TreeNode getRight() {
return right;
}
/**
* Sets the left child.
*
* @param left The new left child.
*/
public void setLeft(TreeNode left) {
this.left = left;
}
/**
* Sets the right child.
*
* @param right The new right child.
*/
public void setRight(TreeNode right) {
this.right = right;
}
}
+72
View File
@@ -0,0 +1,72 @@
import java.util.ArrayList;
import java.util.List;
/**
* A visitor to test the implementation.
*
* @author Marcus
*/
public class TreeVisitor {
/**
* The list of visited tree nodes.
*/
private List<TreeNode> visited = new ArrayList<>();
/**
* Creates a new visitor with an empty list of nodes.
*/
public TreeVisitor() {
super();
}
/**
* Returns the list with the visited nodes.
*
* @return The visited nodes.
*/
public List<TreeNode> getVisited() {
return visited;
}
/**
* Visits the tree node and adds it to the list
* of visited nodes.
*
* @param node The node to visit.
*/
public void visit(TreeNode node) {
visited.add(node);
}
/**
* Converts the visited node list into an int
* array containing the values of the nodes.
*
* @return The array with the node values.
*/
public double[] toArray() {
double[] result = new double[visited.size()];
for (int i = 0; i < result.length; i++) {
//Added null check - otherwise Jack test crash
if(visited.get(i) == null) result[i] = Integer.MAX_VALUE;
else result[i] = visited.get(i).getValue();
}
return result;
}
@Override
public String toString() {
String result = "";
for (int i = 0; i < visited.size(); i++) {
//Added null check - otherwise Jack test crash
if(visited.get(i) == null) result += "[NULL]";
else result += visited.get(i).getValue();
if (i != visited.size() - 1) {
result += ", ";
}
}
return result;
}
}
@@ -0,0 +1,19 @@
package de.uni_due.s3.jack2.backend.checkers.tracingchecker.framework;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class TracingFramework {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Test {
String name();
}
public static void printError(String string) {
System.err.println("ERROR: " + string);
}
}