Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Figuring out if all but one array elements are identical

Tags:

java

Does anyone know how I would work out if all elements in an array but one have the same value?

I have been trying to work it out for ages but cannot solve it. For example testing an array that has 5 elements to see if it has 4 identical values.

Thanks

like image 996
paul Avatar asked Mar 18 '26 21:03

paul


2 Answers

Use a map.

Map<X, Integer> map = new HashMap<X, Integer>(); // where X is the array type
Integer ct;
for(X item : array){
    ct = map.get(item);
    if(ct == 0) ct = Integer.valueOf(1);
    else ct = Integer.valueOf(ct.intValue()+1);
    map.put(item, ct);
}
// now test if map.values() consists of Integer.valueOf(1) and (optionally)
// another positive integer (thx aioobe)
like image 72
Sean Patrick Floyd Avatar answered Mar 20 '26 10:03

Sean Patrick Floyd


Step by Step:

  1. Get the first element.
  2. Loop all the array elements and count the number of times they don't match that first element.

    • If all of the elements match, you have your answer (all are equal).
    • If only one of the elements do not match, you have your answer (one is different).
    • If some of the elements do not match, you have your answer (more than one is different).
  3. In none of the elements match, get the second element and repeat the test.

    • If only one of the elements do not match, again only one is different (the first one).
    • Else, the number of different elements is bigger than one.
like image 29
SJuan76 Avatar answered Mar 20 '26 10:03

SJuan76



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!