Advertisement
dimipan80

Most Frequent Number

Nov 12th, 2014
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a JavaScript function findMostFreqNum(arr) that finds the most frequent number in an array.
  2. If multiple numbers appear the same maximal number of times, print the leftmost of them.
  3. Write JS program numberFinder.js that invokes your function with the sample input data below
  4. and prints the output at the console. */
  5.  
  6. "use strict";
  7.  
  8. function findMostFreqNum(arr) {
  9.     if (arr.length > 1) {
  10.         arr.sort();
  11.         var equalsElements = 1;
  12.         var currentEquals = 1;
  13.         var repeatElement = arr[0];
  14.         var i;
  15.         for (i = 1; i < arr.length; i +=  1) {
  16.             if (arr[i] === arr[i - 1]) {
  17.                 currentEquals += 1;
  18.             } else {
  19.                 if (currentEquals > equalsElements) {
  20.                     repeatElement = arr[i - 1];
  21.                     equalsElements = currentEquals;
  22.                 }
  23.                 currentEquals = 1;
  24.             }
  25.         }
  26.  
  27.         if (currentEquals > equalsElements) {
  28.             repeatElement = arr[arr.length - 1];
  29.             equalsElements = currentEquals;
  30.         }
  31.  
  32.         return repeatElement + ' (' + equalsElements + ' times)';
  33.     } else if (arr.length == 1) return arr[0] + ' (1 times)';
  34.     else return 'undefined (0 times)';
  35. }
  36.  
  37. console.log(findMostFreqNum([4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3]));
  38. console.log(findMostFreqNum([2, 1, 1, 5, 7, 1, 2, 5, 7, 3, 87, 2, 12, 634, 123, 51, 1]));
  39. console.log(findMostFreqNum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]));
  40. console.log(findMostFreqNum([2.5]));
  41. console.log(findMostFreqNum(['a', 'b', 'c', 'a', 'A', 'b', 'c', 'c', 'C']));
  42. console.log(findMostFreqNum([]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement