Last active
March 31, 2020 09:50
-
-
Save Mastersam07/cd47cbb4d2c9aafa7b2a4d9b1d7f1708 to your computer and use it in GitHub Desktop.
pascal triangle
This file contains hidden or 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
| // pascal triangle | |
| void main() { | |
| print(pascalTriangle(5)); // [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]] | |
| print("--------------------------"); | |
| print(pascalTriangle(1)); // should return 1 | |
| print("--------------------------"); | |
| print(pascalTriangle(0)); // should return empty [] | |
| print("--------------------------"); | |
| print(pascalTriangle(-6)); // should return -1 | |
| } | |
| List<List<int>> pascalTriangle(int n) { // where n is number of rows | |
| List<List<int>> triangle = []; // initialize so [] can be returned when rows == 0 | |
| if (n<0){ | |
| triangle=[[-1]]; // where we input negative number returns -1 | |
| } | |
| for (var row = 0; row < n; row++) { | |
| List<int> currentRow = [1]; // initialize current row such that return [1] when row == 1 | |
| if (row >= 2) { // when row is from 2 upwards | |
| for (var j = 0; j < triangle[row - 1].length - 1; j++) { | |
| currentRow.add(triangle[row - 1][j] + triangle[row - 1][j + 1]); | |
| } | |
| } | |
| if (row >= 1) { | |
| currentRow.add(1); | |
| } | |
| triangle.add(currentRow); | |
| } | |
| return triangle; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment