fork(3) download
  1. /* package kitchen.task33; */
  2.  
  3. /**
  4.  * [Одномерные массивы]
  5.  * В массиве целых чисел с количеством элементов n найти наиболее
  6.  * часто встречающееся число. Если таких чисел несколько, то
  7.  * определить наименьшее из них.
  8.  */
  9.  
  10. import java.util.Arrays;
  11.  
  12. public class Main {
  13.  
  14. public static final int ARRAY_MIN_LENGTH = 5;
  15. public static final int ARRAY_MAX_LENGTH = 9;
  16. public static final int ARRAY_ELEMENT_MIN_VALUE = 0;
  17. public static final int ARRAY_ELEMENT_MAX_VALUE = 9;
  18. public static final int TEST_COUNT = 5;
  19. public static final int OVER_9000 = Integer.MAX_VALUE;
  20.  
  21. public static void main(String[] args) {
  22. test(TEST_COUNT);
  23. }
  24.  
  25. public static int solve(int[] arr) {
  26. int result = OVER_9000;
  27. int count = 0;
  28.  
  29. for (int i = 0; i < arr.length; i++) {
  30. int curCount = 1;
  31.  
  32. for (int j = i + 1; j < arr.length; j++) {
  33. if (arr[i] == arr[j]) {
  34. curCount++;
  35. }
  36. }
  37.  
  38. if (curCount > count) {
  39. count = curCount;
  40. result = arr[i];
  41. } else if (curCount == count) {
  42. result = Math.min(result, arr[i]);
  43. }
  44. }
  45.  
  46. return result;
  47. }
  48.  
  49. public static int[] generateInputData(int n) {
  50. int[] res = new int[n];
  51. int diff = ARRAY_ELEMENT_MAX_VALUE - ARRAY_ELEMENT_MIN_VALUE + 1;
  52. for (int i = 0; i < n; i++) {
  53. res[i] = ARRAY_ELEMENT_MIN_VALUE + (int) (Math.random() * diff);
  54. }
  55. return res;
  56. }
  57.  
  58. public static void test(int testCount) {
  59. for (int i = 1; i <= testCount; i++) {
  60. System.out.printf("Test #%03d\n", i);
  61.  
  62. int diff = ARRAY_MAX_LENGTH - ARRAY_MIN_LENGTH + 1;
  63. int n = ARRAY_MIN_LENGTH + (int) (Math.random() * diff);
  64. int[] arr = generateInputData(n);
  65. int res = solve(arr);
  66.  
  67. System.out.println(Arrays.toString(arr));
  68. System.out.println(res);
  69. System.out.println();
  70. }
  71. }
  72.  
  73. }
  74.  
Success #stdin #stdout 0.08s 380224KB
stdin
Standard input is empty
stdout
Test #001
[1, 1, 8, 7, 3, 9, 6, 6, 6]
6

Test #002
[2, 2, 6, 1, 2, 8]
2

Test #003
[2, 9, 6, 4, 2, 5, 6, 1, 2]
2

Test #004
[2, 8, 5, 3, 1, 8, 0]
8

Test #005
[3, 7, 1, 0, 7]
7