CS 2420-20 Homework 4

Due: Tuesday, January 31st, 2012 9:10am

Part 1 – Manhattan Distance

Use this code as mdist.c:

  #include <stdio.h>
  #include <stdlib.h>
  
  struct posn {
    int x;
    int y;
  };
  
  /* define a mdist function here .... */
  
  int main(int argc, char** argv) {
     struct posn p = { atoi(argv[1]), atoi(argv[2]) };
     int d;
  
     d = mdist(p);
  
     printf("You'll have to walk %d blocks\n", d);
  
     return 0;
  }

Implement mdist so that the resulting program takes two small integers on the command line and prints the sum of the two numbers (which is the “Manhattan distance” from the origin, if you think of the two numbers as coordinates).

Part 2 – Walk South

Use this code as south.c:

  #include <stdio.h>
  #include <stdlib.h>
  
  struct posn {
    int x;
    int y;
  };
  
  /* define a walk_south function here .... */
  
  int main(int argc, char** argv) {
     struct posn p = { atoi(argv[1]), atoi(argv[2]) };
  
     walk_south(&p);
  
     printf("Now you're at (%d, %d)\n", p.x, p.y);
  
     return 0;
  }

Implement walk_south so that the resulting program takes two small integers on the command line and prints the first one followed by 6 more than the second one (which like walking 6 blocks south, if you think of the two numbers as street coordinates).

Part 3 – Allocate Positions

Use this code as flip.c:

  #include <stdio.h>
  #include <stdlib.h>
  
  struct posn {
    int x;
    int y;
  };
  
  typedef struct posn * point;
  
  point flip_point(point pt) {
     /* .... */
  }
  
  int main(int argc, char** argv) {
     struct posn p = { atoi(argv[1]), atoi(argv[2]) };
     point pt = &p;
     point pt2;
  
     pt2 = flip_point(pt);
  
     printf("Flipping (%d, %d) gives (%d, %d)\n",
            pt->x, pt->y,
            pt2->x, pt2->y);
  
     return 0;
  }

Implement flip_point so that it allocates a new point and doesn’t change the old point. You will need to use malloc. The new point should have the x and y cooridnates flipped compared to the original point.

For example, if the program is named flip, then

  flip 5 8

should print

  Flipping (5, 8) gives (8, 5)

Part 4 – Tests

Add tests to your programs, testing mdist for part 1, walk_south for part 2, and flip_point for part 3. In each case, the main function should call as test function to run the tests before continuing with the original call to the tested function.

Part 5 – Allocate and Use Lists

In feed.c, implement feed_fish, which takes a list of numbers and returns a list of numbers with each number incremented by one. The feed_fish function should not change the list that it is given. Include tests in your program.

Hint: The usual recursive feed_fish is not in tail form, so don’t try to start with a for loop.


Last update: Tuesday, January 24th, 2012
mflatt@cs.utah.edu