CSCI 134 Williams College Fall 2017
Scribbler 2
CSCI 134:
Algorithmic Problem Solving with Robots
Scribbler 2
Course Home Course Links Course Details: Syllabus, Schedule, Deadlines, Topic organization MyroC Documentation MyroC Project/
Acknowledgments

Note: Although this course is well developed,
expect adjustments in some details as the semester progresses and the course evolves.

Supplemental Problems

Supplemental Problems extend the range of problems considered in the course and help sharpen problem-solving skills. To support this objective, all Supplemental Problems are to be done individually.

Problems numbered 6 or higher may be turned in for extra credit. However, no more than 2 extra-credit problems may be turned in during the last week of classes (December 2-8, 2017). (If more than 2 extra-credit supplemental problems are submitted during the last week of classes, only the first two submitted will be graded.)

Quick links: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15

Submission Details

Use the link, Detailed Coursework Instructions, to find specific instructions regarding code, submission, and testing of supplemental problems.

Points Available

Some Grading Notes:

Classifying SAT and ACT Scores

  1. Each fall, the Departments of Computer Science and Mathematics and Statistics at one college provide recommended placements for incoming students in first courses in computer science, mathematics, and statistics. Overall, the process involves about 125 rules within a reasonably complex computer-based system.

    One of the early steps in this process involves the classification of standardized scores, based on student scores on the SAT and/or ACT. The following edited table suggests the basic framework for a classification.

    Category SAT Range ACT Range
    Superior 700– 31–
    Excellent 640–690 28–30
    Strong 600–630 26–27
    Good 550–590 24–25
    Adequate 480–540 20–23
    Participating –470 –19

    Although this table provides a starting point, students scores sometimes differ substantially from one test to another. This leads to the following rules for determining the actual category for a student' standardized scores.

    • If a student takes the SAT or the ACT, but not both, then the above table provides the classification.
    • If a student takes both the SAT and ACT,
      • the student's classification is the higher of the two categories from the above table, EXCEPT
      • if the categories differ by three or more levels, then the top category is lowered by one.
    • If a student has not taken either the SAT or ACT, the category is specified as "Unknown".

    Examples:

    • A student with a 650 SAT or 28 ACT (or both) would be placed in category "Excellent" for standardized scores.
    • A student with a 650 SAT and 24 ACT would be placed in category "Excellent", based on the 650 SAT. (The 24 ACT is two categories lower than the 650 SAT, and difference of two categories is not enough to lower the classification.)
    • A student with a 650 SAT and a 23 ACT would be placed in category "Strong". (The "Excellent" category from the SAT would be lowered by one, since the 23 ACT is three categories lower.)

    Write a program that computes the appropriate category for a specified SAT and ACT score. Rather than read SAT or ACT scores from the keyboard, the program should assign an SAT and ACT score to variables at the very beginning of the program. If the student has not taken an SAT or an ACT test, then the variable for that test should be set to 0.

    General feedback form
    Problem-specific grading form for Supplemental Problem 1

  1. Mortgage Payments

    The monthly payment on a mortgage which will amortize (be paid off) in N years with a given annual interest rate is given by the formulae:

        monthlyRate = rate / 1200.0
        payment = amount * monthlyRate / (1.0 - (1 + monthlyRate)(-12*N))

    where amount is the amount borrowed.

    Write a program that computes the monthly payment and total amount paid over the life of the loan, and produces a table of the following form:

    annual rate years amount monthly payment total paid
    8.75 25 26000 213.76 64128.00
    5.35 30 90000
    5.35 20 90000
    4.35 25 90000
    ...

    Your program should have these features:

    • Three functions should be defined:
      • double compute_neg_power (double value, int n)
        that returns 1 / (value)n.
        (In the computation, the function should use successive multiplications (or successive divisions) rather than the more general, but less efficient, C library pow function.)
      • double compute_payment (double annRate, int years, double amt)
        that returns the monthly payment for the given parameters.
      • double total_paid( (double annRate, int years, double amt)
        that returns the total amount paid over the life of the loan.
      • Neither function should print anything.
        Rather each function should return the desired value, to be used or printed elsewhere.
      • total_paid should call compute_payment.
    • The main procedure should have three parallel arrays, each with the same number of entries:
      • array annualRate should contain various annual interest rates.
      • array years should contain various lengths of mortgages, given in years.
      • array amount should contain various amounts borrowed.
    • The ith row of the table should given the monthly payment and total amount paid for a computation involving annualRate[i], years[i], and amount[i].
      For example, for the table given above, the first part of each array would be as follows:
      array values for first table row:
      • annualRate[0] = 8.75;
      • years[0] = 25;
      • amount[0] = 26000;
      array values for second table row:
      • annualRate[1] = 5.35;
      • years[1] = 30;
      • amount[1] = 90000;
      array values for third table row:
      • annualRate[2] = 5.35;
      • years[2] = 20;
      • amount[2] = 90000;
      array values for fourth table row:
      • annualRate[3] = 4.35;
      • years[3] = 25;
      • amount[3] = 90000;
      ...

    General feedback form
    Problem-specific grading form for Supplemental Problem 2

Histogram of Letters

  1. When given a number of data elements, it sometimes is convenient to visualize how many times each outcome occurs. For example, in reviewing text, we might count the number of times each letter occurs (ignoring case), and then print this number of asterisks (*) for each letter. The resulting diagram is called a histogram. As an illustration, the following diagram shows a histogram for the letter counts in this paragraph.

    Histogram follows:
             *                                          
             *                                          
             *                                          
             *                                          
             *                                          
             *                             *            
             *                             *            
             *                             *            
             *                             *            
             *                             *            
             *       *                     *            
             *       *                     *            
     *       *       *                     *            
     *       *       *                     *            
     *       *       *                     *            
     *       *       *                     *            
     *       *       *         * *     * * *            
     *       *       *         * *     * * *            
     *       *       *         * *     * * *            
     *       *       *         * *     * * *            
     *       *       *         * *     * * *            
     *       *       *         * *     * * *            
     *       *     * *         * *     * * *            
     *       *     * *       * * *     * * *            
     *       *     * *       * * *     * * *            
     *   *   *     * *       * * *     * * *            
     *   *   *     * *     * * * *     * * *            
     *   *   *   * * *     * * * *     * * *            
     *   *   *   * * *     * * * *     * * * *          
     *   *   *   * * *     * * * *     * * * *          
     *   *   *   * * *     * * * *     * * * *          
     *   *   *   * * *     * * * *     * * * *          
     *   *   * * * * *     * * * *     * * * *          
     *   *   * * * * *     * * * *     * * * *   *      
     *   * * * * * * *     * * * *     * * * *   *      
     *   * * * * * * *     * * * * *   * * * * * *      
     * * * * * * * * *     * * * * *   * * * * * *      
     * * * * * * * * *     * * * * *   * * * * * * *    
     * * * * * * * * *   * * * * * *   * * * * * * * * *
     a b c d e f g h i j k l m n o p q r s t u v w x y z
    

    Programming Notes:

    • This program should allow any number of characters to be entered before the # character is typed, and the input may be on one or more lines.
    • In this histogram of letters, all non-letters should be ignored.
    • Use of C functions, tolower and isalpha, within the ctype.h library is encouraged.
    • In order to determine the number of lines in the histogram, the program will need to determine the maximum count for any letter. For letters with this maximum count, the histogram will have a column of asterisks that goes from the top row to the bottom (just before the row of printed letters).

    General feedback form
    Problem-specific grading form for Supplemental Problem 3

Emergency Telephones

  1. [This problem is inspired by Problem 3 on the 1985 Advanced Placement Computer Science Examination; folklore now sometimes refers to this exercise as "The Dreaded TelLocs Problem".]

    The arrangement of streets in many midwestern cities resembles a 2-dimensional grid. If emergency telephones are placed at the intersection of streets, then their location can be modeled by a 2-dimensional array:

    
        #define north_south_size 20
        #define east_west_size   25
        int tel_locs [north_south_size] [east_west_size];
    

    For this array, the location tel_locs[0][0] is considered to be in the southwestern corner of the grid; and the location tel_locs[1][2] has the location that is north 1 block and east 2 blocks of the southwestern corner of the grid.

    Within this array, tel_locs[i][j] is 1 if an emergency telephone is located at intersection of streets i and j, and tel_locs[i][j] is 0 otherwise.

    In a certain city, intersection [r][s] is considered "safe" if the [r][s] is within 2 blocks of an emergency telephone — moving north or west. Thus, (ignoring the edge of the array), [r][s] is "safe" if there is an emergency telephone at [r][s], [r+1][s], [r+2][s], [r][s-1], [r][s-2], or [r+1][s-1]. (Due to one-way streets, the notion of "safe" does not consider emergency telephones located to the south or east of intersections.)

    Write a C program that analyzes a proposed placement of emergency telephones in a city to determine if all intersections in the city can be considered "safe". The program should have these characteristics:

    1. The array tel_locs should be declared and initialized as part of the main procedure. (You should not read in the placement of telephones; the program will have to be edited for each proposed telephone placement.)
    2. A function safe should take a location and a tel_locs array as parameters and return 1 or 0 if the location is "safe" or not, respectively. (The function should not print anything—just return the value 1 or 0.)
    3. The program should print the coordinates of any intersection that is not "safe".
    4. The end of the program should indicate "all safe" if all intersections in the city are "safe" or "unsafe intersections exist" if there is at least one intersection that is not "safe".

    General feedback form
    Problem-specific grading form for Supplemental Problem 4

Singly-linked-list Processing

  1. Program namelist-2017-fa.c contains a simple framework for maintaining a singly-linked list of names (with no more than 20 characters). The program has these features:

    • A singly-linked-list structure is defined.
    • The list is initially null.
    • A basic menu identifies several processing options, the program reads a user option, and the program calls a procedure for that option.
    • Procedure addName allows names to be added anywhere on the list.
    • Procedure print allows current names to be printed from the first to the last.

    This problem asks you to implement two additional functions within this program.

    • Function printEachNameOnce produces a listing of each name on the current list, with each name appearing exactly once:

      • Each name on the current list is printed (in some order).
      • No names are printed more than once.
      • If a name appears more than once on the original list, its name may appear anywhere in the final printed list.

      In this printing operation, the original list may not be changed in any way. Use of new arrays or linked lists is allowed within this procedure, but no new arrays or list nodes should be defined in order to receive full credit.

    • Function insertLast utilizes two parameters.

      • The address of a pointer to the first node on the list.
      • A pointer to the string to be included in the new node.

      In this processing a new node is created, and it is placed in a new node at the end of the current list.

      • Except for the new node, the program should not create any additional arrays, structs, linked lists, or other structures. (Creating a few local variables for pointers, ints, doubles, or other individual data elements is fine).
      • This problem may be done either iteratively or recursively for full credit.
      • Extra credit will be considered if two procedures are developed, insertLastIter and insertLastRec, the first of which inserts at the end using an iterative algorithm and the second of which inserts at the end using a recursive algorithm.

    Programming Hints:

    • In Program namelist-2017-fa.c, code for addName and print should not be changed in any way.
    • Program namelist.c also contains stubs for the new operations, but the bodies of these procedures only print a message that the operations are not implemented. This problem asks you to expand these stubs to working procedures.
    • Although code within the existing addName procedure itself should not be changed, parts of that code could be copied, modified, and streamlined in another procedure.

    General feedback form
    Problem-specific grading form for Supplemental Problem 5


Any of the following problems may be done for extra credit. As noted in the course syllabus, however, a student's overall problems' average may not exceed 120%.

Multiplication of Three-digit Numbers

  1. [approximately 10 points] Write a program that reads two three-digit integers from the keyboard and then prints their product as shown in the following example:

    Enter first number:  749
    Enter second number: 381
    
    
                   749
               x   381
               -------
                   749
                 5992
                2247
               -------
                285369
    

    Use the following cases as part of your testing:

    • 749 381
    • 381 749
    • 599 100
    • 120 102
    • 102 120

    Notes: In this problem:

    • you may use integer formatting with the %d format specification for integers within printf statements. You should not be using if statements in this problem for formatting.
    • solutions using strings (e.g., arrays of characters) are quite inefficient for extracting digits from numbers. Further, the problem can be solved efficiently with simple arithmetic operations. Altogether, the use of strings in this problem will yield very little credit (e.g., 1 point maximum).

Making Change

  1. [approximately 12 points] Write a program that reads the cost of an item and the amount paid by the customer, and then prints out the difference (the amount owed to the customer). Also print out how many bills of each denomination should be given to the customer (one-, five-, ten-, and twenty-dollar bills), and the remainder to be paid in coins.

    Notes:

    • Rather than read the cost and amount paid, the program should assign the cost of an item and the amount paid by the customer to variables at the very beginning of the program.
    • The output should have the following form, using correct grammar:
      Enter item cost:  $ 12.75
      Enter amount paid:  $ 20.00
      Change:  $ 7.25
         0 twenties
         0 tens
         1 five
         2 ones
         0.25 change
      

      Here is another example:

      Enter item cost:  $ 18.45
      Enter amount paid:  $ 50.00
      Change:  $ 31.55
         1 twenty
         1 ten
         0 fives
         1 one
         0.55 change
      

      In summary, "twenty", "ten" "five", "one" (singular) appear if the number of bills is one, but "twenties", "tens", "fives", and "ones" (plural) appear if the number of bills is either zero or greater than one.

    • Your computation should use the fewest number of bills.
    • Do NOT try to compute how many of each coin type should be given to the customer (pennies, nickels, dimes, and quarters).

Common Letters

  1. [approximately 12 points] Write a program that reads two strings and counts how many letters the strings have in common. To determine common letters, each letter of one word should be matched with exactly one letter of the second word. the case of the letters (upper case versus lower case) should be ignored.)

    Examples:

    • "room" and "tool" have two letters in common (each "o" in "room" is matched with a separate "o" in "tool").
    • "fewer" and "red" have two letters in common (the "e" in "red" matches one of the "e"s in "fewer" and both words contain one "r").
    • "Mississippi" and "Iowa" has just one letter in common (the "I" of Iowa matches one of the "i"s in "Mississippi").
    Notes:
    • Each string should be entered on a line by itself.
    • In this problem, you may assume each string will be no more than 40 characters in length.
    • The strings in this problem may contain letters, numbers, apostrophies, hyphens, and spaces. This observation has at least two consequences:
      • The strings will not contain asterisks (*).
      • scanf cannot be used for string input, as spaces would be ignored (but spaces could be part of a string).

Defective, Perfect, and Superperfect Numbers

  1. [approximately 12 points]

    Definitions: For a positive integer n:

    • A number k is a factor of n if k divides n with no remainder. For example, integers 1, 2, 3, 4, 6, and 12 are factors of 12, but 5, 7, 8, 9, 10, and 11 are not factors of 12.
    • The numbers 1 and n are called trivial factors of n; 1 divides every positive integer, and every positive integer divides itself.
    • A number k is a non-trivial factor of n if k is a factor of n other than 1 or n.
    • A number k is a proper factor of n if k is a factor of n other than n.

    • The number 1 is called a unit.
    • A number n is called prime if it not a unit and if its only factors are trivial.
    • A number n is called defective if it is neither a unit nor a prime and if the sum of its proper divisors is smaller than n. For example, 8 is defective, because its proper divisors are 1, 2, and 4, and the sum 1+2+4 = 7 which is less than 8.
    • A number n is called perfect if the sum of its proper divisors is exactly n. For example, 6 is perfect, because its proper divisors are 1, 2, and 3, and the sum 1+2+3 is the number 6.
    • A number n is called super perfect if the sum of its proper divisors is greater than n. For example, 12 is super perfect, because the sum of its proper divisors is 1+2+3+4+6 = 16 which is greater than 12.

    Write a program that reads a number max and prints, for each integer between 1 and max,

    • followed by its non-trivial factors,
    • the sum of its proper factors, and
    • its classification.

    The results should be printed in a table with the following format (shown when max is 12).

        The classification of numbers
    
        n : non-trivial factors : sum of proper factors : classification
        1 : : 0 : unit
        2 : : 1 : prime
        3 : : 1 : prime
        4 : 2 : 3 : defective
        5 : : 1 : prime
        6 : 2, 3 : 6 : perfect
        7 : : 1 : prime
        8 : 2, 4 : 7 : defective
        9 : 3 : 4 : defective
       10 : 2, 5 : 8 : defective
       11 : : 1 : prime
       12 : 2, 3, 4, 6 : 16 : super perfect
    
    Programming Notes:
    • Use C's remainder operator (%) to check remainders.
    • The integer division (/) should not be used without the instructor's explicit approval.
    • Arrays should not be used in this problem.
    • The program should be reasonably efficient. For example, a single set of nested loops (one outer loop and one inner loop) or a loop and a single recursive fucntion should be adequate for this problem.

    Bonus Option: Bonus points are possible with this problem if the table is formatted with the listing of non-trivial factors at the end:

        The classification of numbers
                             sum of proper
        n : classification :  factors      :  non-trivial factors
        1 : unit           :      0        :
        2 : prime          :      1        :
        3 : prime          :      1        :
        4 : defective      :      3        : 2 
        5 : prime          :      1        :
        6 : perfect        :      6        : 1, 2, 3 
        7 : prime          :      1        :
        8 : defective      :      7        : 2, 4
        9 : defective      :      4        : 3
       10 : defective      :      8        : 2, 5 
       11 : prime          :      1        :
       12 : super perfect  :     16        : 2, 3, 4, 6 
    
    Programming Hint:
    • In addition to the earlier notes for this problem, one might consider a recursive fucntion for printing part of a row in the table.

Word-Find Puzzle

  1. [approximately 14 points] This exercise is based on a programming problem by Marge Coahran.

    This problem asks you to write a program that solves a "word-find" puzzle similar to puzzles that can be found in newspapers and magazines. An example is given below.

    The input data for your program will be a 16 x 16 grid of characters (the puzzle board) followed by a list of words. The object of the puzzle is to search the puzzle board for the words in the word list. Words may appear in the puzzle board horizontally or vertically (but not diagonally). Horizontal words will run left to right; vertical words will run top to bottom. Words will not "wrap around" in either direction, so for example, a word could not occupy columns {15,16,1,2}. Each word will appear at most once in the puzzle board.

    An example data file is available at for your use, but your program should work on any input file that conforms to the following specifications.

    Puzzle Specifications

    The puzzle board will be given first. It will consist of a matrix of 16 x 16 upper-case letters, with a single space between each character on each row. Next the file will contain a list of upper-case words, each on a separate line, and each of which could fit within the puzzle board. The number of words is not specified, so your program should read until the end of the file is reached. There will be no blank lines anywhere in the file.

    Your program should specify the input file name as a command-line parameter, and the program should print the name of the file as part of its output.

    Your program should output a "key" to the word-find puzzle as shown in the example below. Essentially, the key is a copy of the puzzle board matrix that contains only the words which your program has found. All other characters of the board should be removed.

    Anti-hint: There are C library functions called strstr(), strchr(), and strrchr(), which you are NOT ALLOWED to use in this program. These functions would take away too much of your fun.

    Test Cases

    As part of your write up, please describe a set of cases that would be appropriate for testing this program. (Since designing these puzzles is non-trivial, you need not submit a puzzle of your own containing your tests, but describe what situations you would want to test.) It would also be wise of you to modify the example below if there are test cases missing from it, to allow you to thoroughly test your code.

    An (overly-simplified) list of test cases might look something like this:

    • include a horizontal word
    • include a vertical word

    Example

    Consider the input:

    
    G R N L R S Y S T E M E E O M R
    O C O M P U T E R E H I A I C U
    R A I M P R O G R A M A N R R R
    Q M E M O R Y A N T C R N T T M
    L A O N E T W O R K R O H H E U
    G T R Y S T R I N G I A E G Q E
    R R R N E A N Y L Y I L E E U R
    T R P T A R E C O S S G I T A A
    R L T P A R N A G O M E R U T S
    E I H H T A G L I K L B S R I C
    N T E Y T Y I C C M C R M I O H
    Y R O S A H N U U G R A E D N E
    P G R I N N E L L U U C A R S M
    C G Y C E K E U R S S B A S L E
    C N S S R E R S O U R R T P R B
    C N P O C N R M R U A I G A S O
    THEORY
    STRING
    ARRAY
    APPLE
    GRINNELL
    COMPUTER
    PHYSICS 
    CALCULUS
    ALGEBRA
    TIGER 
    SCHEME 
    NETWORK
    PROGRAM
    HOUSE 
    EQUATION
    MEMORY
    SLEEP 
    LOGIC 
    SYSTEM
    PIANO 
    

    When given this input, the program should print:

    
              S Y S T E M 
      C O M P U T E R 
            P R O G R A M 
      M E M O R Y
          N E T W O R K         E
            S T R I N G   A     Q
              A     L     L     U
              R   C O     G     A
        T P   R   A G     E     T S
        H H   A   L I     B     I C
        E Y   Y   C C     R     O H
        O S       U       A     N E
      G R I N N E L L             M
        Y C       U               E
          S       S
    

Dealing Bridge Hands

  1. [approximately 12 points] Write a program that simulates the dealing of a deck of cards to give four bridge hands. The program should print both the cards held for each hand and the point-count for bidding.

    A simple scoring system gives an ace 4 points, a king 3 points, a queen 2 points, and a jack 1 point, with an extra point given if a hand contains all aces and a point deducted if it contains no aces. Points also are given for distribution, with a point given if a hand contains only 2 cards in a suit (a doubleton), 2 points given if a hand contains a single card in a suit (a singleton), and 3 points given if a hand has no cards in some suit.

  1. Directing a Robot to Follow a Tape

    [approximately 14 points] Assume that tape has been place on the floor, and suppose that the color of the tape is significantly different (i.e., darker or lighter) than the floor. This problem asks you to write a program that will control the robot to follow the tape for at least a minute or two.

    Some programming notes:

    • In the lab on two-dimensional arrays, one exercise asks to locate an area of the brightest light in a picture. In this problem, use a similar approach to find the edge of a piece of tape on the floor. Since the color of the tape contrasts with the floor, one should scan a picture from the robot to determine where the color changes substantially from light to dark or dark to light.
    • If the color change is approximately straight ahead, the robot might go forward a short distance before taking another picture.
    • If the color change on the left side of the picture, the right motor might be directed to move more quickly than the left motor, so the robot will move somewhat to the left. The farther the color change is to the left, the more the difference between the right and left motors. After moving a short distance, the robot might stop and take another picture.
    • If the color change is to the right, the right motor might be directed to move less quickly than the left motor, so the robot will move somewhat to the right. The farther the color change is to the left, the more the difference between the right and left motors. After moving a short distance, the robot might stop and take another picture.

    Overall, the robot should follow a tape that winds left and right around the floor for at 10 or more feet.

File Analysis

  1. [approximately 16 points] Write a C program that takes the name of a file as a command-line argument, opens the file, reads through it to determine the number of words in each sentence, displays the total number of words and sentences, and computes the average number of words per sentence. The results should be printed in a table (at standard output), such as shown below:

    
         This program counts words and sentences in file "comp.text ".
    
         Sentence:  1    Words: 29
         Sentence:  2    Words: 41
         Sentence:  3    Words: 16
         Sentence:  4    Words: 22
         Sentence:  5    Words: 44
         Sentence:  6    Words: 14
         Sentence:  7    Words: 32
    
         File "comp.text" contains 198 words words in 7 sentences
         for an average of 28.3 words per sentence.
    

    In this program, you should count a word as any contiguous sequence of letters, and apostrophes should be ignored. Thus, "word", "sentence", "O'Henry", "government's", and "friends'" should each be considered as one word.

    Also in the program, you should think of a sentence as any sequence of words that ends with a period, exclamation point, or question mark.

    Exception: A period after a single capital letter (e.g., an initial) or embedded within digits (e.g., a real number) should not be counted as being the end of a sentence.
    White space, digits, and other punctuation should be ignored.

  1. Filtering and Reporting Data

    [approximately 16 points] Gemstones are attractive forms of rock crystal, commonly used for decoration and in jewelry. Gemstones also have interesting mineral properties. Gemstones may be classified in a variety of ways, including chemical composition, crystal structure, color, specific gravity, refractive index, and hardness:

    1. Chemical Composition: While some gemstones are primarily composed of atoms of one element (e.g., diamonds are mostly carbon, with coloring coming from traces of other elements), other gemstones are made up of atoms of several atoms (e.g., mica molecules include oxygen, hydrogen, silicon, aluminum, iron, and/or many others). On-line sources of information include general references (e.g., Common Mineral Groups) and references to specific minerals (e.g., micas).

    2. Color may be classified informally (e.g., red, yellow, etc.) or more formally by viewing thin slices of mineral crystals through the microscope, using polarized light (see, for example, Minerals under the Microscope).

    3. Specific Gravity is a measure of the density of a mineral. More precisely, specific gravity is the ratio of the weight of the mineral in air to its weight in an equal volume of water. More details are available from various on-line sources (see, for example, the Mineral and Gemstone Kingdom's glossary for specific gravity.

    4. Refractive Index provides a measure of how much light bends within a crystal. The higher the refractive index, the more bending and the more brilliant a crystal is likely to appear. For more information, see various on-line sources, such as Refractive Index.

    5. Crystal Structure: Crystals typically have one of several standard shapes or structures, including cubic, tetragonal, orthorhombic, hexagonal, monoclinic, and triclinic. While the details of such structures are beyond the scope of this problem, the World Wide Web contains many useful references, including crystal forms (at the macro-level.

    6. Hardness often is measured on the (nonlinear) Mohs Scale, which associates a hardness number to each mineral, from 1 (softest) to 10 (hardest):

      1. Talc
      2. Gypsum
      3. Calcite
      4. Fluorite
      5. Apatite
      6. Orthoclase
      7. Quartz
      8. Topaz
      9. Corundum
      10. Diamond

      As a comparison, a fingernail has hardness 2.5, glass has hardness 5.5, and a steel file has hardness 6.5. Minerals of the same hardness should not scratch each other, but a mineral of one hardness will scratch minerals with a lower hardness number.

    File /home/walker/151s/labs/gems.txt contains information on several gemstones, including color, hardness, specific gravity, and refractive index. Within the file, each line contains information about a specific gemstone.

    Here are a couple of sample lines, and a character 'ruler' to show how wide the fields are:

              11111111112222222222333333333344444444445555555555666666666677777
    012345678901234567890123456789012345678901234567890123456789012345678901234
    
                    Zircon        RED           7.5         4.50         1.95
                     Topaz     YELLOW             8         3.53         1.62
    

    To clarify, the names of the gemstones come first in a line and are right-justified in a column. The colors come next, followed by hardness (on a scale 1 to 10), then specific gravity, and finally refractive index (generally between 1.3 and 2.5).

    Write a program print-by-color that will let you select the gemstones of a certain color and print the information about those gemstones, where the resulting table is in alphabetical order by gemstone name and where the columns are labeled.

    For example, if this procedure is invoked with the statement

    
    (print-by-color "GREY")
    
    the procedure should return a table, such as the following:
    
                                                          Specific   Refractive
                  Gemstone       Color       Hardness      Gravity      Index
    
                 Alabaster       GREY             2         2.32         1.53
                  Bakelite       GREY           2.5         1.28         1.65
                   Calcite       GREY             3          2.7         2.71
                    Casein       GREY           2.5         1.33         1.55
                  Celluoid       GREY             2         1.35         1.50
                Chalcedony       GREY             7         2.62         1.53
                  Corundum       GREY             9         3.99         3.99
                   Diamond       GREY            10         3.52         3.52
                  Hematite       GREY             6         5.10         5.05
                     Ivory       GREY           2.5         1.80         1.54
                   Jadeite       GREY             7         3.34         3.33
               Labradorite       GREY             6          2.7         2.70
                    Marble       GREY             3         2.71         1.50
                Meerschaum       GREY             2         1.50         1.53
                  Nephrite       GREY           3.5         3.00         2.96
                      Opal       GREY             6         2.10         2.10
                    Quartz       GREY             7         2.65         1.55
                    Quartz       GREY             7         3.33         2.65
                      Talc       GREY             1         2.70         2.75
    
    Another possible format might be:
    
                                           Specific   Refractive
    Gemstone Name       Color    Hardness   Gravity      Index
    
    Alabaster            GREY       2         2.32        1.53
    Bakelite             GREY       2.5       1.28        1.65
    Calcite              GREY       3         2.70        2.71
    Casein               GREY       2.5       1.33        1.55
    Celluoid             GREY       2         1.35        1.50
    Chalcedony           GREY       7         2.62        1.53
    Corundum             GREY       9         3.99        3.99
    Diamond              GREY      10         3.52        3.52
    Hematite             GREY       6         5.10        5.05
    Ivory                GREY       2.5       1.80        1.54
    Jadeite              GREY       7         3.34        3.33
    Labradorite          GREY       6         2.70        2.70
    Marble               GREY       3         2.71        1.50
    Meerschaum           GREY       2         1.50        1.53
    Nephrite             GREY       3.5       3.00        2.96
    Opal                 GREY       6         2.10        2.10
    Quartz               GREY       7         2.65        1.55
    Quartz               GREY       7         3.33        2.65
    Talc                 GREY       1         2.70        2.75
    

    As shown in each example, the gemstone names and properties must appear in labeled columns. Gemstone names may be either left-justified or right-justified.

    Note that some gemstones, such as Quartz above, appear several times in the table, since variations of a gemstone may have different properties.

Distance to Fire Hydrants

  1. [approximately 16 points] Within cities, rates for property insurance often depend upon the distance between a house and the nearest fire hydrant. This problem outlines a simple version of this rather-general problem.

    Here are some details. We suppose that a city is organized as a grid of streets, and that fire hydrants are located near selected street intersections. The best insurance rates (category A) are available to houses who are at an intersection where there is also a fire hydrant. The second best insurance rates (category B) are available to houses at an intersection where the nearest fire hydrant is 1 block away (there is no fire hydrant at the house's intersection, but there is a fire hydrant 1 block away). The third best insurance rates (category C) are available to houses at an intersection where the nearest fire hydrant is 2 blocks away. The worst insurance rates (category D) are applied to houses for which there is no fire hydrant within 2 blocks (all hydrants are 3 or more blocks away).

    Of course, this problem is not unrelated to the Emergency Telephone problem (supplemental problem 3), with telephones replaced by fire hydrants and with searching possible in any direction. However, in this case, the issue is how close the nearest fire hydrant might be. Also, for this problem, the fire hydrant information will be located in a file.

    Additional details follow:

    • Fire hydrant information will be stored in a file, organized as follows:
      • The first line of the file will contain the city name (up to 40 characters).
      • The second line of the file will contain two integers: the north-south size of the city grid and the east-west size of the city grid.
      • A line of 0's and 1's for the fire hydrants at successive intersections (west to east) for a row of the grid; a 0 indicates no hydrant at that intersection, and a 1 indicates there is a hydrant. The 0's and 1's are separated by one or more spaces.
      • Each successive lines of 0's and 1's represents an east-west street in the town, going from north to south.
    • The program is to read the file name from the command line.
    • The program is to print the name of the city, followed by a table of intersections, with the category rating (A, B, C, or D) for each intersection. The table of intersection ratings will be the same size and organization as the city grid specified in the file.
    • For example, suppose the data file one-hydrant contains the following data:
      one hydrant city
      3 5
      0 0 1 0 0
      0 0 0 0 0 
      0 0 0 0 0
      
      For this data, the program should print the following:
      one hydrant city
      C B A B C
      D C B C D
      D D C D D
      
    • You should test your program on various files, including