CSC 115.005/006 Sonoma State University Spring 2022
Scribbler 2
CSC 115.005/006:
Programming I
Scribbler 2
Instructor: Henry M. Walker

Lecturer, Sonoma State University
Professor Emeritus of Computer Science and Mathematics, Grinnell College


Course Home References Course Details: Syllabus, Schedule, Deadlines, Topic organization MyroC Documentation Project Scope/
Acknowledgments

Notes:

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 7-13, 2019). (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

Submission Details

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

Some Grading Notes:

Problem Statements

  1. Computing a Babysitter's Fee

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

    Write a program that reads four integer values (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.

  1. Making Early Loan Payments

    When investigating a loan, a customer typically states the amount of money (loanAmount) and specifies the loan's length (number of months N). A bank or other lender proposes an annual interest rate (annRate) for the loan. (The annual rate should be specified as a percentage, such as 4.59%—entered by a user as 4.59.) With this information, the monthly payment for the loan is given by the formulae:

    monthlyRate = annRate / 1200.0
    payment = loanAmount * monthlyRate / (1.0 - (1 + monthlyRate)(-N))

    For example, a loan to improve a house might involve $26,000 for 25 years (300 months) at an annual rate of 8.75%, yielding a monthly payment of $213.76.

    The expectation is that the customer will pay this amount (in dollars and cents) each month, although a slight adjustment may be needed the last month to make up for any rounding in the computation.

    The expected payment notwithstanding, the terms of many loans allow the customer to pay an additional amount for one or more months in order to shorten the length of the loan and possibly save some interest charges. This problem investigates the consequences of paying twice the required amount for the first few months.

    More specifically, the program should have these characteristics:

    • The beginning of the program should read from the terminal the values of the loan amount, length (in months), and annual interest rate.
    • The program should compute the normal loan payment using at least two functions:
      • double compute_neg_power (double value, int n)
        that returns 1 / (value)n.
        (In the computation, the function should use successive multiplications. Use of the more general, but much less efficient function pow in th C library will yield a 10-point penalty.)
      • double compute_payment (double annRate, int months, double amt)
        that returns the monthly payment for the given parameters.
      • compute_payment should call compute_neg_power.
    • The main procedure should determine the actual length of the loan and the total amount paid assuming each of three payment options:
      • The customer pays exactly the expected amount each month (except that the last month may be smaller, if appropriate)..
      • The customer pays twice the expected amount the first month and then the expected amount each subsequent month (except that the last month may be smaller, if appropriate).
      • The customer pays twice the expected amount each month in the first year and then the expected amount each subsequent month (except that the last month may be smaller, if appropriate).
    • Some programming constraints:
      • No global variables may be used in this program.
      • When using functions, all relevant values must be passed as parameters.
      • Values may be returned from functions either through a return statement or via parameters (with addresses).
      • No printf statements are allowed in any final function except main. (printf may be used in functions for testing, but these should be commented out for any final runs.) In particular, neither function compute_neg_power nor function compute_payment should print anything.
    • Computations of actual payments and the cost of the loan should be given to the nearest cent. Note that if double value is a real number, then
      • ((int)(value * 100.0)) / 100.0 truncates value to two decimal places, and
      • ((int)(value * 100.0 + 0.5)) / 100.0 rounds value to two decimal places.
    • In addition to computing the cost of the loan for the three payment plans, the program should indicate the additional costs (if any) of each of the first two payment options over the third.

    Grading Forms

  1. Computing a Polynomial

    A polynomial function has the form

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

    Write a function compute_poly that takes three parameters:

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

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

    Notes:

    • compute_poly should make only one pass through the list of coefficients.
    • Both the number x and the elements of the array a should be real numbers (e.g., of type double) rather than integers.
    • The number x may be used in a multiplication operation no more than n times in the entire computation. (Thus, recomputing xi from scratch for each of the n terms is not acceptable for this problem.)
    • Since the pow function in the math.h library requires many multiplication operations, use of pow in this problem would violate the condition that no more than n multiplications are allowed in the entire solution to this problem. (To be specific, use of pow in this program will yield an automatic score of 0 for this program.)
    • 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.
    • Be sure that the array element a[n] is used as the coefficient of xn (not the coefficient of x0).
    • You will need to include compute_poly in a main program for testing.
    • Be sure your testing covers an appropriate range of cases.
    • compute_poly should return the result of the computation, not print the result. (Any printf statement in compute_poly is subject to a 12 point penalty!)

    Grading Forms

  1. Grading Passwords

    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 function

    
       char gradePassword (char * password)
    

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

    • Starting at 0, add 1 point for each of the following elements in the password:
      • 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
    • Adjust points based on the length of the password:
      • deduct 2 points for passwords that contain less than 6 characters
      • passwords of 6, 7, or 8 characters have no point deductions or additions
      • add a point for passwords that contain 9, 10, or 11 characters
      • add 2 points for passwords that contain 12, 13, 14, or 15 characters
      • add 4 points for passwords than contain more than 15 characters
    • Assign a letter grade to the password by applying the sum of the points above to the following.
      • 9 or more points: A
      • 7 or 8 points: B
      • 5 or 6 points: C
      • 3 or 4 points: D
      • 0 or 1 or 2 points: F

    Note: Use of globals is expressly forbidden on this problem.

    • -10 for declaration of first global variable
    • 0 points total on problem if 2 or more global variables.

Grading Forms

  1. A Picture Suite

    For this project, you will write the following series of functions which modify a picture. For each function, the address of a picture is passed as a parameter, so the picture passed into the function (e.g., from main) will be changed.

    • void pixelStrip (Picture * pic, char color)

      This function should set the R, G, or B value of every pixel in the picture to 0 (depending on what char color is).
      For example if parameter color is 'G', then this procedure should change the 'G' component of each pixel in the picture to 0; the 'R' and 'B' components would remain unchanged.

    • void pictureRedder (Picture * pic)
      void pictureGreener (Picture * pic)
      void pictureBluer (Picture * pic)

      These functions should increase the intensity of their respective colors (red, green, or blue).

      • This increase should never go past 255.
      • The color should increase less when it is already high than when it is low.
      • Successive calls to one of these functions should increase the intensity of the appropriate color with each call (except for colors which are near the maximum 255 to begin with). (Thus, setting a designated color to 255, regardless of its initial intensity, is not appropriate.)

      • void circleSelect (Picture * pic, int xCenter, int yCenter, int radius)

        This function should select a circle from your picture and turn each pixel within that circle to the corresponding grayscale value.

      • a creative function of your choosing

        This function should do something interesting and creative to your picture. It should not just be a rehashing of a previous exercise or lab, and there should be a good amount of thought and effort placed into this function.

    Note on Testing and Problem Submission

    As stated, this problem only requires that you write 5 functions with specific headers and a sixth function of your choosing. However, any code, for this course or for other uses, must be tested. Thus, to complete this problem, you also will need to write a main function that can be used to test the required functions.

    In submitting your problem, you will need to include a statement of what tests you have run to determine that your functions work properly, and you should describe the results of your testing. For example, you might describe pictures used in testing as well as the results obtained when functions are called on those images.


    Grading


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

  1. Unusual Canceling

    [approximately 9 points]

    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.

    Note: An extensivie discussion of this problem may be found at Lucky fractions: Where bad arithmetic gives the correct answer by Tom Osler, Rowan University.

  1. Alphabetizing Numbers

    [approximately 9 points]

    Write a C program that generates the names of the numbers from zero to two hundred and prints them in alphabetical order.

    Notes:

    • All numbers should be written as lower-case names.
    • The program should be as compact as possible and utilize logic rather than brute force. (For example, a program consisting of 200 printf statements will earn very little credit.)
    • The program should run efficiently. (For example, few points will be given for a program utilizing a bubble sort.)
  1. Common Letters

    [approximately 10 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").
  1. Printing Cross Words

    [approximately 9 points]

    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.

  1. Simulation of Hi Ho! Cherry-O

    [approximately 11 points]

    This problem explores statistics for the game of Hi Ho! Cherry-O. For our purposes, we will follow the description of the game as described in Wikipedia. Note, however, that the number of cherries on a player's tree is always between 0 and 10. If one spins a bird or dog and the number of cherries on the tree is 8 or fewer, then the number of cherries on the tree goes up by 2. However, if one spins a bird or dog and the number of cherries on the tree is 9 or 10, then the number of cherries on the tree goes to 10 (not higher).

    The game progresses in rounds, during which each player in turn spins a game spinner that has seven outcomes (as described in the Wikipedia article). In our simulations, we will assume that each outcome of the spinner arises randomly with equal probability.

    Within this framework, the specific purpose of this supplemental problem is general statistics on how many rounds the game is likely to continue, based on the number of people playing the game. The required work for this problem involves three C procedures, combined within a main program.

    • Procedure turn simulates one turn of a player; that is, it takes a number init_cherries as parameter, and adjusts the number of cherries on the tree appropriately — using C's rand function to determine the outcome of the spinner.
    • Procedure playGame has players, the number of players, as input parameter, and returns the number of rounds taken until some player wins.
    • Procedure playNGames has two parameters: players, the number of players in a game, and games, the number of games to be simulated. playNGames returns a list with the maximum, minimum, and average number of rounds taken by the players over the full number of games.

    Hints: Although you are free to approach this problem however you want, the following pieces might help.

    • Write a procedure init_games that takes a number of players as parameter and generates a list of that number of 10's (the initial number of cherries on the trees for each of those players).
    • Write a procedure play_round that takes a list of tree-cherry numbers as parameter, plays one round for each player, and returns a list of new totals for the number of cherries for each player.
    • Write a procedure check_win that takes a list of tree-cherry numbers as parameter and checks if any of the players has won.
  1. Elementary Text Analysis

    [approximately 12 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.
    

    Notes for this problem:

    • A word is defined as any contiguous sequence of letters. Apostrophes at the beginning or the end of a word should be ignored. Apostrophes with letters immediately before and after are considered part of a word. For example, "O'Henry", "I've", "you're", "friend's" and "friends'" should each be considered as one word.

    • A sentence is defined as any sequence of words that ends with a period, exclamation point, or question mark, except 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.

    • Digits and punctuation (other than apostrophes, periods, explanation points, and question marks) should be considered the same as white space. Thus,

         After they walked, talked, and ate, the first person said, "I'd like 
         to swim: crawl, side stroke, and butterfly."
      

      Should be considered the same as

         After they walked  talked  and ate  the first person said   I'd like 
         to swim  crawl  side stroke  and butterfly
      
    • White space (e.g., spaces, tabs, line feeds, and return characters) are considered as equivalent. Multiple white space characters are considered the same as one space character. Thus, the above passage would equivalent to the following:

      After they walked talked and ate the first person said I'd like to swim crawl side stroke and butterfly
      
  1. Filtering and Reporting Data

    [approximately 12 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.

  1. Assigning Lab Partners

    [approximately 12 points]

    In CSC 161 and numerous other courses, students may work on labs or projects (sometimes other assignments) in small groups (usually pairs). These groups are assigned by the instructor, and groups are changed frequently. This problem seeks a program to determine these assigned groups. (Currently, the assignments are done manually, with a labor-intensive process.) The basic requirements follow:

    • Suppose there are N students in the class (where N is between 24 and 38). For the purposes of this problem, the students are numbered 1, ..., N.
    • Early in the semester, students are given the option of indicating which students they do NOT to work with during the semester.
    • Following past history, for this problem, we assume no more than 6 students indicate which people they do not want to work with. (Usually the number is just 2 or 3.)
    • Groups of 2 are preferred for an assignment, but a group of 3 is needed if N is odd.
    • To the extent possible, students should be working with someone different with each assignment.
    • During the semester, a student should not be asked to work in a group of three more than once.
    • Sometimes during the semester (but not often), a student drops the course. That is, the student may be assigned a group for the first several weeks, but the student should not be assigned a partner after a designated week.

    Write a program that identifies and prints up to 14 assignments of students (i.e., up to one new assignment of pairs each week). The program should have the following features:

    • The program is deterministic. That is, the program makes the same assignments every time it is run. (This allows the program to be run several times during the semester, if a few people drop.)
    • The program provides the option that up to 8 students may drop the course after varying assignments. (In practice, there are rarely more than 2 drops, so allowing 8 is intended to be safe.)
    • Under varying circumstances, it may not be possible to make different assignments each week. However, in all cases, a student should never have to work with someone they explicitly wanted to avoid. Also, the resulting assignments should have as few repeated pairs of students as possible.
    • If a group of 3 is required (e.g., the number of students in the class is odd), then the students in the group of 3 should change from week to week as much as possible.
  1. A Simple Route Cipher

    [approximately 15 points]

    When sending a message from one place to another, it is common for the sender to encode the message before it is sent with the understanding that the receiver would know how to decode the message. With this encoding process, anyone intercepting the message in transit would not be able read the text.

    For encoding, one approach is a substitution cipher, in which each letter in original message is replaced by another letter. (For example, each "a" in the message might be replaced by "d" and each "t" might be replaced by "w". This type of cipher is commonly used in many word puzzles in newspapers and puzzle books.

    A second approach for encoding is called transposition, in which the characters of the original message are rearranged in a different order. This problem implements a simple type of transition cipher, called a route cipher. (Historically, the Union forces in the American Civil War used a variation of a route cipher, called the Union Route Cipher.)

    Encoding: In a simple route cipher, letters of a message are placed into a rectangular table. As an example, suppose the cipher is based on a table of 5 rows and 9 columns, and suppose we wish to encode the text "this short example illustrates a route cipher". The first step of a route cipher is to insert the message row-by-row into the table, on character at a time.

    t h i s   s h o r
    t   e x a m p l e
      i l l u s t r a
    t e s   a   r o u
    t e   c i p h e r

    With this arrangement, the encoded message is obtained by retrieving the letters according a designated path or route from the rectangle. For this problem, we will retrieve the letters from the table column by column. For example, reading column-by-column from the above table, we obtain the coded message "tt tth ieeiels sxl c auaisms phptrholroereaur".

    Decoding: Given an encoded message, the receiver places the text character-by-character into the rectangle according the prescribed path (e.g., column by column). With the letters in the rectangle, the original message can be restored by reading the rectangle row-by-row.

    Extensions: In the basic encoding approach, the original message is placed in a rectangle of a designated size. If the rectangle has r rows and c columns, this approach works well if the message has length r*c, the size of the rectangle. Extensions are needed if the original message has length other than r*c characters.

    • If the original message has less than r*c characters, additional characters might be added to get the needed number. For example, we might add letters of the alphabet a, b, c, d, e, ... at the end of message as needed to fill the rectangle.
    • If the original message has more than r*c characters, the message is divided into blocks of r*c characters, and each block is encoded separately.

    As another example, suppose the rectangle is specified with 3 rows and 4 columns, and suppose we want to encode the message "this extended example shows the full algorithm".

    Encoding follows these steps:

    1. Divide the message into blocks of 3*4 = 12 characters. The last block would have only 10 characters, so "a" and "b" have been added to complete the block.

      t h i s   e x t e n d e
      d   e x a m p l e   s h
      o w s   t h e f u l l
        a l g o r i t h m a b
    2. Place each block into a rectangle, row-by-row:
      t h i s       d   e x       o w s           a l g
        e x t       a m p l       t h e       o r i t
      e n d e       e   s h       f u l l       h m a b
    3. Read characters from each block, column-by-column:
      "t ehenixdste"   "dae m epsxlh"   "otfwhusel  l"   " oharmliagtb"

      Combining the encoded blocks gives:
      "t ehenixdstedae m epsxlhotfwhusel  l oharmliagtb"

    Problem:

    • Write a program that reads the rectangle size (a row and a column) and the text of a message and prints the encoded message.
    • Explain how the above program can also be used for decoding and illustrate your explanation with an example.

    Programming Notes:

    • Although conceptually the first encoding step reads the entire message and then divides it into pieces, in practice, the program should read and process one block at a time:
      1. Read rectangle size and create rectangle(s) of the appropriate dimensions to process a single block.
      2. Continue until all input is processed
        1. Read one block
        2. Process characters for the one block
        3. Print encoded characters for that block
    • C allows arrays to be declared of a length that is determined during run time. See Arrays of Variable Length for details.

    Reference: A nice treatment of transposition ciphers may be found in Abraham Sinkov, "Elementary Cryptanalysis: A Mathematical Approach", The New Mathematical Library, Random House and the Mathematical Association of America, 1968, Chapter 5. A revised edition of the book is available in Abraham Sinkov and Todd Feil, "Elementary Cryptanalysis Second Edition", The New Mathematical Library, Mathematical Association of America, 2009.