I was reading a question posted here: Sudoku algorithm in C#
And one of the solutions posted was this piece of code.
public static bool IsValid(int[] values) {
int flag = 0;
foreach (int value in values) {
if (value != 0) {
int bit = 1 << value;
if ((flag & bit) != 0) return false;
flag |= bit;
}
}
return true;
}
The idea is that it will detect duplicates in the array of values; but I’m overwhelmed by how much I don’t know. Can someone explain this to me?
EDIT: Thanks everyone. So many great answers, I don’t know how to select one. It now makes perfect sense.
Really a nice idea.
Basically, it uses an
intflag (initially set to zero) as a “bit array”; for each value, it checks if the corresponding bit in the flag is set, and if it’s not, it sets it.If, instead, that bit position is already set, it knows that the corresponding value has already been seen, so the piece of Sudoku is invalid.
More in detail: