New day, new exercise for my DevAdvent 2022. Over the weekend I discovered a few other devAdvents but still decided not to follow any of them. Instead, I will continue to pick a random problem from CodeWars. Today’s one is about how to find the minimum and maximum of a series of numbers.

### The problem

In this little assignment you are given a string of space separated numbers, and have to return the highest and lowest number.

Examples

``````highAndLow("1 2 3 4 5"); // return "5 1"
highAndLow("1 2 -3 4 5"); // return "5 -3"
highAndLow("1 9 3 4 -5"); // return "9 -5"
``````

### The solution

This is my solution for TypeScript:

``````export class Kata {
static highAndLow(numbers: string): string {
const arr: number[] = numbers.split(" ").map((c) => parseInt(c));
const max: number = Math.max(...arr);
const min: number = Math.min(...arr);
return `\${max} \${min}`;
}
}
``````

This is my solution for JavaScript:

``````function highAndLow(numbers) {
const arr = numbers.split(" ").map((c) => parseInt(c));
const max = Math.max(...arr);
const min = Math.min(...arr);
return `\${max} \${min}`;
}
``````

Also in this case I preferred to divide the problem into several steps.

First of all, I split the string into an array of numbers. Then I used the `Math.max` and `Math.min` functions to find the maximum and minimum values. Finally, I returned the result as a string.

To split the string I use the String.split() method. This way I get an array of strings.

``````// ts
const arrString: string[] = numbers.split(" ");

//js
const arrString = numbers.split(" ");
``````

Then I use the Array.map() method to modify each element of the array. This way I can convert each element to a number.

``````// ts
const arrNumber: number[] = arrString.map((c) => parseInt(c));

//js
const arrNumber = arrString.map((c) => +c);
``````

Finally, I use the Math.max() and Math.min() functions to find the maximum and minimum values.

``````// ts
const max: number = Math.max(...arr);
const min: number = Math.min(...arr);

// js
const max = Math.max(...arr);
const min = Math.min(...arr);
``````

I can also approach the problem in a slightly different way. After converting the string to an array of numbers, I sort the array. Then I return the first and last item.

``````export class Kata {
static highAndLow(numbers: string) {
let arr = numbers
.split(" ")
.map((x) => parseInt(x))
.sort((a, b) => a - b);

return `\${arr[arr.length - 1]} \${arr[0]}`;
}
}
``````
``````function highAndLow(numbers) {
const arr = numbers
.split(" ")
.map((c) => parseInt(c))
.sort((a, b) => a - b);

return `\${arr[arr.length - 1]} \${arr[0]}`;
}
``````

Tags:

Categorie:

Aggiornato: