In order to determine the mode of an array consisting of integer numbers only, I must create a function named findMode. If the array is empty, the function should return 0. Otherwise, it should return the element that occurs most frequently in the array. In case there are multiple modes, the smallest value among them should be returned. To achieve this, I need to generate a new array to keep track of how many times each number appears in the input array.
Here is the initial implementation:
import { print } from "....";
export let main = async () => {
let input = [2, 1, 1, 2, 1, 0]
print(mode(input))
};
export let findMode = (b: number[]): number => {
let newArr: number[] = []; /** An intermediate array created to store count */
if (b.length === 0) {
return 0;
for (let i = 0; i < b.length; i++) {
};
main();
The expected/actual results are as follows:
If the array is [2,1,1,2,1,0], the expected result is 1. When inspecting the array with counts, newArr[1,3,2] should be printed. This signifies that element 0 appears once, element 1 appears thrice, and element 2 appears twice. The maximum occurrence corresponds to index 1 in the intermediate array, leading to the mode being 1.
For arrays like [0,0,0,1,1,2,1,1], [4,4,7,4,0,7], [-4,-4,-1,3,5], [1,1,2,3,2], and [10,10,10,20,20,30], the expected modes are 1, 4, -4, 1, and 10 respectively. In cases where there are multiple modes, the smallest one should always be selected.