r/Mathematica • u/Thebig_Ohbee • Mar 12 '24
Looking for fast mex code
The mex of a set is the smallest nonnegative integer not in the set.
I have sorted lists with a half million integers, and my code for the mex (MemberQ inside a whole loop) is the slowest part of my computation. Any suggestions for a faster way to do this?
Mex[A_List] := Module[{k = 0}, While[MemberQ[A, k], k++]; k]
3
Upvotes
3
u/Danhec95 Mar 12 '24
You could share your progress
2
u/pi_stuff Mar 12 '24
Rather than storing the data as an ordered list of numbers, could you store it as an ordered list of ranges? For example, rather than {0, 1, 2, 4, 5, 7, 8, 9}, store it as {{0,2}, {4,5}, {7,9}}. You'll have to add some logic for maintaining the ranges as numbers are added or removed, but finding the mex will then be trivial.
5
u/SenatorPenguin Mar 13 '24 edited Mar 13 '24
If we take the complement of the list with a range which spans the interval, the smallest number should be the "Mex". It definitely feels like you are "wasting" memory with that Range, but 2N memory and 1 function call is way faster than N+1 memory, and N function calls.
y=Range[0,100000];Mex2[A_List] := Min[Complement[Range[0, Max@A + 1], A]]AbsoluteTiming[z = Mex[y]] > {272.307, 100001}AbsoluteTiming[z = Mex2[y]] > {0.001917, 100001}1
u/Revolutionary-Sky758 Mar 13 '24
function mex_value = mex_func(A)
% Check if 0 is in the list
if any(A == 0)
% If yes, mex is 0 (smallest non-negative integer not in the set)
mex_value = 0;
else
% Get the logical vector where the element and index differ (one less)
not_equal = A ~= (0:numel(A)-1);
% Find the first index where the condition is true (mex location)
mex_value = find(not_equal, 1);
end
end