Exercise description:
Find the most common number in an array of numbers.
Create a software that takes an array of numbers as parameter. The return of the function shall be the most common number.
Example: Assume that the list is ... 1, 5, 1, 3, 5, 5, 2.
The program will output 5, because this is the most common number.
Note that if there is more than one most common number, the program will just print one of the most common numbers.
My solution (written in TypeScript):
let numbers: number[] = [1, 5, 1, 3, 5, 5, 2];
namespace Main {
export function searchMostCommonNumber(arr: number[] = []): number {
let current: number = 0;
let max: number = 0;
let mostCommonNumber: number = 0;
let i: number;
for (i = 0; i < arr.length - 1; i++) {
let current: number = 1;
let j: number;
for (j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
current++;
}
}
if (current > max) {
max = current;
mostCommonNumber = arr[i];
}
}
return mostCommonNumber;
}
}
console.log(Main.searchMostCommonNumber(numbers));
Live demo (with compiled code):
var numbers = [1, 5, 1, 3, 5, 5, 2];
var Main;
(function(Main) {
function searchMostCommonNumber(arr) {
if (arr === void 0) {
arr = [];
}
var current = 0;
var max = 0;
var mostCommonNumber = 0;
var i;
for (i = 0; i < arr.length - 1; i++) {
var current_1 = 1;
var j = void 0;
for (j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) {
current_1++;
}
}
if (current_1 > max) {
max = current_1;
mostCommonNumber = arr[i];
}
}
return mostCommonNumber;
}
Main.searchMostCommonNumber = searchMostCommonNumber;
})(Main || (Main = {}));
console.log('The most common number is :', Main.searchMostCommonNumber(numbers));
What do you think about my solution?
Is there a better way to accomplish the task? What would you have done differently?
Looking forward to reading your comments and answers.