Physics 5—Scientific  Computing

Instructor: Geoff Hagopian,
office: Math 12
email: ghagopian@colleGEOFthedesert.edu
phone
: 776-7223
Meetings: TR: 9:30-12:00

[Syllabus]
[Calendar]
[Compilers]
[Exams]
[References]
[Grades]

babs

Assignments

3.15: Math Tutor

Write a program that can be used as a math tutor for a young student. The program should display two random numbers to be added, such as

 249
+
924

The program should then pause while the student works on the problem. When the student is ready to check the answer, he or she can press a key and the program will display the correct solution:

 249
+
924
1173

3.17: Monthly Payments

The monthly payment on a loan may be calculated by the following formula:

pymnts

Here R is the monthly interest rate, which is the annual interest rate divided by 12 so that, for instance, 12% annual interest is 1% monthly interest. N is the number of payments and L is the amount of the loan. Write a program that asks for these values and displays a report similar to

Loan Amount:
$
10000.00
Monthly Interest Rate:
1%
Number of Payments:
36
Monthly Payment: $
332.14
Amount Paid Back: $
11957.15
Interest Paid: $
1957.15

 

 

 

 

3.25. Word Game

Write a porgram that plays a word game with the user. The program shoulod ask the user to enter the following :

  • His or her name
  • His or her age
  • The name of a city
  • The name of a college
  • A profession
  • A type of animal
  • A pet's name

After the user has entered these items the program should display the following story, inserting the user's input into the appropriate locations:

There once was a person named NAME who lived in CITY. At the age of AGE, NAME went to college at COLLEGE. NAME graduated and went to work as a PROFESSION. Then, NAME adopted a(n) ANIMAL named PETNAME. They both lived happily ever after.

4.2. Roman Numeral Converter

Write a program that asks the user to enter a number within the range of 1 through 10. Use a switch statement to display the Roman numeral version of that number. Input validation: Do not accept a number less than 1 or greater than 10.

4.9 Math Tutor

This is a modification of 3.15 above. Write a program that can be used as a math tutor for a young student. The program should display two random numbers to be added, such as

 249
+
924

The program should then wait for the student to enter the answer. If the answer is correct, print a message of congratulations. If the answer is incorrect, a message should be printed shoing the correct answer.

Hangman

Here's an pseudocode/outline for how to carry out this game.

Initialize word, fillIn, list of bad letters, number of turns, number of good letters, etc.

Repeat the following:
1. Show the correct guesses so far, together with the unknown letters, like "--e-r--e"
2. Show the current list of wrong letters.
3. Say how many turns are remaining.
4. Get a guess for a letter in the word from the user.
5. If the guess is right, fill in all the places where it's right.
6. If the guess is not right, use up a turn and add to the list of wrong guesses.
Until either the turns are used up or the word is guessed.
Give a message explaining the results of the game when the game is over.

For the code I wrote, I got this output:

So far you've got -----
Your wrong letters are
You have 10 turns remaining.

What would you like to guess? a
So far you've got -----
Your wrong letters are a
You have 9 turns remaining.

What would you like to guess? e
So far you've got -----
Your wrong letters are ae
You have 8 turns remaining.

What would you like to guess? t
So far you've got -----
Your wrong letters are aet
You have 7 turns remaining.

What would you like to guess? o
So far you've got -----
Your wrong letters are aeto
You have 6 turns remaining.

What would you like to guess? i
So far you've got --i--
Your wrong letters are aeto
You have 6 turns remaining.

==and so on==================

What would you like to guess? p
So far you've got -rimp
Your wrong letters are aetos
You have 2 turns remaining.

What would you like to guess? c

Congrats, you guessed it! crimp!

============================

Doublets

Doublets is a game invented by Lewis Carroll (aka Dodgson) which you can get detailed information about doublets at Riddles On Line, ThinksDotCom , LogicVille, or the Google Books result.

To play doublet, start with 2 four-letter words (appropriate for polite company) and by changing only one letter at a time, produce a sequence of words starting with the first given and ending with the last given. For example, the sequence "good, food, fool, foil, fail" goes from "good" to "fail" in a minimum of 3 words in between.

The challenge of this assignment is to write c++ code that will play this game.

In the lecture last week, we developed a sequence of problems you would need to solve to work out the code for such a program. Here's the list of tasks we came up with:

1. Obtain two words from the user and validate that they are four letter words.

To do this validation we used a while loop

i = 0; // letter counter
while(startWord[i]!='\0') // count letters in word
    i = i + 1;
while(i!=4) // insist on four-letter word
{
    cout << "\nYou didn't enter a 4-letter word. Try again.";
    cin >> startWord;
    i = 0;
    while(startWord[i]!='\0') // count letters in word
       i = i + 1;
}

If you have another way to do this, please go ahead and use it.

2. Validate that the words the user enters are in our list of four-letter words. You can use this file: FourLetterWords.txt.

You will need to include the fstream header file with #include <fstream> and create an input file stream object, say with
                // Open the list of allowable four letter words.
      
 ifstream readFile("FourLetterWords.txt");

so that, in this case, readFile will be an input stream object associated with the local file FourLetterWords.txt (in the same directory where you are editing and compiling your c++ code) and positioned to start reading at the beginning.

Note that there are a number of ways to manipulate the ifstream object. The web site http://www.cplusplus.com/reference/iostream/istream/ is a good place to get information about these. In particular, the member function seekg is useful for positioning. For instance, when you want to look for another word in the FourLetterWords file, reset the read position of the readFile "object" using its member function, seekg()like so:

    readFile.seekg(0,ios::beg);

The function seekg is a member function of the ifstream object we created and it is accessed by the dot operator. Also note the use of the binary scope resolution operator (::).

Now here's the code we developed in class for validating that the word is in the approved list:

    //Look to see if the word is in our dictionary
    readFile >> currWord;
    int j = 0; // start at the first letter
    while(j < 4 )
    {
        while(currWord[j]!=startWord[j] && currWord[0] != '?')
        {   // Keep reading through the file until you either
            // get match a letter or get to the end

            readFile >> currWord;
        }
        j = j + 1; // At this point you've either matched a letter
    }              // or the search has failed. Get next letter.

    if(currWord[0]!='?')
        cout << "\nThe word " << currWord
             << " is in the dictionary.";
    else cout << "\nThe word " << startWord
              << " is not in the dictionary.";

The idea is that for each letter in the given word we can read through the FourLetterWords text file and look for a match. If no match is found, we'll know because we're at the end of the file.

But there's a logic flaw. Look at the following output to see the flaw in action:

We're going to play doublet...eventually.

For now, just enter a starting four letter word
and the computer will validate whether or not it
is a four letter word in the Scrabble list: COUT

Your start word is COUT
The word CRIT is in the dictionary.

Now enter the end word: CRIP

The word CROP is in the dictionary.

So neither "COUT" nor "CRIP" are in our dictionary, though some dictionaries list "crip" as word for "cripple" which is generally considered offensive, so I'm just as glad to leave it out.

DOUBLET PROBLEM #1: Figure out what the logic flaw is and fix it.

In the following pseudocode for the basic logic I used in tackling this, I use two boolean flags: one to indicate whether or not the word has been found yet and one for whether or not the search has failed:

1.  Set flags to indicate that the word has not yet been found and the search has not failed.
2. While the search has not succeeded, keep looking.
3. Create a letter index for which letter of the dictionary word you're going to compare with the corresponding letter of your start word and initialize it to = 0. This is the basic comparison we need to see if we've found the word or not.
4. Reset the file pointer to the beginning of FourLetterWords
5. While your search hasn't failed and while your letter index is less than 4, do the following:
6. Keep getting the next word from the FourLetterWords file until the index letters match.
7. If you get a match, make sure all the previous letters are still the same - if one of the previous letters is different then the search has failed and you can set that flag.
8. Increment letter index (it's counting from 0 to 3 by steps of 1.)
9. If the search is successful then set a boolean flag to indicate that you've the word is good and you can move on.
10. If the search has failed, prompt the user for a different word and then if it's a four letter word, loop back and search the FourLetterWords file again (use boolean flags to work this magic.)

3. Once we have properly validated that the two words supplied by the user are four letter words in our list, the next thing we may want to do is establish a metric for the distance between two four letter words as the number of letters by which they differ.

DOUBLET PROBLEM #2: Write code that will compute and report the number of characters by which two words differ. For example the distance from TORT to TROT is 2, since they differ in the 2nd and 3rd characters.

4. To play this game on a computer, it may be useful to define the "value" of a four-letter word as the number of four-letter words which differ from that word by 1 letter.

DOUBLET PROBLEM #3: Write code that will take a four-letter word and then count and list all the words at a distance one from that word.

When you're done with problem 3 you should put it all together in program that will reliably produce output similar this:

We're going to play doublet...eventually.

For now, just enter a starting four letter word
and the computer will validate whether or not it
is a four letter word in the Scrabble list: TAMP

You entered TAMP.
The word TAMP is in the dictionary.

Now enter the end word: RUMP

The word RUMP is in the dictionary.
The word TAMP is at a distance 2 from RUMP

The words at a distance 1 from TAMP are:
CAMP DAMP GAMP LAMP RAMP SAMP TAME TAMS TARP TEMP TUMP TYMP VAMP

The value of TAMP is 13
Enter q to quit:

As an aside, the Scrabble dictionary contains some questionable words that traditional dictionaries don't necessarily include, but all of these seem to be good.

Merriam Webster offers this for GAMP:

Britain : a large umbrella *halfway to the station my gamp blew inside out Sydney (Australia) Bulletin*; often : one that is untidily or loosely tied up *if you carry an umbrella use it tightly rolled and never as a gamp S.D.Barney

TAM is short for tam-o-shanter, a woolen cap of Scottish origin that is made with a tight headband and a very wide flat circular crown usually with a pompon in the center compare BONNET

TUMP has two definitions: 1 chiefly dialect England : a small rise of ground: as a : MOUND, HUMMOCK b : MOLEHILL c : ANTHILL d : 1BARROW 2, TUMULUS
2 : a clump of vegetation (as trees, shrubs, or grass); especially : one making a dry spot in a swamp

TYMP is short for tympan: the stone or the water-cooled iron casting protecting the top of the opening through which molten slag and iron continually pass into the forehearth in an old type open-front iron blast furnace

VAMP is loaded with meaning. 1 dialect : a short hose coming to the calf formerly sometimes worn over a stocking : SOCK
2 : the part of a shoe upper or boot upper covering especially the forepart of the foot and sometimes also extending forward over the toe or backward to the back seam of the upper see BROGUED VAMP, CIRCULAR VAMP, THREE-QUARTER VAMP, WHOLE VAMP; SHOE illustration
3 [2vamp] a : a simple musical accompaniment improvised for the occasion b : an introductory section of two or four measures often played several times (as in vaudeville) before a solo or between verses while the soloist is preparing to sing or is indulging in byplay
4 [2vamp] : something vamped or patched up; especially : a literary composition based on old material

transitive verb
1 a : to provide (a shoe) with a new vamp : REVAMP b : to piece (something old) with a new part : PATCH used often with together or up *vamp up old sermons* *a vamped play*
2 : INVENT, CONCOCT, FABRICATE usually used with up *vamp up an excuse* *hastily vamped-up pretext*
3 obsolete : to make to present (one) as something else
4 dialect : to walk or tramp over or along
5 : to make a vamp to : improvise (an accompaniment) for a solo
intransitive verb
1 dialect : to go on foot : TRAMP, PLOD
2 : to play a vamp or a vamped accompaniment

==============================================================

Babylonian Algorithm

Write C++ code to implement the Babylonian algorithm as described in the flow chart below

flowchart

=======================================

List Primes

Write a function called isPrime that will take an integer and determine whether or not it is prime. Start be validating that the integer is greater than 1.  Then write a program that uses isPrime to write the prime numbers less than 100 to a file.

 

==========================================

Binomial Theorem

Write a function called factorial that will take an unsigned short and return its factorial as an unsigned long. Write another function called binomial, which will call factorial and input two unsigned shorts to compute the binomial coefficient B(n,k) = n!/(k!(n-k)!) which it will return as an unsigned long.. Then write a program that uses these function to expand the expression
bin

 

=================================

King's Tour.

Read the paper here and answer the questions about it at ILRN.COM.

The ultimate goal here is to develop some robust tools for investigating king's tours under various rules and conditions.

We'll take it one baby step at a time.

King's TourProblem 1: Write a program that will ask the user to supply the dimensions of the board: m and n and the row, column coordinates of the original position of the king on the board and then display the board, showing an m by n array of zeros and ones: zeros for the positions the king has not yet visited and 1's for the position (only one initially) it has visited.
King's Tour Problem 2: Amend the code we wrote in class to add the "even rule" and then display the king's tour as an array on the console.
King's Tour Problem 3: Iterate the king's tour 100 or more times and create an array to keep track of, for a given m by n board how many kings tours of length k there are where 0 < k < m*n. Compare results with the even rule and without the even rule.