Skip to content

Commit 84589c8

Browse files
committed
feat: add Davis lesson7 HW
1 parent 10df15c commit 84589c8

File tree

3 files changed

+2742
-12
lines changed

3 files changed

+2742
-12
lines changed

lesson_07/conditionals/.env.test

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
HW_VERSION=your homework version here
1+
HW_VERSION=E

lesson_07/conditionals/src/lesson7.ts

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,36 @@ export function compareStrings(a: string, b: string): number {
2828
* @return The factorial of n.
2929
*/
3030
export function computeFactorial(n: number): number {
31-
return 0;
31+
if (n === 0 || n === 1) {
32+
return 1;
33+
}
34+
if (n < 0) {
35+
return 0;
36+
}
37+
let result = 1;
38+
for (let i = 2; i <= n; i++) {
39+
result *= i;
40+
}
41+
return result;
3242
}
33-
3443
/**
3544
* Returns an array of the first `n` Fibonacci numbers starting from 1.
3645
*
3746
* @param n The first `n` of Fibonacci values to compute.
3847
* @return An array containing the first `n` Fibonacci values.
3948
*/
4049
export function getFirstNFibonacciNumbers(n: number): number[] {
41-
return [];
50+
if (n <= 0) {
51+
return [];
52+
}
53+
if (n === 1) {
54+
return [1];
55+
}
56+
const Fibonacci: number[] = [1, 1];
57+
for (let i = 2; i < n; i++) {
58+
Fibonacci.push(Fibonacci[i - 1] + Fibonacci[i - 2]);
59+
}
60+
return Fibonacci;
4261
}
4362

4463
/**
@@ -62,12 +81,17 @@ export function binarySearch(
6281
}
6382

6483
const pivotIndex = Math.floor((start + end) / 2); // The index in the middle of the array.
65-
66-
// TODO(you): Finish implementing this algorithm
67-
68-
// If values[pivotIndex] is equal to value then return `pivotIndex`.
69-
// Else if values[pivotIndex] is greater than the value, then
70-
// call `binarySearch(values, start, pivotIndex - 1, value)` and return its value;
71-
// Else call `binarySearch(values, pivotIndex + 1, end, value)` and return its value.
72-
return -1;
84+
if (values[pivotIndex] === value) {
85+
return pivotIndex;
86+
} else if (values[pivotIndex] > value) {
87+
return binarySearch(values, start, pivotIndex - 1, value); // Search in the right half
88+
} else {
89+
return binarySearch(values, pivotIndex + 1, end, value); // Search in the left half
90+
}
7391
}
92+
// TODO(you): Finish implementing this algorithm
93+
94+
// If values[pivotIndex] is equal to value then return `pivotIndex`.
95+
// Else if values[pivotIndex] is greater than the value, then
96+
// call `binarySearch(values, start, pivotIndex - 1, value)` and return its value;
97+
// Else call `binarySearch(values, pivotIndex + 1, end, value)` and return its value.

0 commit comments

Comments
 (0)