teaching machines

CS 330 Lecture 24 – Memory, Polymorphism, and Higher-order Functions

April 3, 2015 by . Filed under cs330, lectures, spring 2015.

Agenda

TODO

Program This

Code

multireturn.c

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

/* [int, int] divmod(int numerator, int denominator) { */
  /* return [numerator / denominator, numerator % denominator]; */
/* } */

void divmod(int numerator, int denominator, int *quotient, int *remainder) {
  *quotient = numerator / denominator;
  *remainder = numerator % denominator;
}

int main(int argc, char **argv) {
  int quotient, remainder;
  divmod(500, 9, &quotient, &remainder);  
  printf("quotient: %d\n", quotient);
  printf("remainder: %d\n", remainder);
  return 0;
}

poly.c

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

int find_minear(void *list,
                int nbytes_per_element,
                int nelements,
                int (*compare)(void *a, void *b)) {
  // assume first is min
  // for each remaining element
  //   try to oust min with element i
  //
  // return i
  int imin = 0;
  for (int i = 1; i < nelements; ++i) {
    void *min_so_far = list + imin * nbytes_per_element; 
    void *usurper = list + i * nbytes_per_element; 
    if (compare(min_so_far, usurper) > 0) {
      imin = i;
    }
  }

  return imin;
}

int int_compare(void *a, void *b) {
  int *ai = (int *) a;
  int *bi = (int *) b;
  if (*ai < *bi) {
    return -1;
  } else if (*ai == *bi) {
    return 0;
  } else {
    return 1;
  }
}

int main(int argc, char **argv) {
  int numbers[] = {
    9, 7, 99, 42, 12, 3, 500, 999
  };

  int imin = find_minear(numbers, sizeof(int), 8, int_compare);
  printf("numbers[imin]: %d\n", numbers[imin]);

  return 0;
}

torus.c

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

#include <GLUT/glut.h>

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("sdafasd\n");
  return 0;
}

Haiku

an algorithm with holes:
To live a _____ life
Drink 8 _____ everyday
Marry your first _____