Skip to content

Instantly share code, notes, and snippets.

@JJ
Last active December 10, 2015 17:18
Show Gist options
  • Save JJ/4466671 to your computer and use it in GitHub Desktop.
Save JJ/4466671 to your computer and use it in GitHub Desktop.
Compare two strings returning the number of symbols in the correct position ("blacks") and the number of symbols in the wrong position ("whites"), MasterMind style
#include <stdio.h>
#include <string.h>
// with help from http://www.eskimo.com/~scs/cclass/notes/sx13.html
int main( int argc, char *argv[] )
{
char *hidden = argv[1];
char *target = argv[2];
char colors = atoi( argv[3] );
printf( "Hidden %s target %s colors %d\n", hidden, target, colors);
int i;
int blacks = 0;
int whites = 0;
int colors_in_string_h[colors], colors_in_string_t[colors];
for ( i = 0; i < colors; i++ ) {
colors_in_string_h[i] = colors_in_string_t[i] = 0;
}
for ( i = 0; i < strlen( hidden ); i++ ) {
if ( hidden[i] == target[i] ) {
blacks++;
hidden[i] = target[i] = '.';
} else {
colors_in_string_h[hidden[i] - 'A']++;
colors_in_string_t[target[i] - 'A']++;
}
}
for ( i = 0; i < colors; i ++ ) {
if ( colors_in_string_h[i] && colors_in_string_t[i] ) {
whites += ( colors_in_string_h[i] < colors_in_string_t[i])?
colors_in_string_h[i]: colors_in_string_t[i];
}
}
printf("Result: b %d w %d \n", blacks, whites );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment