-
Notifications
You must be signed in to change notification settings - Fork 0
/
algoW2D5.js
82 lines (62 loc) · 2.17 KB
/
algoW2D5.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
Challenge: Create Pascal's Triangle see: https://www.mathsisfun.com/pascals-triangle.html
Your task is to write a JavaScript function that takes an integer n as input and returns an array of arrays
that represents the first n rows of Pascal's triangle.
Pascal's triangle is a triangular array of numbers in which the first and last number in each row is 1,
and each remaining number is the sum of the two numbers above it in the previous row.
For example, if n is 5, the function should return the following array:
[
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1]
]
hint: How many digits are in row n?
*/
function generatePascalsTriangle(n) {
//Your code here
// if (numRows === 0) return [];
// if (numRows === 1) return [[1]];
// let result = [];
// for (let row = 1; row <= numRows; row++) {
// let arr = [];
// for (let col = 0; col < row; col++) {
// if (col === 0 || col === row - 1) {
// arr.push(1);
// } else {
// arr.push((result[row-2][col-1] + result[row-2][col]));
// }
// }
// result.push(arr);
// }
// return result;
let triangle = []; //create triangle array
for (let i = 0; i < n; i++) { //for each n
let row = []; //create a row array
for (let j = 0; j <= i; j++) { //this loops fills in the row array
if (j === 0 || j === i) { //if we're at the start or end, we push a 1
row.push(1);
} else { //otherwise, we calculate by adding corresponding two numbers from the previous row
row.push(triangle[i - 1][j - 1] + triangle[i - 1][j]);
}
}
triangle.push(row); //row is ready to add to the triangle
}
return triangle;
}
console.log(generatePascalsTriangle(1));
// => [[1]]
console.log(generatePascalsTriangle(2));
// => [[1], [1, 1]]
console.log(generatePascalsTriangle(5));
// => [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
console.log(generatePascalsTriangle(6));
// => [
// [ 1 ],
// [ 1, 1 ],
// [ 1, 2, 1 ],
// [ 1, 3, 3, 1 ],
// [ 1, 4, 6, 4, 1 ],
// [ 1, 5, 10, 10, 5, 1 ]
// ]