teaching machines

CS 330 Lecture 17 – Higher-order Functions in C

March 3, 2014 by . Filed under cs330, lectures, spring 2014.

Agenda

TODO

Code

olympics.c

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

struct standing_t {
  const char *name;
  int ngolds;
  int nsilvers;
  int nbronzes;
};

int compare_by_medals(const void *a, const void *b) {
  struct standing_t *sa = (struct standing_t *) a;
  struct standing_t *sb = (struct standing_t *) b;
  int nmedals_a = sa->ngolds + sa->nsilvers + sa->nbronzes;
  int nmedals_b = sb->ngolds + sb->nsilvers + sb->nbronzes;
  return nmedals_b - nmedals_a;
  /*
   for a to appear in list before b, we'd need to return negative

   if nmedals_a > nmedals_b
     return negative
   else if nmedals_a < nmedals_b
     return positive
   else
     return 0
   */
}

int compare_by_bronzes(const void *a, const void *b) {
  struct standing_t *sa = (struct standing_t *) a;
  struct standing_t *sb = (struct standing_t *) b;
  return sb->nbronzes - sa->nbronzes;
}

int main(int argc, char **argv) {
  const int NSTANDINGS = 7;

  struct standing_t standings[] = {
    {"Canada", 10, 10, 5},
    {"Norway", 11, 5, 10},
    {"Switzerland", 6, 3, 2},
    {"United States", 9, 7, 12},
    {"Russia", 13, 11, 9},
    {"Germany", 8, 6, 5},
    {"Netherlands", 8, 7, 9},
  }; 

  qsort(standings, NSTANDINGS, sizeof(struct standing_t), compare_by_bronzes);

  for (int i = 0; i < NSTANDINGS; ++i) {
    printf("%d - %s %d %d %d\n", i + 1, standings[i].name, standings[i].ngolds, standings[i].nsilvers, standings[i].nbronzes);
  }

  return 0;
}

torus.c

#include <stdio.h>
#include <stdlib.h>
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

int x_angle = 0;
int y_angle = 0;

void on_draw() {
  glClear(GL_COLOR_BUFFER_BIT);
  glLoadIdentity();
  glRotatef(x_angle, 1.0f, 0.0f, 0.0f);
  glRotatef(y_angle, 0.0f, 1.0f, 0.0f);
  glutWireTorus(0.3f, 0.5f, 10, 10);
  glutSwapBuffers();
}

void on_key(unsigned char key, int mouse_x, int mouse_y) {
  switch (key) {
    case 'x':
      ++x_angle;
      break;
    case 'X':
      --x_angle;
      break;
    case 'y':
      ++y_angle;
      break;
    case 'Y':
      --y_angle;
      break;
  }

  glutPostRedisplay();
}

int main(int argc, char **argv) {
  glutInit(&argc, argv);
  glutCreateWindow("My first torus");
  glutDisplayFunc(on_draw);
  glutKeyboardFunc(on_key);
  glutMainLoop();
  printf("asdfklasdflkasdjfklasd");

  return 0;
}

Haiku

To f, one must g
x got jealous and stormed off
g said, “Where’s my x?”