Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class PascalTriangle {
- private static final String NEW_LINE = System.getProperty("line.separator");
- private long[][] triangle;
- public PascalTriangle(int rowCount) {
- if (rowCount <= 0) {
- return;
- }
- triangle = new long[rowCount][];
- for (int r = 0; r < rowCount; r++) {
- int colCount = r + 1;
- triangle[r] = new long[colCount];
- triangle[r][0] = 1;
- triangle[r][colCount - 1] = 1;
- for (int c = 1; c < colCount - 1; c++) {
- triangle[r][c] = triangle[r - 1][c - 1] + triangle[r - 1][c];
- }
- }
- }
- public long getValue(int row, int col) throws IllegalArgumentException {
- if (triangle == null) {
- return 0;
- }
- if (col > row) {
- throw new IllegalArgumentException(
- "Invalid column entry, column value cannot be greater than row value");
- }
- return triangle[row - 1][col - 1];
- }
- public String getTriangleDisplay() {
- if (triangle == null) {
- return null;
- }
- StringBuilder triangleBuilder = new StringBuilder();
- for (int r = 0; r < triangle.length; r++) {
- triangleBuilder.append(r != 0 ? NEW_LINE : "");
- for (int c = 0; c < triangle[r].length; c++) {
- triangleBuilder.append(c != 0 ? '\t' : "");
- triangleBuilder.append(triangle[r][c]);
- }
- }
- return triangleBuilder.toString();
- }
- public static void main(String[] args) throws Exception {
- BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
- int row = 0;
- int col = 0;
- String line;
- while ((line = prompt(in)) != null) {
- if (line.startsWith("exit")) {
- break;
- }
- String[] input = line.split(",\\s+");
- try {
- row = Integer.parseInt(input[0]);
- if (row <= 0) {
- throw new IllegalArgumentException();
- }
- } catch (IllegalArgumentException e) {
- System.err
- .println("Invalid row entry, expected positive integer but got "
- + input[0]);
- continue;
- }
- try {
- col = Integer.parseInt(input[1]);
- if (col <= 0) {
- throw new IllegalArgumentException();
- }
- } catch (IllegalArgumentException e) {
- System.err
- .println("Invalid column entry, expected positive integer but got "
- + input[1]);
- continue;
- }
- PascalTriangle triangle = new PascalTriangle(row);
- long value = 0;
- try {
- value = triangle.getValue(row, col);
- } catch (IllegalArgumentException e) {
- System.err.println(e.getMessage());
- continue;
- }
- System.out.println("Output: " + value);
- System.out.println();
- System.out.println(triangle.getTriangleDisplay());
- System.out.println();
- }
- }
- private static String prompt(BufferedReader in) throws IOException {
- System.out.println();
- System.out.print("Enter Input (type 'exit' to end): ");
- return in.readLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment