It checks to see if values in the array are unique. To do this, it creates an integer - flag - and it sets bits in the flag according to values in the array of values. It checks to see if a particular bit is already set; if it is, then there is a duplicate and it fails. Otherwise, it sets the bit.
Here's a breakdown:
public static bool IsValid(int[] values) {
int flag = 0; // <-- Initialize your flags; all of them are set to 0000
foreach (int value in values) { // <-- Loop through the values
if (value != 0) { // <-- Ignore values of 0
int bit = 1 << value; // <-- Left-shift 1 by the current value
// Say for example, the current value is 4, this will shift the bit in the value of 1
// 4 places to the left. So if the 1 looks like 000001 internally, after shifting 4 to the
// left, it will look like 010000; this is how we choose a specific bit to set/inspect
if ((flag & bit) != 0) return false; // <-- Compare the bit at the
// position specified by bit with the corresponding position in flag. If both are 1 then
// & will return a value greater than 0; if either is not 1, then & will return 0. E.g.
// if flag = 01000 and bit = 01000, then the result will be 01000. If flag = 01000 and
//bit = 00010 then the result will be 0; this is how we check to see if the bit
// is already set. If it is, then we've already seen this value, so return false, i.e. not
// a valid solution
flag |= bit; // <-- We haven't seen this value before, so set the
// corresponding bit in the flag to say we've seen it now. e.g. if flag = 1000
// and bit = 0100, after this operation, flag = 1100
}
}
return true; // <-- If we get this far, all values were unique, so it's a valid
// answer.
}
values
equals the sum of unique possible digits (for 9x9 game it would be 45) be more efficient for a high-level language? – Hydrodynamics