Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package june_18th_2016;
- /**
- * 1. Mode is the most frequently appearing value. Write a function
- * named hasSingleMode that takes an array argument and returns 1 if the
- * mode value in its array argument occurs exactly once in the
- * array, otherwise it returns 0. If you are writing in Java or C#, the function
- * signature is int hasSingleMode(int[ ] ). If you are writing in C or C++,
- * the function signature is int hasSingleMode(int a[ ], int len) where len
- * is the length of a. Examples Array elements Mode values Value returned
- * Comments 1, -29, 8, 5, -29, 6 -29 1 single mode 1, 2, 3, 4, 2, 4, 7 2, 4 0 no
- * single mode 1, 2, 3, 4, 6 1, 2, 3, 4, 6 0 no single mode 7, 1, 2, 1, 7, 4, 2,
- * 7, 7 1 single mode
- *
- *
- */
- public class SingleMode {
- public static void main(String[] args) {
- System.out.println("Return number = " + hasSingleMode(new int[] { 1, -29, 8, 5, -29, 6 }));
- System.out.println("Return number = " + hasSingleMode(new int[] { 1, 2, 3, 4, 2, 4, 7 }));
- System.out.println("Return number = " + hasSingleMode(new int[] { 1, 2, 3, 4, 4, 4, 6, 6 }));
- System.out.println("Return number = " + hasSingleMode(new int[] { 7, 1, 2, 2, 1, 7, 4, 2, 7 }));
- }
- private static int hasSingleMode(int[] a) {
- boolean flag = false;
- int maxCount = 0, count, retVal = 0;
- for (int i = 0; i < a.length; i++) {
- count = 1;
- for (int j = 0; j < a.length; j++) {
- if (i != j && a[i] == a[j]) {
- count++;
- }
- }
- if (count > maxCount) {
- retVal = a[i];
- maxCount = count;
- } else if (a[i] != retVal && maxCount > 1 && count == maxCount) {
- retVal = a[i];
- // System.out.println(retVal);
- return 0;
- }
- }
- // System.out.println(retVal);
- return 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement