CIT052 Index > awk Exercise 4

awk Exercise 4

Save the following data in a file named coordinates.txt.


A,0,0;B,3,4
C,4,7;D,2,9
E,8,2;F,0,6

Each line of the file contains the name of a point and its x-y coordinates, a semicolon, then the name of a second point and its x-y coordinates. Write an awk script that will do the following:

After you have processed all the records, generate two random numbers in the range 0 to 10 (inclusive). These will be coordinates for point "Q". Then generate two random numbers in the range 0 to 10 (inclusive) as point "R". Print the coordinates for these new points, then calculate and print the distance and city block distance for these new, random points.

Print the output to look like the following. Print only three numbers after the decimal point.

From A (0, 0) to B (3, 4): actual distance 5.000; city block distance 7
From C (4, 7) to D (2, 9): actual distance 2.828; city block distance 4
From E (8, 2) to F (0, 6): actual distance 8.944; city block distance 12
From Q (9, 2) to R (3, 7): actual distance 7.810; city block distance 11

When You Finish

Name your file in the form lastname_firstname_coordinates.awk and upload it to Moodle.

Pseudocode

BEGIN { FS="[;,]"}

function distance( x1, y1, x2, y2 ) {
  # set variable d to the square root of (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2)
  # return d
}

function city_block( x1, y1, x2, y2 ) {
  # set variable d1 to x1 - x2
  # if d1 is less than zero, set d1 to -d1

  # set variable d2 to y1 - y2
  # if d2 is less than zero, set d2 to -d2

  # set variable result to d1 + d2
  # return variable result
}

function show_point( name, x, y ) {
    # use a printf to print the three parameters -- don't use a \n
    # if variable name contains "A",
    # variable x contains 5, and variable y contains 7,
    # the printf should produce:
    # A (5, 7)
}

# $1 is point 1
# $2 is x1
# $3 is y1
# $4 is point 2
# $5 is x2
# $6 is y2

{
  # set variable actual to the distance from ($2, $3) to ($5, $6)
  # set variable city to the city block distance from ($2, $3) to ($5, $6)
  printf "From "
  # call show_point with parameters $1, $2, and $3.
  printf " to "
  # call show_point with parameters $4, $5, and $6
  # now call printf to display the variables actual and city
}

END {
  # seed the random number generator

  # set x1 to the integer part of a random number times 11 
  # set y1 to the integer part of a random number times 11 
  # set x2 to the integer part of a random number times 11 
  # set y2 to the integer part of a random number times 11 

  # set variable actual to the distance from (x1,y1) to (x2,y2)
  # set variable city to the city block distance from (x1,y1) to (x2, y2)
  printf "From "
  # call show_point with parameters "Q", x1, and y1
  printf " to "
  # call show_point with parameters "R", x2, and y2
  # now call printf to display the variables actual and city
}