Task

Write a player for the game that follows the following rules:

The scorer will choose a number between set limits. The computer player will print a guess of the target number. The computer asks for a score of whether its guess is higher than, lower than, or equal to the target. The computer guesses, and the scorer scores, in turn, until the computer correctly guesses the target number.
The computer should guess intelligently based on the accumulated scores given. One way is to use a Binary search based algorithm.



Related tasks

   Guess the number/With Feedback
   Bulls and cows/Player


#import <Foundation/Foundation.h>
 
@interface GuessNumberFakeArray : NSArray {
  int lower, upper;
}
- (instancetype)initWithLower:(int)l andUpper:(int)u;
@end
 
@implementation GuessNumberFakeArray
- (instancetype)initWithLower:(int)l andUpper:(int)u {
  if ((self = [super init])) {
    lower = l;
    upper = u;
  }
  return self;
}
- (NSUInteger)count { return upper-lower; }
- (id)objectAtIndex:(NSUInteger)i {
  printf("My guess is: %d. Is it too high, too low, or correct? (H/L/C) ", lower + (int)i);
  char input[2] = " ";
  scanf("%1s", input);
  switch (tolower(input[0])) {
    case 'l':
      return @-1;
    case 'h':
      return @1;
    case 'c':
      return @0;
  }
  return nil;
}
@end
 
#define LOWER 0
#define UPPER 100
 
int main(int argc, const char *argv[]) {
  @autoreleasepool {
 
    printf("Instructions:\n"
           "Think of integer number from %d (inclusive) to %d (exclusive) and\n"
           "I will guess it. After each guess, you respond with L, H, or C depending\n"
           "on if my guess was too low, too high, or correct.\n",
           LOWER, UPPER);
    NSUInteger result = [[[GuessNumberFakeArray alloc] initWithLower:LOWER andUpper:UPPER]
                         indexOfObject:[NSNumber numberWithInt: 0]
                         inSortedRange:NSMakeRange(0, UPPER - LOWER)
                               options:0
                       usingComparator:^(id x, id y){ return [x compare: y]; }];
    if (result == NSNotFound)
      printf("That is impossible.\n");
    else
      printf("Your number is %d.", LOWER + (int)result);
 
  }
  return 0;
}