-
Notifications
You must be signed in to change notification settings - Fork 0
/
Array-squareUp_b.js
30 lines (25 loc) · 921 Bytes
/
Array-squareUp_b.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
// -------------------------------Description---------------------------------
// This is a question from codingbat
// Given an integer n greater than or equal to 0, create and return an array with the following pattern:
// squareUp(3) => [0, 0, 1, 0, 2, 1, 3, 2, 1]
// squareUp(2) => [0, 1, 2, 1]
// squareUp(4) => [0, 0, 0, 1, 0, 0, 2, 1, 0, 3, 2, 1, 4, 3, 2, 1]
// 0 <= n <= 1000.
// ---------------------------------------------------------------------------
const squareUp = (n) => {
let result = [];
for (let i = n; i > 0; i--) {
for (let j = 1; j <= n; j++) {
if (j <= i) {
result.unshift(j);
} else {
result.unshift(0);
}
}
}
return result;
};
// Test cases
console.log(squareUp(3)); // Output: [0, 0, 1, 0, 2, 1, 3, 2, 1]
console.log(squareUp(2)); // Output: [0, 1, 2, 1]
console.log(squareUp(4)); // Output: [0, 0, 0, 1, 0, 0, 2, 1, 0, 3, 2, 1, 4, 3, 2, 1]