CSC 161 Grinnell College Spring, 2012
 
Imperative Problem Solving and Data Structures
 
 

Supplemental Problems

This page has not been revised for Spring 2012; do not rely upon any of the problems stated here until the semester begins!

Supplemental Problems extend the range of problems considered in the course and help sharpen problem-solving skills. Problems numbered 8 or higher may be turned in for extra credit.

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

This page will evolve as the semester progresses. I hope to have each supplemental problem finalized at least 1 week before it is due.

Format:

In turning in any programs for the course, please follow these directions:
  1. The first six lines of any C program should be comments containing your name, your mailbox number, this course number (161), and an identification of assignment being solved. For example:
    
        /***************************************
         * Henry M. Walker                     *
         * Box Science II                      *
         * Program for CSC 161                 *
         * Assignment for Tuesday, February 10 *
         ***************************************/
    
    Also, a comment is needed for every definition of a C function, stating both pre- and post-conditions for that program unit.

  2. Obtain a listing of your program and a record of relevant test runs using the script command:
    • Within a terminal window (before running C), begin recording session with the statement

      script filename

      where filename is the name of the file in which you want the session stored.
    • Within the script file,
      • Print a copy of your program with the command

        cat C-file.c

        where C-file.c is the name of the file containing your C program.
      • If your work involves several files, list the main program first with the cat command; then list any supplementary files.
      • Compile your program with the gcc command, and run it with appropriate test cases to check the correctness of your program.
    • When your runs are complete, stop the script session by typing <Ctrl/D>.
    • Print the record of your session by typing

      print filename

  3. Either write on your printout or include a separate statement that argues why your program is correct, based upon the evidence from your test runs.

Some Grading Notes:


Computing a Babysitter's Fee

  1. A baby sitter charges $1.50 per hour until 9:00 pm (while the kids are still up), $1.00 per hour between 9:00 pm and midnight, and $1.25 per hour after midnight (since late night baby sitting interferes with morning classes).

    Write a program that begins with four integer variables (the sitter's starting time in hours and minutes and the ending time in hours and minutes) and computes the sitter's fee. Assume all times are between 6:00 pm and 6:00 am, and hours should be specified as being between 0 and 12 (inclusive). Hours outside the range of 0 to 12 should be considered invalid.

    • The hour 6 should be considered as 6:00 pm, when it is entered as a starting time.
    • The hour 6 should be considered as 6:00 am, when it is entered as an ending time.

    The following table may clarify allowed time values for this problem.

    Starting Starting Ending Ending StartingEnding
    Hour Minutes Hour Minutes Time time
    8 0 3 30 8:00pm 3:30am
    6 0 0 45 6:00pm 12:45am
    12 0 6 0 12:00am (midnight) 6:00am

    Programming Note: You may NOT use loops or recursion in this program.

Computing a Polynomial

  1. A polynomial function has the form

    p(x) = anxn + an-1xn-1 + ... + a2x2 + a1x + a0

    Write a function compute_poly that takes two or three parameters:

    • an x value, and
    • a list of coefficients, (an, an-1, ..., a1, a0),
    • (optional) an integer n which gives the largest power of x with a non-zero coefficient.

    and returns the value of the polynomial p(x).

    Notes:

    • compute_poly should make only one pass through the list of coefficients.
    • As a hint, you may want to search for discussion of Horner's Rule either in a book on numerical analysis or on the Web.
    • You will need to include compute_poly in a main program for testing.
    • Be sure your testing covers an appropriate range of cases.

Grading Passwords

  1. Since many modern computer systems use passwords as a means to provide protection and security for users, a major issue can be the identification of appropriate passwords. The main point should be to choose passwords that are not easily guessed, but which the user has a chance of remembering. For example, passwords related to birthdays, anniversaries, family names, or common words are all easily guessed and should be avoided.

    Some common guidelines suggest that a password should contain at least 6 characters and include characters from at least three of the following categories:

    • uppercase letters
    • lowercase letters
    • digits
    • punctuation (considered to be anything not a letter or a digit)

    Other guidelines indicate that elements of passwords should be pronounceable. One simple measure of this guideline suggests that any group of letters in a password should contain both vowels and consonants.

    This supplemental problem asks you to write and test a procedure

    
       char gradePassword (char * password)
    

    that assigns a grade to the given password, as follows:

    • Assign 1 point for each of the following elements in the password:
      • password contains at least 6 characters
      • password contains at least 1 vowel
      • password contains at least 1 consonant
      • password contains at least 1 upper-case letter
      • password contains at least 1 lower-case letter
      • password contains at least 1 numeric character
      • password contains at least 1 punctuation mark
    • Assign a letter grade to the password by applying the sum of the points above to the following.
      • 6 or 7 points: A
      • 5 points: B
      • 4 points: C
      • 3 points: D
      • 0 or 1 or 2 points: F

Distance to Fire Hydrants

  1. 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, file /home/walker/161/problems/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

Common Letters

  1. 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").

Word-Find Puzzle

  1. 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 /home/walker/161/problems/puzzleboard 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
    

Recording and Retrieving Golf Scores

  1. The reading on doubly-linked lists presents this problem: "In recording scores for a golf tournament, we enter the name and score of the player as the player finishes. This information is to be retrieved in each of the following ways:

    • Scores and names can be printed in order by ascending or by descending scores.
    • Given the name of a player, other players with the same score can be printed."

    This supplemental problem asks you to solve this problem using a doubly linked list. Some details follow.

    • The program should maintain a doubly-linked list of nodes.
    • Each node should contain a player's name as a string and the int score that the player obtained in a round of golf.
    • The doubly-linked list should begin empty.
    • A menu for the program should include five options:
      1. Enter the name/score of a player
      2. Enter the name of a player and obtain a listing of those players who have the same score as the given player. (If the specified player is not found, the program should print that no players have been found.)
      3. List the players in ascending order of golf scores.
      4. List the players in descending order of golf scores.
      5. Exit the program.
    • Nodes in the linked list should be ordered in ascending order of score. (For players with the same score, any ordering of nodes is fine.)
    • Printing of nodes should start at one end of the list and proceed linearly to the other end using a simple iterative loop that takes advantage of the ordering in the doubly-linked list — recursion and doubly-nested loops should not be used.
    • To find players with the same score, the program should start searching at one end of the list and proceed linearly toward the other end. If the player is found, processing should follow "previous" links to find the first player with the given score. Then processing should follow "next" links to print subsequent players with the same score.

    Note: This program may utilize any code developed in the lab for doubly-linked lists (with appropriate citation). Since that lab does not place nodes in order (menu option a) or move back and forth from a given node (menu option b), those parts of this problem should not be based on the collaborative lab.


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%.

Unusual Canceling

  1. The fraction 64/16 has the unusual property that its reduced value of 4 may be obtained by "canceling" the 6 in the numerator with that in the denominator. Write a program to find the other fractions whose numerators and denominators are two-digit numbers and whose values remain unchanged after "canceling."

    Of course, some fractions trivially have this property. For example, when numerator and denominator are multiples of 10, such as 20/30, one can always "cancel" the zeroes. Similarly, cancellation is always possible when the numerator and denominator are equal, as in 22/22. Your program should omit these obvious cases.

Roman Numerals

  1. Write a procedure that reads an integer N between 1 and 1000 from the keyboard and prints the Roman numerals between 1 and N in alphabetical order.

    Note: The Bubble Sort is not covered in this course, because it is never considered to be an acceptable algorithm.

Printing Cross Words

  1. Consider the problem of printing two words, the first word vertically (one letter per line) and the second word horizontally, so the words cross at a common letter. For example, if the first word is FUNCTIONAL and the second is SCHEME, then the desired output is:

    
     F
     U
     N
    SCHEME
     T
     I
     O
     N
     A 
     L
    
    

    In this problem, you are to write a program that reads two words from a terminal window and prints them in the crossed pattern shown above (assuming they have a letter in common). If the words have more than one letter in common, then they may be printed with the crossing at any common letter. If the words have no letters in common, then the program should print an error message.

Dealing Bridge Hands

  1. 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.

Information on the 1997-1998 Iowa Senate

  1. File /home/walker/151s/labs/ia-senate contains information about the members of the 1997-1998 Iowa Senate. After a title line and a blank line, a typical line has the following form:
    
    Angelo          Jeff        44      Creston           IA 50801
    Kramer          Mary        37      West Des Moines   IA 50265
    Lundby          Mary        26      Marion            IA 52302-0563
    
    Thus, a typical line gives the last name, the first name, the district number, the town of residence, the state (always IA), and the town's zip code. The information in these lines is arranged in columns.

    Design and write a Scheme program that reads in data from this file and creates two output files, senators-by-district and senators-by-zip-code, in the current working directory. The senators-by-district file should contain the same data as the source file, in the same format, but with the lines arranged by senate district (column 3). The other file, senators-by-zip-code, should contain a list of all senators in the following format

    
    
    
    Jeff Angelo
    Creston, IA 50801
    
    A blank line should appear after each senator and city address. In this format, the name appears on a first line (first name, then last), and the city, a comma, the state, and zip code is on the next line -- separated by single spaces in the format shown. Note that a variation of this format (with a street address, if available) might be used for a mailing label.

File Analysis

  1. 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.

Parenthesis Checking

  1. Write a program that reads a line of text from the terminal and checks if the parentheses in the line are balanced.

    Notes

    1. The program should distinguish among three types of parentheses, { }, [ ], ( ).
    2. Parentheses checking should involve working from the inside of nested parentheses to the outside.
    3. In each case, the appropriate right parenthesis should be matched with a left parenthesis of the same type.

    Examples

    1. ( these { parentheses[] match } perfectly ) !!!
    2. (the {right [parentheses ) on } this line ] are in the wrong order.
    3. this ( line { is missing } one (round ) right parenthesis.

    Comments on a solution to the problem: This problem can be solved reasonably easily using a single left-to-right scan of a line, if left parentheses are placed on a stack as they are encountered. Then, when a right parenthesis is found, the stack can be popped and one can check if the right parenthesis has the same type as the left one.

    Programming Note: Your program should use a self-contained Stack library package, as described in the lab on Stacks and Queues with Linked Lints and implemented as lists.