teaching machines

CS 330 Lecture 17 – Higher-order functions

March 5, 2012 by . Filed under cs330, lectures, spring 2012.

Agenda

TODO

Program This

With a neighbor, write a short C function that chooses a random number between 0 and 100 and lets a computer player guess until it picks the right answer.

Code

guess_a_number.c

#include <stdio.h>
#include <stdlib.h>

/* ------------------------------------------------------------------------- */

enum feedback_t {
  NO_FEEDBACK,
  TOO_LOW,
  TOO_HIGH,
  JUST_RIGHT
};

/* ------------------------------------------------------------------------- */

int get_guess_random(enum feedback_t feedback) {
  return (int) (rand() / (float) RAND_MAX * 100.0f);
}

/* ------------------------------------------------------------------------- */

int get_guess_linear(enum feedback_t feedback) {
  static int my_last_guess = -1;
  ++my_last_guess;
  return my_last_guess;
}

/* ------------------------------------------------------------------------- */

#if 0
int get_guess(enum feedback_t feedback) {
  static int my_last_guess = -1;
  if (feedback == NO_FEEDBACK) {
    my_last_guess
    return 50;
  } else if (feedback == TOO_LOW) {
    return 
  }
}
#endif

/* ------------------------------------------------------------------------- */

void play(int (*get_guess)(enum feedback_t feedback)) {
  int answer = (int) (rand() / (float) RAND_MAX * 100.0f);
  int guess = -1;
  int ntries = 0;
  enum feedback_t feedback = NO_FEEDBACK;

  while (feedback != JUST_RIGHT) {
    ++ntries;
    guess = get_guess(feedback);

    if (guess < answer) {
      feedback = TOO_LOW;
    } else if (guess > answer) {
      feedback = TOO_HIGH;
    } else {
      feedback = JUST_RIGHT;
    }
  }

  printf("ntries: %d\n", ntries);
}

/* ------------------------------------------------------------------------- */

int main(int argc, char **argv) {
  srand(time(NULL));
  play(get_guess_linear);
  play(get_guess_random);
  return 0;
}

Haiku

SETI: waste of time.
Random function pointers: sweet!
Garbage can be smart.