Add implementation and test classes for MasterMind, Horner, Lotto, Nimmspiel, Complex, and Polynomial

This commit is contained in:
Dominik 2025-02-20 11:42:23 +01:00
parent cdf8a508c2
commit beda36149d
12 changed files with 507 additions and 0 deletions

View file

@ -0,0 +1,53 @@
package de.dhbwka.java.exercise.classes;
public class Complex {
private double real;
private double imag;
public Complex(double real, double imag) {
this.real = real;
this.imag = imag;
}
public Complex() {
this(0, 0);
}
public double getMagnitude() {
return Math.sqrt(real * real + imag * imag);
}
public boolean isLessThan(Complex c) {
return this.getMagnitude() < c.getMagnitude();
}
public Complex add(Complex c) {
return new Complex(this.real + c.real, this.imag + c.imag);
}
public Complex sub(Complex c) {
return new Complex(this.real - c.real, this.imag - c.imag);
}
public Complex mul(Complex c) {
return new Complex(this.real * c.real - this.imag * c.imag, this.real * c.imag + this.imag * c.real);
}
public Complex div(Complex c) {
return new Complex((this.real * c.real + this.imag * c.imag) / (c.real * c.real + c.imag * c.imag),
(this.imag * c.real - this.real * c.imag) / (c.real * c.real + c.imag * c.imag));
}
public double getImag() {
return imag;
}
public double getReal() {
return real;
}
@Override
public String toString() {
return real + (imag >= 0 ? "+" : "") + imag + "i";
}
}

View file

@ -0,0 +1,26 @@
package de.dhbwka.java.exercise.classes;
public class ComplexTest {
public static void main(String[] args) {
Complex[] complexNumbers = new Complex[10];
for (int i = 0; i < complexNumbers.length; i++) {
complexNumbers[i] = new Complex(Math.floor(Math.random() * 10), Math.floor(Math.random() * 10));
}
// Bubble sort
for (int i = 0; i < complexNumbers.length; i++) {
for (int j = 0; j < complexNumbers.length - 1; j++) {
if (complexNumbers[j].isLessThan(complexNumbers[j + 1])) {
Complex temp = complexNumbers[j];
complexNumbers[j] = complexNumbers[j + 1];
complexNumbers[j + 1] = temp;
}
}
}
for (Complex complex : complexNumbers) {
System.out.println(complex);
}
}
}

View file

@ -0,0 +1,37 @@
package de.dhbwka.java.exercise.classes;
public class Horner {
private double[] coefficients;
public Horner(double[] coefficients) {
this.coefficients = coefficients;
}
public double getValue(double x) {
double result = 0;
for (int i = coefficients.length - 1; i >= 0; i--) {
result = coefficients[i] + x * result;
}
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < coefficients.length; i++) {
sb.append(coefficients[i]);
if (i > 0) {
sb.append("x^").append(i);
}
if (i < coefficients.length - 1) {
sb.append(" + ");
}
}
return sb.toString();
}
}

View file

@ -0,0 +1,11 @@
package de.dhbwka.java.exercise.classes;
public class HornerTest {
public static void main(String[] args) {
Horner h = new Horner(new double[] { 1, 2, 3, 4, 5 });
System.out.println(h.getValue(2));
System.out.println(h.getValue(3));
System.out.println(h);
}
}

View file

@ -0,0 +1,81 @@
package de.dhbwka.java.exercise.classes;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Lotto {
private int m;
private int n;
private int[] tipp;
private int[] gezogeneZahlen;
private Random random = new Random();
public Lotto(int m, int n) {
this.m = m;
this.n = n;
this.tipp = new int[m];
this.gezogeneZahlen = new int[m];
}
public void tippen() {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < m; i++) {
System.out.printf("Geben Sie bitte Ihren Tipp für die %d. Zahl ein: ", i + 1);
tipp[i] = scanner.nextInt();
while (tipp[i] < 1 || tipp[i] > n) {
System.out.printf("Ungültige Zahl. Geben Sie bitte Ihren Tipp für die %d. Zahl ein: ", i + 1);
tipp[i] = scanner.nextInt();
}
}
Arrays.sort(tipp);
scanner.close();
}
public void tippen(int[] tipp) {
if (tipp.length != m) {
throw new IllegalArgumentException("Die Länge des Tipps muss " + m + " sein.");
}
this.tipp = Arrays.copyOf(tipp, tipp.length);
Arrays.sort(this.tipp);
}
public void ziehen() {
for (int i = 0; i < m; i++) {
int zahl;
do {
zahl = random.nextInt(n) + 1;
} while (contains(gezogeneZahlen, zahl));
gezogeneZahlen[i] = zahl;
}
Arrays.sort(gezogeneZahlen);
}
public int richtige() {
int count = 0;
for (int zahl : tipp) {
if (contains(gezogeneZahlen, zahl)) {
count++;
}
}
return count;
}
private boolean contains(int[] array, int value) {
for (int i : array) {
if (i == value) {
return true;
}
}
return false;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Tipp: ").append(Arrays.toString(tipp)).append("\n");
sb.append("Gezogene Zahlen: ").append(Arrays.toString(gezogeneZahlen)).append("\n");
sb.append("Richtige: ").append(richtige());
return sb.toString();
}
}

View file

@ -0,0 +1,10 @@
package de.dhbwka.java.exercise.classes;
public class LottoTest {
public static void main(String[] args) {
Lotto deutschesLotto = new Lotto(6, 49);
deutschesLotto.tippen(new int[] { 1, 11, 17, 22, 33, 49 });
deutschesLotto.ziehen();
System.out.println(deutschesLotto);
}
}

View file

@ -0,0 +1,90 @@
package de.dhbwka.java.exercise.classes;
import java.util.Random;
import java.util.Scanner;
public class MasterMind {
private static final int COMBINATION_LENGTH = 5;
private static final int MAX_ATTEMPTS = 20;
private static final char[] COLORS = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
private String secretCombination;
public MasterMind() {
this.secretCombination = generateSecretCombination();
}
private String generateSecretCombination() {
Random random = new Random();
StringBuilder combination = new StringBuilder(COMBINATION_LENGTH);
for (int i = 0; i < COMBINATION_LENGTH; i++) {
combination.append(COLORS[random.nextInt(COLORS.length)]);
}
return combination.toString();
}
public void play() {
Scanner scanner = new Scanner(System.in);
int attempts = 0;
boolean won = false;
System.out.println("Welcome to MasterMind!");
System.out.println("Try to guess the combination of 5 letters (A to H). You have " + MAX_ATTEMPTS + " attempts.");
while (attempts < MAX_ATTEMPTS && !won) {
System.out.print("Enter your guess: ");
String guess = scanner.nextLine().toUpperCase();
if (guess.length() != COMBINATION_LENGTH) {
System.out.println("Invalid input. Please enter exactly " + COMBINATION_LENGTH + " letters.");
continue;
}
attempts++;
int[] result = evaluateGuess(guess);
System.out.println("Correct positions: " + result[0] + ", Correct letters in wrong positions: " + result[1]);
if (result[0] == COMBINATION_LENGTH) {
won = true;
System.out.println("Congratulations! You've guessed the correct combination.");
}
}
if (!won) {
System.out.println("Sorry, you've used all your attempts. The correct combination was: " + secretCombination);
}
scanner.close();
}
private int[] evaluateGuess(String guess) {
int correctPositions = 0;
int correctLettersWrongPositions = 0;
boolean[] secretUsed = new boolean[COMBINATION_LENGTH];
boolean[] guessUsed = new boolean[COMBINATION_LENGTH];
// First pass: check for correct positions
for (int i = 0; i < COMBINATION_LENGTH; i++) {
if (guess.charAt(i) == secretCombination.charAt(i)) {
correctPositions++;
secretUsed[i] = true;
guessUsed[i] = true;
}
}
// Second pass: check for correct letters in wrong positions
for (int i = 0; i < COMBINATION_LENGTH; i++) {
if (!guessUsed[i]) {
for (int j = 0; j < COMBINATION_LENGTH; j++) {
if (!secretUsed[j] && guess.charAt(i) == secretCombination.charAt(j)) {
correctLettersWrongPositions++;
secretUsed[j] = true;
break;
}
}
}
}
return new int[] { correctPositions, correctLettersWrongPositions };
}
}

View file

@ -0,0 +1,8 @@
package de.dhbwka.java.exercise.classes;
public record MasterMindTest() {
public static void main(String[] args) {
MasterMind game = new MasterMind();
game.play();
}
}

View file

@ -0,0 +1,58 @@
package de.dhbwka.java.exercise.classes;
import java.util.Scanner;
public class Nimmspiel {
private String player1;
private String player2;
private int heap1;
private int heap2;
private boolean isPlayer1Turn;
public Nimmspiel(String player1, String player2) {
this.player1 = player1;
this.player2 = player2;
this.heap1 = (int) (Math.random() * 10) + 1;
this.heap2 = (int) (Math.random() * 10) + 1;
this.isPlayer1Turn = true;
}
public String toString() {
return "Spieler: " + player1 + " und " + player2 + ", Haufen 1: " + heap1 + " Kugel(n), Haufen 2: " + heap2
+ " Kugel(n)";
}
public boolean isGameOver() {
return heap1 == 0 && heap2 == 0;
}
public void makeMove(int heap, int balls) {
if (heap == 1) {
heap1 -= balls;
} else {
heap2 -= balls;
}
isPlayer1Turn = !isPlayer1Turn;
}
public void play() {
Scanner scanner = new Scanner(System.in);
while (!isGameOver()) {
System.out.println(this);
String currentPlayer = isPlayer1Turn ? player1 : player2;
System.out.println("Spieler " + currentPlayer + ": Von welchem Haufen ziehen Sie Kugeln? (1 oder 2)");
int heap = scanner.nextInt();
System.out.println("Spieler " + currentPlayer + ": Wieviele Kugeln ziehen Sie?");
int balls = scanner.nextInt();
if ((heap == 1 && balls > 0 && balls <= heap1) || (heap == 2 && balls > 0 && balls <= heap2)) {
makeMove(heap, balls);
} else {
System.out.println("Ungültiger Zug, bitte erneut versuchen.");
}
}
scanner.close();
System.out.println("Spiel beendet.");
String winner = isPlayer1Turn ? player2 : player1;
System.out.println("Gewonnen hat Spieler " + winner);
}
}

View file

@ -0,0 +1,16 @@
package de.dhbwka.java.exercise.classes;
import java.util.Scanner;
public class NimmspielTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Bitte geben Sie den Namen des ersten Spielers ein:");
String player1 = scanner.nextLine();
System.out.println("Bitte geben Sie den Namen des zweiten Spielers ein:");
String player2 = scanner.nextLine();
Nimmspiel game = new Nimmspiel(player1, player2);
game.play();
scanner.close();
}
}

View file

@ -0,0 +1,93 @@
package de.dhbwka.java.exercise.classes;
public class Polynomial {
private double[] factors;
public Polynomial(double[] factors) {
if (factors == null || factors.length != 3) {
throw new IllegalArgumentException("Factors must not be null and must have a length of 3");
}
this.factors = factors;
}
public double[] getFactors() {
return factors;
}
public void setFactors(double[] factors) {
this.factors = factors;
}
@Override
public String toString() {
String result = "";
if (factors[0] != 0) {
if (factors[0] < 0) {
result += "-";
}
if (factors[0] != 1 && factors[0] != -1) {
result += Math.abs(factors[0]);
}
result += "x^2";
}
if (factors[1] != 0) {
if (factors[1] < 0) {
result += " - ";
} else if (factors[0] != 0) {
result += " + ";
}
if (factors[1] != 1 && factors[1] != -1) {
result += Math.abs(factors[1]);
}
result += "x";
}
if (factors[2] != 0) {
if (factors[2] < 0) {
result += " - ";
} else if (factors[0] != 0 || factors[1] != 0) {
result += " + ";
}
result += Math.abs(factors[2]);
}
return result;
}
public double evaluate(double x) {
return factors[0] * x * x + factors[1] * x + factors[2];
}
public Polynomial add(Polynomial p) {
return new Polynomial(
new double[] { factors[0] + p.factors[0], factors[1] + p.factors[1], factors[2] + p.factors[2] });
}
public Polynomial sub(Polynomial p) {
return new Polynomial(
new double[] { factors[0] - p.factors[0], factors[1] - p.factors[1], factors[2] - p.factors[2] });
}
public Polynomial scalarMul(double scalar) {
return new Polynomial(new double[] { factors[0] * scalar, factors[1] * scalar, factors[2] * scalar });
}
public double[] findRoots() {
double discriminant = factors[1] * factors[1] - 4 * factors[0] * factors[2];
if (factors[0] == 0 && factors[1] == 0) {
return new double[0];
} else if (factors[0] == 0) {
return new double[] { -factors[2] / factors[1] };
} else if (discriminant < 0) {
return new double[0];
} else if (discriminant == 0) {
return new double[] { -factors[1] / (2 * factors[0]) };
} else {
double root1 = (-factors[1] + Math.sqrt(discriminant)) / (2 * factors[0]);
double root2 = (-factors[1] - Math.sqrt(discriminant)) / (2 * factors[0]);
return new double[] { root1, root2 };
}
}
}

View file

@ -0,0 +1,24 @@
package de.dhbwka.java.exercise.classes;
public class PolynomialTest {
public static void main(String[] args) {
Polynomial p1 = new Polynomial(new double[] { 1, 2, 3 });
Polynomial p2 = new Polynomial(new double[] { 0, -3, 4 });
Polynomial p3 = p1.add(p2);
System.out.println(p1 + " + " + p2 + " = " + p3);
Polynomial p4 = p1.scalarMul(2);
System.out.println(p1 + " * 2 = " + p4);
System.out.println(p1 + " evaluated at x=2: " + p1.evaluate(2));
System.out.println(p2 + " evaluated at x=2: " + p2.evaluate(2));
System.out.println(p3 + " evaluated at x=2: " + p3.evaluate(2));
System.out.println(p4 + " evaluated at x=2: " + p4.evaluate(2));
double[] roots = p2.findRoots();
System.out.println("Root: " + roots[0]);
}
}