CS 2420-20 Homework 3

Due: Thursday, January 27th, 2011 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)

Last update: Thursday, April 7th, 2011
mflatt@cs.utah.edu