@@ -8,13 +8,15 @@ import { computeLexicographicDistance } from "./util.js";
8
8
* @return -1 if a is less than b, 1 if a is greater than b, and 0 otherwise.
9
9
*/
10
10
export function compareStrings ( a : string , b : string ) : number {
11
- // The distance will be a number less than 0 if string `a` is lexicographically less than `b`, 1
12
- // if it is greater, and 0 if the strings are equal.
13
11
const distance = computeLexicographicDistance ( a , b ) ;
14
12
15
- // TODO(you): Finish this method.
16
-
17
- return 0 ;
13
+ if ( distance < 0 ) {
14
+ return - 1 ;
15
+ } else if ( distance > 0 ) {
16
+ return 1 ;
17
+ } else {
18
+ return 0 ;
19
+ }
18
20
}
19
21
20
22
/**
@@ -24,7 +26,16 @@ export function compareStrings(a: string, b: string): number {
24
26
* @return The factorial of n.
25
27
*/
26
28
export function computeFactorial ( n : number ) : number {
27
- return 0 ;
29
+ if ( n === 0 ) {
30
+ return 1 ;
31
+ }
32
+
33
+ let result = 1 ;
34
+ for ( let i = 1 ; i <= n ; i ++ ) {
35
+ result *= i ;
36
+ }
37
+
38
+ return result ;
28
39
}
29
40
30
41
/**
@@ -34,7 +45,20 @@ export function computeFactorial(n: number): number {
34
45
* @return An array containing the first `n` Fibonacci values.
35
46
*/
36
47
export function getFirstNFibonacciNumbers ( n : number ) : number [ ] {
37
- return [ ] ;
48
+ if ( n <= 0 ) return [ ] ;
49
+
50
+ const fib : number [ ] = [ 1 ] ;
51
+
52
+ if ( n === 1 ) return fib ;
53
+
54
+ fib . push ( 1 ) ; // Add the second 1
55
+
56
+ for ( let i = 2 ; i < n ; i ++ ) {
57
+ const next = fib [ i - 1 ] + fib [ i - 2 ] ;
58
+ fib . push ( next ) ;
59
+ }
60
+
61
+ return fib ;
38
62
}
39
63
40
64
/**
@@ -53,17 +77,16 @@ export function binarySearch(
53
77
value : number ,
54
78
) : number {
55
79
if ( end < start ) {
56
- // The range is not valid so just return -1.
57
- return - 1 ;
80
+ return - 1 ; // Base case: value not found
58
81
}
59
82
60
- const pivotIndex = Math . floor ( ( start + end ) / 2 ) ; // The index in the middle of the array.
83
+ const pivotIndex = Math . floor ( ( start + end ) / 2 ) ;
61
84
62
- // TODO(you): Finish implementing this algorithm
63
-
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 ;
85
+ if ( values [ pivotIndex ] === value ) {
86
+ return pivotIndex ;
87
+ } else if ( values [ pivotIndex ] > value ) {
88
+ return binarySearch ( values , start , pivotIndex - 1 , value ) ;
89
+ } else {
90
+ return binarySearch ( values , pivotIndex + 1 , end , value ) ;
91
+ }
69
92
}
0 commit comments