@@ -11,11 +11,12 @@ export function compareStrings(a: string, b: string): number {
11
11
// The distance will be a number less than 0 if string `a` is lexicographically less than `b`, 1
12
12
// if it is greater, and 0 if the strings are equal.
13
13
const distance = computeLexicographicDistance ( a , b ) ;
14
+ return distance ;
15
+ }
14
16
15
- // TODO(you): Finish this method.
17
+ // TODO(you): Finish this method.
16
18
17
- return 0 ;
18
- }
19
+ // Removed misplaced return statement
19
20
20
21
/**
21
22
* Computes the factorial of the given value of `n`.
@@ -24,7 +25,20 @@ 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
+ return 0 ;
30
+ }
31
+ if ( n === 1 ) {
32
+ return 1 ;
33
+ }
34
+ if ( n === 2 ) {
35
+ return 2 ;
36
+ }
37
+ let result = 1 ;
38
+ for ( let i = 2 ; i <= n ; ++ i ) {
39
+ result *= i ;
40
+ }
41
+ return result ;
28
42
}
29
43
30
44
/**
@@ -34,7 +48,20 @@ export function computeFactorial(n: number): number {
34
48
* @return An array containing the first `n` Fibonacci values.
35
49
*/
36
50
export function getFirstNFibonacciNumbers ( n : number ) : number [ ] {
37
- return [ ] ;
51
+ if ( n < 1 ) {
52
+ return [ ] ;
53
+ }
54
+ if ( n === 1 ) {
55
+ return [ 1 ] ;
56
+ }
57
+ if ( n === 2 ) {
58
+ return [ 1 , 1 ] ;
59
+ }
60
+ const sequence = [ 1 , 1 ] ;
61
+ for ( let i = 2 ; i < n ; ++ i ) {
62
+ sequence [ i ] = sequence [ i - 1 ] + sequence [ i - 2 ] ;
63
+ }
64
+ return sequence ;
38
65
}
39
66
40
67
/**
@@ -56,14 +83,19 @@ export function binarySearch(
56
83
// The range is not valid so just return -1.
57
84
return - 1 ;
58
85
}
59
-
60
- const pivotIndex = Math . floor ( ( start + end ) / 2 ) ; // The index in the middle of the array.
61
-
62
86
// TODO(you): Finish implementing this algorithm
63
87
64
88
// If values[pivotIndex] is equal to value then return `pivotIndex`.
65
89
// Else if values[pivotIndex] is greater than the value, then
66
90
// call `binarySearch(values, start, pivotIndex - 1, value)` and return its value;
67
91
// Else call `binarySearch(values, pivotIndex + 1, end, value)` and return its value.
68
- return - 1 ;
92
+
93
+ const pivotIndex = Math . floor ( ( start + end ) / 2 ) ; // The index in the middle of the array.
94
+ if ( values [ pivotIndex ] === value ) {
95
+ return pivotIndex ;
96
+ } else if ( values [ pivotIndex ] > value ) {
97
+ return binarySearch ( values , start , pivotIndex - 1 , value ) ;
98
+ } else {
99
+ return binarySearch ( values , pivotIndex + 1 , end , value ) ;
100
+ }
69
101
}
0 commit comments