PascalRecursive
Typer | Posted on | |
import java.util.Scanner;
public class PascalRecursive {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("----- Welcome to Pascal Triangle (Recursive) -----");
while (true) {
int rows;
while (true) {
System.out.println("\nEnter number of rows (positive integer) or 'bye' to quit:");
String input = scan.nextLine().trim();
if (input.matches("(?i).*(bye|exit|quit).*")) {
System.out.println("Goodbye!");
return;
}
if (input.matches("\\d+") && Integer.parseInt(input) > 0) {
rows = Integer.parseInt(input);
break;
} else {
System.out.println("Invalid input!");
}
}
long start = System.currentTimeMillis(); // Start timing before computation
printPascalRecursive(rows); // Call recursive function
long end = System.currentTimeMillis(); // End timing after computation
System.out.println("Recursive method duration: " + (end - start) + " ms\n");
while (true) {
System.out.println("\nPlay again? (y/n)");
String again = scan.nextLine().trim();
switch (again.toLowerCase()) {
case "n" -> {
System.out.println("Program ended. Goodbye!");
return;
}
case "y" -> {
break;
}
default -> {
System.out.println("Invalid input!");
continue;
}
}
break; // Exit loop and restart program
}
}
}
}
// Recursive function to compute Pascal's Triangle values
public static int pascal(int row, int column) {
if (column == 0 || column == row)
return 1;
return pascal(row - 1, column - 1) + pascal(row - 1, column);
}
// Print Pascal's Triangle using recursive calculations
public static void printPascalRecursive(int rows) {
int maxWidth = 4 * rows; // Define maximum width for alignment
for (int row = 0; row < rows; row++) {
// Print leading spaces to center the row
System.out.printf("%" + (maxWidth - 2 * row) + "s", "");
for (int column = 0; column <= row; column++) {
System.out.printf("%4d", pascal(row, column)); // Format numbers for alignment
}
System.out.println(); // Move to the next line
}
}
}