How to Test If All Items in an Array Are Identical

Check if all values of array are equal

const allEqual = arr => arr.every( v => v === arr[0] )
allEqual( [1,1,1,1] ) // true

Or one-liner:

[1,1,1,1].every( (val, i, arr) => val === arr[0] )   // true

Array.prototype.every (from MDN) :
The every() method tests whether all elements in the array pass the test implemented by the provided function.

Check if each item in an array is identical in JavaScript

function identical(array) {
for(var i = 0; i < array.length - 1; i++) {
if(array[i] !== array[i+1]) {
return false;
}
}
return true;
}

Check if all elements in a list are identical

Use itertools.groupby (see the itertools recipes):

from itertools import groupby

def all_equal(iterable):
g = groupby(iterable)
return next(g, True) and not next(g, False)

or without groupby:

def all_equal(iterator):
iterator = iter(iterator)
try:
first = next(iterator)
except StopIteration:
return True
return all(first == x for x in iterator)

There are a number of alternative one-liners you might consider:

  1. Converting the input to a set and checking that it only has one or zero (in case the input is empty) items

    def all_equal2(iterator):
    return len(set(iterator)) <= 1
  2. Comparing against the input list without the first item

    def all_equal3(lst):
    return lst[:-1] == lst[1:]
  3. Counting how many times the first item appears in the list

    def all_equal_ivo(lst):
    return not lst or lst.count(lst[0]) == len(lst)
  4. Comparing against a list of the first element repeated

    def all_equal_6502(lst):
    return not lst or [lst[0]]*len(lst) == lst

But they have some downsides, namely:

  1. all_equal and all_equal2 can use any iterators, but the others must take a sequence input, typically concrete containers like a list or tuple.
  2. all_equal and all_equal3 stop as soon as a difference is found (what is called "short circuit"), whereas all the alternatives require iterating over the entire list, even if you can tell that the answer is False just by looking at the first two elements.
  3. In all_equal2 the content must be hashable. A list of lists will raise a TypeError for example.
  4. all_equal2 (in the worst case) and all_equal_6502 create a copy of the list, meaning you need to use double the memory.

On Python 3.9, using perfplot, we get these timings (lower Runtime [s] is better):

for a list with a difference in the first two elements, groupby is fastestfor a list with no differences, count(l[0]) is fastest

check whether all the values in array is same or not in javascript

Here is one approach to how you might do this. A Set in javascript can only hold unique values, thus, if its size equates to 1, then the array has all equal values, if its size equates to something greater than one, then all the values are not unique:

Take a look at the snippet below:

const aArr = [1, 2, 3, 4, 5];const bArr = [1, 1, 1, 1, 1];
const isUniqueArr = arr => { const tmp = new Set(arr); if(tmp.size > 1) { return false; } return arr[0];}
console.log(isUniqueArr(aArr)); // expected: false
console.log(isUniqueArr(bArr)); // expected: 1

C++: Fastest method to check if all array elements are equal

int check(const int a[], int n)
{
while(--n>0 && a[n]==a[0]);
return n!=0;
}

fastest way to check if all elements in an array are equal

This algorithm is O(n) which is the fastest way to check all elements of a list because you only have to check each element only one time.

Now just because this is the fastest algorithm in finding if all elements equal a value doesn't mean you have optimized it to its fullest potential.

This then leaves room for a multi-threaded/multiprocessor implementation.

A solution using more cores or threads is splitting the array into the amount of thread/cores you want to process simultaneously i.e. if you have an array of 100 elements and want 10 threads running at the same time-- split the array into 10 pieces and run each section on the array.

Some psudo code:

 int from,to, threadCount = 10;
boolean check[threadCount];

int factor = array.length()/threadCount;
for(int i = 0; i < threadCount; i++){
from = i*factor;
to = i*factor+factor;
newThreadProcess(from, to, array, check[i]);
}

barrier(); //Wait till all the threads are done processing
for(int i = 0; i < threadCount; i++){
if(!check[i]) return false;
}
return true;

This is best when the array is very large

Check if all values in array are the same

All values equal the test value:

// note, "count(array_flip($allvalues))" is a tricky but very fast way to count the unique values.
// "end($allvalues)" is a way to get an arbitrary value from an array without needing to know a valid array key. For example, assuming $allvalues[0] exists may not be true.
if (count(array_flip($allvalues)) === 1 && end($allvalues) === 'true') {

}

or just test for the existence of the thing you don't want:

if (in_array('false', $allvalues, true)) {

}

Prefer the latter method if you're sure that there's only 2 possible values that could be in the array, as it's much more efficient. But if in doubt, a slow program is better than an incorrect program, so use the first method.

If you can't use the second method, your array is very large, and the contents of the array is likely to have more than 1 value (especially if the 2nd value is likely to occur near the beginning of the array), it may be much faster to do the following:

/**
* Checks if an array contains at most 1 distinct value.
* Optionally, restrict what the 1 distinct value is permitted to be via
* a user supplied testValue.
*
* @param array $arr - Array to check
* @param null $testValue - Optional value to restrict which distinct value the array is permitted to contain.
* @return bool - false if the array contains more than 1 distinct value, or contains a value other than your supplied testValue.
* @assert isHomogenous([]) === true
* @assert isHomogenous([], 2) === true
* @assert isHomogenous([2]) === true
* @assert isHomogenous([2, 3]) === false
* @assert isHomogenous([2, 2]) === true
* @assert isHomogenous([2, 2], 2) === true
* @assert isHomogenous([2, 2], 3) === false
* @assert isHomogenous([2, 3], 3) === false
* @assert isHomogenous([null, null], null) === true
*/
function isHomogenous(array $arr, $testValue = null) {
// If they did not pass the 2nd func argument, then we will use an arbitrary value in the $arr (that happens to be the first value).
// By using func_num_args() to test for this, we can properly support testing for an array filled with nulls, if desired.
// ie isHomogenous([null, null], null) === true
$testValue = func_num_args() > 1 ? $testValue : reset($arr);
foreach ($arr as $val) {
if ($testValue !== $val) {
return false;
}
}
return true;
}

Note: Some answers interpret the original question as (1) how to check if all values are the same, while others interpreted it as (2) how to check if all values are the same and make sure that value equals the test value. The solution you choose should be mindful of that detail.

My first 2 solutions answered #2. My isHomogenous() function answers #1, or #2 if you pass it the 2nd arg.

Check if all elements in an array are equal

All you need to change is the termination condition in the for loop to

i < newArr.Length - 1

so that you can compare array[i] with array[i + 1]. This change makes sure you do not get past the upper bound of the array.

How do I test if all items in an array are identical?

class Array
def same_values?
self.uniq.length == 1
end
end

[1, 1, 1, 1].same_values?
[1, 2, 3, 4].same_values?

What about this one? It returns false for an empty array though, you can change it to <= 1 and it will return true in that case. Depending on what you need.



Related Topics



Leave a reply



Submit