@@ -8,23 +8,33 @@ 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+ }
16+
17+ if ( distance > 0 ) {
18+ return 1 ;
19+
1820}
1921
22+ return 0 ;
23+ }
2024/**
2125 * Computes the factorial of the given value of `n`.
2226 *
2327 * @param n The value for which to compute the factorial.
2428 * @return The factorial of n.
2529 */
2630export function computeFactorial ( n : number ) : number {
27- return 0 ;
31+ if ( n < 0 )
32+ return 0 ; // Factorial is not defined for negative numbers
33+ let result = 1 ;
34+ for ( let i = 2 ; i <= n ; i ++ ) {
35+ result *= i ;
36+ }
37+ return result ;
2838}
2939
3040/**
@@ -34,11 +44,19 @@ export function computeFactorial(n: number): number {
3444 * @return An array containing the first `n` Fibonacci values.
3545 */
3646export function getFirstNFibonacciNumbers ( n : number ) : number [ ] {
37- return [ ] ;
47+ if ( n <= 0 ) return [ ] ;
48+ if ( n === 1 ) return [ 1 ] ;
49+
50+ const fibs : number [ ] = [ 1 , 1 ] ;
51+ while ( fibs . length < n ) {
52+ const next = fibs [ fibs . length - 1 ] + fibs [ fibs . length - 2 ] ;
53+ fibs . push ( next ) ;
54+ }
55+ return fibs ;
3856}
3957
4058/**
41- * Finds a value in an array of values.
59+ * Finds a value in an array of values using binary search .
4260 *
4361 * @param values The values to search.
4462 * @param start The left most index to search.
@@ -52,18 +70,21 @@ export function binarySearch(
5270 end : number ,
5371 value : number ,
5472) : number {
73+
5574 if ( end < start ) {
56- // The range is not valid so just return -1.
5775 return - 1 ;
5876 }
5977
78+
6079 const pivotIndex = Math . floor ( ( start + end ) / 2 ) ; // The index in the middle of the array.
6180
6281 // 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 ;
82+ if ( values [ pivotIndex ] === value ) {
83+ return pivotIndex ;
84+ } else if ( values [ pivotIndex ] > value ) {
85+ return binarySearch ( values , start , pivotIndex - 1 , value ) ;
86+ } else {
87+ return binarySearch ( values , pivotIndex + 1 , end , value ) ;
88+ }
89+
6990}
0 commit comments