I am trying to write a simple program that uses Julia to test if all elements of an array are the same. Is there a simple way to do this in Julia?
allunique
tests if all elements of an array are unique. In order to test if all elements of an array are the same you can write e.g.:
function allequal(itr)
local x
isfirst = true
for v in itr
if isfirst
x = v
isfirst = false
else
isequal(x, v) || return false
end
end
return true
end
and now you have
julia> allequal([1,2,3])
false
julia> allequal([1,2,1])
false
julia> allequal([1,1,1])
true
You could write a shorter function like e.g.:
f1(itr) = length(Set(itr)) <= 1
but it probably will be slower (I have not run the benchmarks).
or you could write something like:
f2(itr) = length(itr) == 0 ? true : all(isequal(itr[1]), itr)
if your iterable has length
defined and supports indexing.
-
Great catch and answer. Sorry about that. Had a little bit of a brain malfunction there :) – logankilpatrick Dec 20 '19 at 14:14
-
1
all( isequal(first(itr)), itr)
also works if the iterator doesn't support indexing, no? – crstnbr Dec 20 '19 at 14:20 -
Yes, but you have to check that
itr
is not empty additionally as a special case. – Bogumił Kamiński Dec 20 '19 at 15:46 -
also
first
might alter the state of some iterables, and in general if they supportgetindex
it is rather safe to assume that using it will not affect it. – Bogumił Kamiński Dec 20 '19 at 16:05
length(itr)==0 || all( ==(itr[1]), itr)
This seems to be 3x faster than the proposed allequal
function.
Some benchmarks:
julia> allequal_2(itr) = length(itr)==0 || all( ==(itr[1]), itr);
julia> const vv = ones(10000000)*3;
julia> @btime allequal($vv)
13.212 ms (0 allocations: 0 bytes)
true
julia> @btime allequal_2($vv)
4.178 ms (0 allocations: 0 bytes)
true
What is even more interesting it is 2x faster than the proposed very similar f2
function:
julia> @btime f2($vv)
9.509 ms (0 allocations: 0 bytes)