Created
April 5, 2014 03:31
-
-
Save jimexist/9987138 to your computer and use it in GitHub Desktop.
number guessing game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
#include<assert.h> | |
#include<stdbool.h> | |
#define DUP (-1) | |
#define INVALID (-2) | |
static int comp(int a, int b, int c, int d) { | |
if (a == c) { | |
if (b == d) { | |
return DUP; | |
} | |
return a; | |
} else if (a == d) { | |
if (b == c) { | |
return DUP; | |
} | |
return b; | |
} else if (b == c) { | |
if (a == d) { | |
return DUP; | |
} | |
return b; | |
} else if (b == d) { | |
if (a == d) { | |
return DUP; | |
} | |
return b; | |
} | |
return INVALID; | |
} | |
static int do_guess(int size, int* guess, int* reply) { | |
if (size < 2) { | |
return DUP; | |
} | |
int prime = guess[0] + reply[0]; | |
int less = guess[0] - reply[0]; | |
bool only_one = false; | |
for (int i=1; i<size; ++i) { | |
int a = guess[i] + reply[i]; | |
int b = guess[i] - reply[i]; | |
if (only_one) { | |
if (a != prime && b != prime) return INVALID; | |
} else { | |
int result = comp(prime, less, a, b); | |
switch (result) { | |
case DUP: break; | |
case INVALID: return INVALID; | |
default: | |
prime = result; | |
only_one = true; | |
break; | |
} | |
} | |
} | |
return only_one ? prime : DUP; | |
} | |
int main(int argc, char* argv[]) { | |
int size = atoi(argv[1]); | |
assert(size * 2 == argc - 2); | |
int* guess = (int*) malloc(sizeof(int) * size); | |
int* reply = (int*) malloc(sizeof(int) * size); | |
for (int i=0; i<size; ++i) { | |
guess[i] = atoi(argv[i+2]); | |
reply[i] = atoi(argv[i+2+size]); | |
} | |
int result = do_guess(size, guess, reply); | |
printf("%d\n", result); | |
free(guess); | |
free(reply); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment