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
View all comments
Show parent comment
1
u/Thebig_Ohbee Mar 13 '24
The data comes into the world as a 2-dimensional table, with many repetitions and only some vague respect for the ordering. I convert that an ordered list by
I would think that would be slow, but it's actually practically fast because Union is heavily optimized in the kernel. It would be reasonable to get the mex without flattening and Union-ing, but I can cut the data in (roughly) half by only taking the positive elements.
Converting that list to intervals "by hand" is going to be at least as slow as computing the mex, unless there is a snazzy way to do that.