PascalOptimized
Typer | Posted on | |
/*
@startuml
class pascalOptimized {
+main(String[] args) : void
-printPascalIterative(int rows) : void
}
pascalOptimized ..> java.util.Scanner : uses
@enduml
*/
import java.util.Scanner;
public class PascalOptimized {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("---------- Welcome to Pascal Triangle (Optimized) ----------");
while (true) {
int rows;
while (true) {
System.out.print("Please enter a 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();
pascal(rows);
long end = System.currentTimeMillis();
long duration = end - start;
System.out.println("Duration: " + duration + " ms\n");
while (true) {
System.out.println("Do you want to play again? (y/n)");
String again = scan.nextLine().trim().toLowerCase();
switch (again) {
case "n" -> {
System.out.println("Program ended. Goodbye!");
return;
}
case "y" -> {
break;
}
default -> {
System.out.println("Invalid input.");
continue;
}
}
break;
}
}
}
}
public static void pascal(int rows) {
int[][] table = new int[rows][rows];
int lineMaxWidth = 4 * rows;
for (int i = 0; i < rows; i++) {
table[i] = new int[i + 1];
table[i][0] = table[i][i] = 1;
for (int j = 1; j < i; j++) {
table[i][j] = table[i - 1][j - 1] + table[i - 1][j];
}
System.out.printf("%" + (lineMaxWidth - 2 * i) + "s", "");
for (int element : table[i]) {
System.out.printf("%4d", element);
}
System.out.println();
}
}
}