@@ -13,7 +13,8 @@ export function compareStrings(a: string, b: string): number {
1313 const distance = computeLexicographicDistance ( a , b ) ;
1414
1515 // TODO(you): Finish this method.
16-
16+ if ( distance < 0 ) return - 1 ;
17+ if ( distance > 0 ) return 1 ;
1718 return 0 ;
1819}
1920
@@ -24,7 +25,19 @@ export function compareStrings(a: string, b: string): number {
2425 * @return The factorial of n.
2526 */
2627export 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 ;
2841}
2942
3043/**
@@ -34,9 +47,17 @@ export function computeFactorial(n: number): number {
3447 * @return An array containing the first `n` Fibonacci values.
3548 */
3649export 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 ;
3858}
3959
60+
4061/**
4162 * Finds a value in an array of values.
4263 *
@@ -58,12 +79,18 @@ export function binarySearch(
5879 }
5980
6081 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+ }
6190
62- // TODO(you): Finish implementing this algorithm
91+ // TODO(you): Finish implementing this algorithm
6392
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