feat: add Uebung 1 und 2

This commit is contained in:
Alicia Dietrich 2023-12-04 21:55:59 +02:00
parent 57cb2cc075
commit 643f451554
2 changed files with 79 additions and 0 deletions

View File

@ -0,0 +1,30 @@
public class Fibonacci {
public static void main(String[] args) {
int iterativ = printFibonacciIterative(45);
System.out.println(iterativ);
int recursive = fibonacciRecursive(45);
System.out.println(recursive);
}
public static int printFibonacciIterative(int n) {
//Hilfsvariablen a und b
int a = 1, b = 1;
int sum = 0;
//for-Schleife für die iterative Berechnung der Fibonacci Folge
for (int i = 1; i < n-1; i++) {
sum = a + b;
a = b;
b = sum;
}
return sum;
}
private static int fibonacciRecursive(int a) {
if (a == 1 || a == 2) {
return 1;
} else {
return fibonacciRecursive(a - 1) + fibonacciRecursive(a - 2);
}
}
}

View File

@ -0,0 +1,49 @@
public class QueensProblem {
public static void main(String[] args) {
//Initialisiere Schachfeld 8x8
boolean[][] queen = new boolean[8][8];
int counter = solutions(queen, 0);
System.out.println(counter);
}
private static int solutions(boolean[][] queen, int row) {
if (row == queen.length) {
return 1;
}
int counter = 0;
for (int col = 0; col < queen.length; col++) {
if (!isPositionSave(queen, row, col)) {
continue;
}
queen[row][col] = true;
counter += solutions(queen, row + 1);
queen[row][col] = false;
}
return counter;
}
public static boolean isPositionSave(boolean[][] queen, int row, int col) {
for (int i = 0; i < row; i++) {
int dC = row - i;
// Teste Spalte
if (queen[i][col]) {
return false;
}
// Teste linke Diagonale
if (col - dC >= 0 && queen[i][col - dC]) {
return false;
}
// Teste rechte Diagonale
if (col + dC < queen.length && queen[i][col + dC]) {
return false;
}
}
return true;
}
}