I'm looking for an elegant way to compute the score of a guess in the MasterMind game in Objective C, based on this article already on stackoverflow:
MasterMind scoring algorithm in C# using LIN开发者_JAVA百科Q
I assume you can do this in 'not so elegant' imperative way with NSArray
and NSSet
.
For functional approach used in LINQ solution you can either
1) google for some Objective-C functional lib - http://www.google.com/search?q=functional+programming+objective-c
or
2) implement required functions - Intersect
, Zip
, Count
, Sum
.
Intersect(a1, a2)
. Make sets from your arrays and make intersection withobjectsPassingTest:
.Zip(block, a1, a2)
. Iterate max(a1.count, a2.count) and push into answer array result of calling block on corresponding array elements.Count(predicate, array)
isSum((x -> predicate(x) ? 1 : 0), array)
Sum(block, array)
isFoldl((x, sum -> sum + block(x)), 0, array)
Foldl(block, init, array)
isid result = init; for (id obj in array) { result = block(result, obj); }
I believe no matter what approach you select result will be ugly as hell. Objective-C just isn't that kind of language.
For now I've come up with this (well, it's actually C but you can easily rewrite it using NSArray and isEqual)
int secret[] = { 1, 2, 3, 1 };
int guess[] = { 1, 1, 2, 2 };
int white = 0, black = 0;
for(int i=0; i<4; ++i) {
if( secret[i] == guess[i] ) {
secret[i] = 0;
++white;
continue;
}
for(int j=0; j<4; ++j) {
if( secret[j] == guess[i] ) {
secret[j] = 0;
++black;
break;
}
}
}
An answer inspired by Max's answer, but updated to deal with a case where (in my opinion) it provides the wrong answer:
int secret[] = { 1, 1, 2, 3 };
int guess[] = { 4, 1, 5, 1 };
int white = 0, black = 0;
for(int i=0; i<4; ++i) {
if( secret[i] == guess[i] ) {
secret[i] = 0;
++white;
continue;
}
for(int j=0; j<4; ++j) {
if( secret[j] == guess[i] ) {
if ( secret[j] == guess[j] ) {
++white;
} else {
++black;
}
secret[j] = 0;
break;
}
}
}
精彩评论