यह जांचता है कि सरणी में मान अद्वितीय हैं या नहीं। ऐसा करने के लिए, यह एक पूर्णांक बनाता है - ध्वज - और यह मानों की सरणी में मानों के अनुसार ध्वज में बिट्स सेट करता है। यह देखने के लिए जांच करता है कि कोई विशेष बिट पहले से सेट है या नहीं; यदि यह है, तो एक डुप्लिकेट है और यह विफल रहता है। अन्यथा, यह थोड़ा सेट करता है।
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.
}
स्रोत
2011-02-24 22:50:55
जाँच नहीं चाहेंगे कि 'मानों का योग 'अद्वितीय संभव अंकों के योग के बराबर है (9 x 9 गेम के लिए यह 45 होगा) उच्च स्तर की भाषा के लिए अधिक कुशल हो? – Anthony