I need fastest way to find the values in array A that their mods is array B when divided by 4:
A = {4,5,6,7,8,9,10}
B={2,3}
result={6,7,10}
mine:
foreach (int b in B)
{
S= A.Where(n => n % 4 == b).ToArray();
foreach (int s in S)
{
newlist.Add(s);
}
}
newlist.Distinct().ToArray();
Why not:
If
Bcould be large, you could create aHashSet<int>instead, but if it’s really going to be mod 4, there’s no point.Alternatively, assuming you know that every element in
AandBis positive (and thatBdoesn’t have any silly values, like 5), you can mapBto abool[4]and use& 3instead of% 4: