Created
October 10, 2021 18:58
-
-
Save sinanduman/5c83c0d7f5ccb4cc78b2ed5609462068 to your computer and use it in GitHub Desktop.
Pascal Triangle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.List; | |
public class Pascal { | |
public static void main(String[] args) { | |
int numberOfRows = 8; | |
String blank = " "; | |
List<List<Integer>> listOfList = new ArrayList<>(); | |
/* First row */ | |
List<Integer> one = Arrays.asList(1); | |
listOfList.add(one); | |
System.out.println(blank.repeat(numberOfRows - listOfList.size()) + one); | |
/* 1 to last Row */ | |
for (int i = 0; i < numberOfRows - 1; i++) { | |
List<Integer> curr = listOfList.get(listOfList.size() - 1); | |
List<Integer> temp = new ArrayList<>(); | |
/* Leftmost 1 */ | |
temp.add(1); | |
for (int j = 0; j < listOfList.size() - 1; j++) { | |
temp.add(curr.get(j) + curr.get(j + 1)); | |
} | |
/* Rightmost 1 */ | |
temp.add(1); | |
listOfList.add(temp); | |
System.out.println(blank.repeat(numberOfRows - listOfList.size()) + temp); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]