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
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)
Step by Step:
Loop all the array elements and count the number of times they don't match that first element.
In none of the elements match, get the second element and repeat the test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With