alboig

MostFrequent - JavascriptModule0

Apr 14th, 2020
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Most Frequent
  2. // Write a program that finds the most frequent number in an array of N elements.
  3.  
  4. // Input
  5. // On the first line you will receive the number N
  6. // On the next N lines the numbers of the array will be given
  7. // Output
  8. // Print the most frequent number and how many time it is repeated
  9. // Output should be REPEATING_NUMBER (REPEATED_TIMES times)
  10. // Constraints
  11. // 1 <= N <= 1024
  12. // 0 <= each number in the array <= 10000
  13. // There will be only one most frequent number
  14. // Sample tests
  15. // Input Output
  16. // 13
  17. // 4
  18. // 1
  19. // 1
  20. // 4
  21. // 2
  22. // 3
  23. // 4
  24. // 4
  25. // 1
  26. // 2
  27. // 4
  28. // 9
  29. // 3 4 (5 times)
  30. // reference https://www.w3resource.com/javascript-exercises/javascript-array-exercise-8.php
  31. const input = ['13', '4', '1', '1', '4', '2', '3', '4', '4', '1', '2', '4', '9', '3'];
  32. const print = this.print || console.log;
  33. const gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
  34. const numberOfItems = +gets();
  35. const arrOfItems = [];
  36. let frequentNumber;
  37. let frequency = 0;
  38. let frequentTimes = 1;
  39. for (let i = 0; i < numberOfItems; i++) {
  40.   arrOfItems.push(+gets());
  41. }
  42. for (let i = 0; i < arrOfItems.length; i++) {
  43.   for (let j = i; j < arrOfItems.length; j++) {
  44.     if (arrOfItems[i] === arrOfItems[j]) {
  45.       frequency++;
  46.     }
  47.     if (frequentTimes < frequency) {
  48.       frequentTimes = frequency;
  49.       frequentNumber = arrOfItems[i];
  50.     }
  51.   }
  52.   frequency = 0;
  53. }
  54. print(`${frequentNumber} (${frequentTimes} times)`);
Advertisement
Add Comment
Please, Sign In to add comment