@@ -13,7 +13,8 @@ export function compareStrings(a: string, b: string): number {
13
13
const distance = computeLexicographicDistance ( a , b ) ;
14
14
15
15
// TODO(you): Finish this method.
16
-
16
+ if ( distance < 0 ) return - 1 ;
17
+ if ( distance > 0 ) return 1 ;
17
18
return 0 ;
18
19
}
19
20
@@ -24,7 +25,19 @@ export function compareStrings(a: string, b: string): number {
24
25
* @return The factorial of n.
25
26
*/
26
27
export function computeFactorial ( n : number ) : number {
27
- return 0 ;
28
+ if ( n < 0 ) {
29
+ throw new Error ( "Factorial is not defined for negative numbers." ) ;
30
+ }
31
+ if ( n === 0 || n === 1 ) {
32
+ return 1 ;
33
+ }
34
+
35
+ let result = 1 ;
36
+ for ( let i = 2 ; i <= n ; i ++ ) {
37
+ result *= i ;
38
+ }
39
+
40
+ return result ;
28
41
}
29
42
30
43
/**
@@ -34,9 +47,17 @@ export function computeFactorial(n: number): number {
34
47
* @return An array containing the first `n` Fibonacci values.
35
48
*/
36
49
export function getFirstNFibonacciNumbers ( n : number ) : number [ ] {
37
- return [ ] ;
50
+ if ( n === 0 ) {
51
+ return [ ]
52
+ }
53
+ const fibNum = [ 1 , 1 ] ;
54
+ for ( let i = 2 ; i < n ; i ++ ) {
55
+ fibNum . push ( fibNum [ i - 1 ] + fibNum [ i - 2 ] )
56
+ }
57
+ return fibNum ;
38
58
}
39
59
60
+
40
61
/**
41
62
* Finds a value in an array of values.
42
63
*
@@ -58,12 +79,18 @@ export function binarySearch(
58
79
}
59
80
60
81
const pivotIndex = Math . floor ( ( start + end ) / 2 ) ; // The index in the middle of the array.
82
+ if ( values [ pivotIndex ] === value ) {
83
+ return pivotIndex ; // Value found at pivot index.
84
+ } else if ( values [ pivotIndex ] > value ) {
85
+ return binarySearch ( values , start , pivotIndex - 1 , value ) ; // Search left half.
86
+ } else {
87
+ return binarySearch ( values , pivotIndex + 1 , end , value ) ; // Search right half.
88
+ }
89
+ }
61
90
62
- // TODO(you): Finish implementing this algorithm
91
+ // TODO(you): Finish implementing this algorithm
63
92
64
- // If values[pivotIndex] is equal to value then return `pivotIndex`.
65
- // Else if values[pivotIndex] is greater than the value, then
66
- // call `binarySearch(values, start, pivotIndex - 1, value)` and return its value;
67
- // Else call `binarySearch(values, pivotIndex + 1, end, value)` and return its value.
68
- return - 1 ;
69
- }
93
+ // If values[pivotIndex] is equal to value then return `pivotIndex`.
94
+ // Else if values[pivotIndex] is greater than the value, then
95
+ // call `binarySearch(values, start, pivotIndex - 1, value)` and return its value;
96
+ // Else call `binarySearch(values, pivotIndex + 1, end, value)` and return its value.
0 commit comments