Skip to content

Instantly share code, notes, and snippets.

@sinanduman
Created October 10, 2021 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sinanduman/5c83c0d7f5ccb4cc78b2ed5609462068 to your computer and use it in GitHub Desktop.
Save sinanduman/5c83c0d7f5ccb4cc78b2ed5609462068 to your computer and use it in GitHub Desktop.
Pascal Triangle
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);
}
}
}
@sinanduman
Copy link
Author

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]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment