Advertisement
Guest User

neutrino-count-occurence

a guest
May 12th, 2014
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Write a program that finds the most frequent number in an array.
  2. // Example: {4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3} -> 4 (5 times)    
  3. function mostFreqNum(arr) {
  4.     var count = {};    
  5.     var maxKey = arr[0];
  6.     var i, key;        
  7.     for (i = 0; i < arr.length; i++) {
  8.         key = arr[i];
  9.         if (count[key] == undefined) count[key] = 1;
  10.         else count[key]++;                
  11.         if (count[key] > count[maxKey]) maxKey = key;
  12.     }
  13.     console.log(arr);
  14.     console.log("Most frequent number: %d (%d times)", maxKey, count[maxKey]);  
  15. }    
  16. mostFreqNum([4, 1, 1, 4, 2, 3, 4, 4, 1, 2, 4, 9, 3]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement