Advertisement
aseeshr

singleMode

Nov 18th, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. package june_18th_2016;
  2.  
  3. /**
  4.  * 1. Mode is the most frequently appearing value. Write a function
  5.  * named hasSingleMode that takes an array argument and returns 1 if the
  6.  * mode value in its array argument occurs exactly once in the
  7.  * array, otherwise it returns 0. If you are writing in Java or C#, the function
  8.  * signature is   int hasSingleMode(int[ ] ).   If you are writing in C or C++,
  9.  * the function signature is   int hasSingleMode(int a[ ], int len)   where len
  10.  * is the length of a.   Examples Array elements Mode values Value returned
  11.  * Comments 1, -29, 8, 5, -29, 6 -29 1 single mode 1, 2, 3, 4, 2, 4, 7 2, 4 0 no
  12.  * single mode 1, 2, 3, 4, 6 1, 2, 3, 4, 6 0 no single mode 7, 1, 2, 1, 7, 4, 2,
  13.  * 7, 7 1 single mode
  14.  *
  15.  *
  16.  */
  17. public class SingleMode {
  18.     public static void main(String[] args) {
  19.         System.out.println("Return number = " + hasSingleMode(new int[] { 1, -29, 8, 5, -29, 6 }));
  20.         System.out.println("Return number = " + hasSingleMode(new int[] { 1, 2, 3, 4, 2, 4, 7 }));
  21.         System.out.println("Return number = " + hasSingleMode(new int[] { 1, 2, 3, 4, 4, 4, 6, 6 }));
  22.         System.out.println("Return number = " + hasSingleMode(new int[] { 7, 1, 2, 2, 1, 7, 4, 2, 7 }));
  23.     }
  24.  
  25.     private static int hasSingleMode(int[] a) {
  26.  
  27.         boolean flag = false;
  28.         int maxCount = 0, count, retVal = 0;
  29.         for (int i = 0; i < a.length; i++) {
  30.             count = 1;
  31.             for (int j = 0; j < a.length; j++) {
  32.                 if (i != j && a[i] == a[j]) {
  33.                     count++;
  34.  
  35.                 }
  36.             }
  37.             if (count > maxCount) {
  38.                 retVal = a[i];
  39.                 maxCount = count;
  40.             } else if (a[i] != retVal && maxCount > 1 && count == maxCount) {
  41.                 retVal = a[i];
  42.                 // System.out.println(retVal);
  43.                 return 0;
  44.             }
  45.         }
  46.         // System.out.println(retVal);
  47.         return 1;
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement