@@ -8,13 +8,15 @@ import { computeLexicographicDistance } from "./util.js";
88 * @return -1 if a is less than b, 1 if a is greater than b, and 0 otherwise.
99 */
1010export 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.
1311 const distance = computeLexicographicDistance ( a , b ) ;
1412
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+ }
1820}
1921
2022/**
@@ -24,7 +26,16 @@ export function compareStrings(a: string, b: string): number {
2426 * @return The factorial of n.
2527 */
2628export 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 ;
2839}
2940
3041/**
@@ -34,7 +45,20 @@ export function computeFactorial(n: number): number {
3445 * @return An array containing the first `n` Fibonacci values.
3546 */
3647export 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 ;
3862}
3963
4064/**
@@ -53,17 +77,16 @@ export function binarySearch(
5377 value : number ,
5478) : number {
5579 if ( end < start ) {
56- // The range is not valid so just return -1.
57- return - 1 ;
80+ return - 1 ; // Base case: value not found
5881 }
5982
60- const pivotIndex = Math . floor ( ( start + end ) / 2 ) ; // The index in the middle of the array.
83+ const pivotIndex = Math . floor ( ( start + end ) / 2 ) ;
6184
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+ }
6992}
0 commit comments