Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Most Frequent
- // Write a program that finds the most frequent number in an array of N elements.
- // Input
- // On the first line you will receive the number N
- // On the next N lines the numbers of the array will be given
- // Output
- // Print the most frequent number and how many time it is repeated
- // Output should be REPEATING_NUMBER (REPEATED_TIMES times)
- // Constraints
- // 1 <= N <= 1024
- // 0 <= each number in the array <= 10000
- // There will be only one most frequent number
- // Sample tests
- // Input Output
- // 13
- // 4
- // 1
- // 1
- // 4
- // 2
- // 3
- // 4
- // 4
- // 1
- // 2
- // 4
- // 9
- // 3 4 (5 times)
- // reference https://www.w3resource.com/javascript-exercises/javascript-array-exercise-8.php
- const input = ['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3'];
- const print = this.print || console.log;
- const gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
- const numberOfItems = +gets();
- const arrOfItems = [];
- let frequentNumber;
- let frequency = 0;
- let frequentTimes = 1;
- for (let i = 0; i < numberOfItems; i++) {
- arrOfItems.push(+gets());
- }
- for (let i = 0; i < arrOfItems.length; i++) {
- for (let j = i; j < arrOfItems.length; j++) {
- if (arrOfItems[i] === arrOfItems[j]) {
- frequency++;
- }
- if (frequentTimes < frequency) {
- frequentTimes = frequency;
- frequentNumber = arrOfItems[i];
- }
- }
- frequency = 0;
- }
- print(`${frequentNumber} (${frequentTimes} times)`);
Advertisement
Add Comment
Please, Sign In to add comment