add UE09_Rekursion2
This commit is contained in:
57
src/UE09_191124_Rekursion2/UE09_Rekursion2.java
Normal file
57
src/UE09_191124_Rekursion2/UE09_Rekursion2.java
Normal file
@@ -0,0 +1,57 @@
|
||||
package UE09_191124_Rekursion2;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class UE09_Rekursion2 {
|
||||
public static void main(String[] args) {
|
||||
// int[][] file1 = readFile("src/UE09_191124_Rekursion2/UE09_triangle1.txt");
|
||||
// int[][] file2 = readFile("src/UE09_191124_Rekursion2/UE09_triangle2.txt");
|
||||
// int[][] file3 = readFile("src/UE09_191124_Rekursion2/UE09_triangle.txt");
|
||||
// System.out.println("\n" + maxTotalRekursion(file1, 0, 0));
|
||||
// System.out.println("\n" + maxTotalRekursion(file2, 0, 0));
|
||||
// System.out.println("\n" + maxTotalRekursion(file3, 0, 0)); //Braucht ewig lange, da File sehr groß
|
||||
System.out.println(collatz());
|
||||
}
|
||||
|
||||
public static int[][] readFile(String file) {
|
||||
try {
|
||||
List<String> lines = Files.readAllLines(Path.of(file));
|
||||
int[][] output = new int[lines.size()][];
|
||||
for (int i = 0; i < output.length; i++) {
|
||||
String[] line = lines.get(i).trim().split(" ");
|
||||
output[i] = new int[line.length];
|
||||
for (int j = 0; j < line.length; j++) output[i][j] = Integer.parseInt(line[j]);
|
||||
}
|
||||
return output;
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public static long maxTotalRekursion(int[][] input, int x, int y) {
|
||||
return (x >= input.length - 1) ? input[x][y] : Long.max(maxTotalRekursion(input, x + 1, y), maxTotalRekursion(input, x + 1, y + 1)) + input[x][y];
|
||||
}
|
||||
|
||||
public static long collatz() {
|
||||
long startingNumber = 0, maxLength = 0;
|
||||
for (int i = 1; i < 1000000; i++) {
|
||||
long length = longestCollatzSequence(new ArrayList<>(), i).size();
|
||||
if (length > maxLength) {
|
||||
maxLength = length;
|
||||
startingNumber = i;
|
||||
}
|
||||
}
|
||||
return startingNumber;
|
||||
}
|
||||
|
||||
public static List<Long> longestCollatzSequence(List<Long> l, long n) {
|
||||
if (n == 1) return l;
|
||||
l.add(n);
|
||||
n = ((n & 1) == 0) ? (n / 2) : (3 * n + 1);
|
||||
return longestCollatzSequence(l, n);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user