CECS 282 Program 1 to 6 solutions

$140.00

Original Work ?
Category: You will Instantly receive a download link for .ZIP solution file upon Payment

Description

5/5 - (1 vote)

Solitaire Prime – Prog 1 CECS 282-01

Solitaire is a card game that is played by one person. Solitaire is also known by the name “Patience”.

It is estimated that there are more than 1700 different versions of Solitaire… make that 1701 because we are inventing a new Solitaire game today.

 

Welcome to Solitaire Prime! This game uses one standard deck of cards. Here are the rules:

 

  • Take the top card from the deck and place it face up on the table.
  • The Sum is now the value of that card (Ace = 1, 2 = 2, … 10 = 10, Jack = 10, Queen = 10, King = 10)
  • If the Sum is a prime number, discard that pile (hand), and start over at instruction #1
  • If the Sum is not prime, take the next card from the top of the deck and place it on top of the card stack (pile or hand) on the table.
  • The Sum is now the sum of all cards in the stack on the table.
  • Go to instruction #3.

 

Continue to play the game, keeping track of how many piles you have created that are prime.

 

If the last card from the deck gives you a prime pile, then you win! Write the word “Winner” on the screen and show how many prime piles there were.

 

If the last card from the deck does not give you a prime pile, then you lose. Write the word “Loser” in the screen.

 

These 2 screen shots show possible winner and loser hands. When you acquire a Prime pile, print out the value (prime number) and start over on the next line.

 

 

 

 

 

You will have 2 classes:

  • The Deck class which will create the deck of cards
  • The Card class which creates cards

 

The main logic of the program will be in the main function. You will use the Card class and the Deck class to play the game.

 

Here the methods you will need to create. Feel free to add more if you need them.

 

public class Deck

public Deck( ) // constructor which creates a deck of 52 cards. Ace of Spades on top, followed by the rest of the spades in order, followed by Hearts, Diamonds and Clubs.

public void refreshDeck(); // reset the deck so it looks like a new deck.

public Card deal( ) // deal a card from the top of the deck.

public void shuffle( ) // shuffle the cards in the deck.

public int cardsLeft( ) // return the number of cards left in the deck

public void showDeck( ); // show all the cards in the deck: 13 columns and 4 rows.

 

public class Card

public Card( ) // create a “blank” card

public Card  ( char r, char s ) // constructor to create a card, setting the rank and suit

public void setCard( char r, char s) // set an existing blank card to a particular value

public int getValue( ) // return the point value of the card. Ace = 1, 2 thru 10, Jack = 10, Queen = 10, King = 10

public void showCard( ) // display the card using 2 fields… Ace of Spade:AS, Ten of Diamond:10D, Queen of Heart:QH, Three of Club:3C. (If you want to get fancy, you can use these symbols for the suit ♠, ♣, ♥, ♦)

 

 

In the main function, you will have a menu that looks like this:

 

Welcome to Solitaire Prime!

  • New Deck
  • Display Deck
  • Shuffle Deck
  • Play Solitaire Prime
  • Exit

 

New Deck will create an unshuffled deck in the following order: Spades, Hearts, Diamonds, Clubs… Ace, 2, 3, …, 10, Jack, Queen, King

Display Deck will display all cards in a grid: 13 columns by 4 rows.

Shuffle Deck will randomly shuffle all cards in the deck.

Play Solitaire will play the game as described above.

Exit will exit the program.

 

You must create your own function to shuffle (cannot use the random_shuffle provided by C++) and you must create your own function called “isPrime” (cannot use any C++ library function). One is NOT a prime number.

 

Objectives:

  • Understand how to create classes
  • Learn how to use arrays in C++
  • Learn how to use header files and .cpp file as separate files.
  • Learn about preprocessor directives, #include libraries, and “using namespace std”
  • Learn how to protect header files by using #ifndef, #define, #endif
  • Difference between array of objects in C++ verses Java.
    1. Java arrays of objects have object references -= not actual objects. No need for a default constructor – example –> array of cards: Card [ ] deck = new Card[52]; This array contains 52 Card references but no cards.
    2. C++ arrays of objects have the actual objects. Need to have a default constructor. Example-> Card deck[52]; This array contains 52 cards – you need to create a default constructor, then you need to reset all 52 cards to actual values with a function setCard(‘A’, ‘S’) for the Ace of Spades.
  • Introduce the rand() function for shuffling cards
  • Get a random number within a range of numbers

CECS 282-01 Advanced C++ Program 2 – myDate Object

Create a C++ class called myDate. It should have the following operations:

  • myDate() – default constructor. This will set the date to May 11, 1959
  • myDate(int M, int D, int Y) – overloaded constructor. This will set the date to the values passed in through the parameter list represented by Month, Day and Year.
  • void display() – display the date in the following format (May 11, 1959) Do NOT print a linefeed after the date.
  • void increaseDate(int N) – increment the date by N days.
  • void decreaseDate(int N) – decrement the date by N days.
  • int daysBetween(myDate D) – return the number of days between this date and the date D.  If date D is a future date, the return value will be a positive int.  If date D is in the past, the return value will be a negative int.
  • int getMonth() – return the month in integer form
  • int getDay() – return the day of the month
  • int getYear() – return the year
  • int dayOfYear() – return the number of days since the current year began. Example Jan 1 is 1, Feb 1 is 32.
  • string dayName() – returns Monday, Tuesday, etc according to the day of the week.

 

Write a driver program that tests each operation. I will provide a test program to you before the due date.

 

Note:

 

You can never have a date that is invalid. The only opportunity for this to happen will be with the overloaded constructor. Therefore if any invalid data is passed to this constructor, ignore all data and set the values to the default date.

 

I have included an explanation of Julian dates. You can make your life much easier by using this formula. The example code is written in FORTRAN.

 

You will need to use “pass by reference” for some of the functions in the Julian date converter.

 

Create 2 functions that are NOT class members. Locate these function in the top portion of the  myDate.cpp file. Here are the prototypes for these 2 functions:

 

int Greg2Julian(int month, int day, int year); // pass in the Month, Day, Year and return Julian number

 

void Julian2Greg(int JD, int & month, int & day, int & year); // pass in the Julian Date, and get the correct Month, Day and Year through the parameter list – pass by reference

 

Program #2 summary – myDate

 

Description:

Create a class that handles dates based on a specific definition of functions. The student will receive a test driver program the day before the program is due. The student is expected to create and test the myDate class based entirely on the specification.

 

Objectives:

In this assignment, the student is introduced to Julian dates which will help manipulate and manage dates. Formulas are provided that convert a Gregorian date (example: 5/11/1959) to a Julian date which is the number of days that has elapsed since Nov 28, 4768 BC (or 11/28/-4768). The student will need to use pass-by-reference parameter passing to implement the JulianToGregorian function since 3 parameters (month, day and year) have to be modified within the function and returned to the calling routine.

The following concepts will be learned:

  • Reference variables (AKA alias variables)
  • Pass by reference
  • Pass by value
  • Creating and Abstract Data Type (a class with associated values and functions)
  • Checking for valid objects at creation time

 

 

 

 

Converting Between Julian Dates and Gregorian Calendar Dates

 

The Julian date (JD) is a continuous count of days from 1 January 4713 BC (= -4712 January 1), Greenwich mean noon (= 12h UT). For example, AD 1978 January 1, 0h UT is JD 2443509.5 and AD 1978 July 21, 15h UT, is JD 2443711.125.

Conversion of Gregorian calendar date to Julian date for years AD 1801-2099 can be carried out with the following formula:

JD = 367K – <(7(K+<(M+9)/12>))/4> + <(275M)/9> + I + 1721013.5 + UT/24 – 0.5sign(100K+M-190002.5) + 0.5

where K is the year (1801 <= K <= 2099), M is the month (1 <= M <= 12), I is the day of the month (1 <= I <= 31), and UT is the universal time in hours (“<=” means “less than or equal to”). The last two terms in the formula add up to zero for all dates after 1900 February 28, so these two terms can be omitted for subsequent dates. This formula makes use of the sign and truncation functions described below:

The sign function serves to extract the algebraic sign from a number.
Examples: sign(247) = 1; sign(-6.28) = -1.

The truncation function < > extracts the integral part of a number.
Examples: <17.835> = 17; <-3.14> = -3.

Example: Compute the JD corresponding to 1877 August 11, 7h30m UT.
Substituting K = 1877, M = 8, I = 11 and UT = 7.5,
JD = 688859 – 3286 + 244 + 11 + 1721013.5 + 0.3125 + 0.5 + 0.5
= 2406842.8125

The formula given above was taken from the U.S. Naval Observatory’s no-longer- published Almanac for Computers for year 1990.

Also see our Julian date converter data service.

Fliegel and van Flandern (1968) published compact computer algorithms for converting between Julian dates and Gregorian calendar dates. Their algorithms were presented in the Fortran programming language, and take advantage of the truncation feature of integer arithmetic. The following Fortran code modules are based on these algorithms. In this code, YEAR is the full representation of the year, such as 1970, 2000, etc. (not a two-digit abbreviation); MONTH is the month, a number from 1 to 12; DAY is the day of the month, a number in the range 1-31; and JD is the Julian date at Greenwich noon on the specified YEAR, MONTH, and DAY.

 

Conversion from a Gregorian calendar date to a Julian date. Valid for any Gregorian calendar date producing a Julian date greater than zero:

      INTEGER FUNCTION JD (YEAR,MONTH,DAY)                                      C                                                                               C—COMPUTES THE JULIAN DATE (JD) GIVEN A GREGORIAN CALENDAR                    C   DATE (YEAR,MONTH,DAY).                                                      C                                                                                     INTEGER YEAR,MONTH,DAY,I,J,K                                           C                                                                                     I= YEAR                                                                         J= MONTH                                                                        K= DAY                                                                    C                                                                                     JD= K-32075+1461*(I+4800+(J-14)/12)/4+367*(J-2-(J-14)/12*12)                   2    /12-3*((I+4900+(J-14)/12)/100)/4                                      C                                                                                     RETURN                                                                          END

Conversion from a Julian date to a Gregorian calendar date.

      SUBROUTINE GDATE (JD, YEAR,MONTH,DAY)                              C                                                                       C—COMPUTES THE GREGORIAN CALENDAR DATE (YEAR,MONTH,DAY)               C   GIVEN THE JULIAN DATE (JD).                                         C                                                                             INTEGER JD,YEAR,MONTH,DAY,I,J,K                                   C                                                                             L= JD+68569                                                             N= 4*L/146097                                                           L= L-(146097*N+3)/4                                                     I= 4000*(L+1)/1461001                                                   L= L-1461*I/4+31                                                        J= 80*L/2447                                                            K= L-2447*J/80                                                          L= J/11                                                                 J= J+2-12*L                                                             I= 100*(N-49)+I+L                                                 C                                                                             YEAR= I                                                                 MONTH= J                                                                DAY= K                                                            C                                                                             RETURN                                                                  END

Example: YEAR = 1970, MONTH = 1, DAY = 1, JD = 2440588.

Reference: Fliegel, H. F. and van Flandern, T. C. (1968). Communications of the ACM, Vol. 11, No. 10 (October, 1968).

 

CECS 282-01 Program 3 – Structs and Pointers

Create student structure with the following fields:

  • Name (cstring or null-terminated character array)
  • Student ID (int – unique random value between 1000 and 9999)
  • grade (char – Values A thru F)
  • birthday (myDate – random value: range 1/1/2000 to 12/31/2005)
  • Home Town (string)

 

Create an array of pointers to students of size 10.                              Example: Student *stuPtr[10];

Write a function that populates the array with 10 students.               Example: populate(stuPtr);

 

Write a display function that displays the contents of the array on the screen as shown below – nicely formatted and left justified.

 

The displayed list should be nicely formatted with column names like this: All columns should be left-justified.

 

Name                          Student ID       Grade             Birthday                      Home Town

Tom Thumb                1002                 C                     January 1, 2002            Small Ville

Fred Flintstone            1995                 D                     February 3, 2003            Bedrock

Sponge Bob                 2987                 B                      June 3, 2001                 Bikini Bottom

 

Create a menu that shows the following options:

 

  • Display list sorted by Name
  • Display list sorted by Student ID
  • Display list sorted by Grade
  • Display list sorted by Birthday
  • Display list sorted by Home Town
  • Exit

 

You need to write a sorting function for each of the menu items – 5 options needs 5 functions.

 

Note:

 

You must create a function that returns a date between a range of 2 dates.

 

You will use the myDate class in this program – you will not create any other class. The Student structure is NOT a class.

 

Take advantage of your myDate class that you just wrote. Also, it might be helpful to create a new function that returns a string for the date format:

 

string myDate::toString( );

 

To help with formatting, you may want to use the library <iomanip> which includes the setw()

Prog#3 Teaching Objectives

  • Intro to pointers
  • Increment pointers
  • Intro to structs
    • Structs are data focused – typically do not have constructors
    • Classes are object focused
  • Introduce cstrings – null-terminated character array
  • Compare and contrast string with cstring
  • Manage cstrings
    • strlen, strcpy, strcat, strcmp,
  • Create and use simple sorting algorithm (bubblesort)
  • Array names act like pointers (const pointers)
  • sizeof( )
  • Use <iomanip> for format things nicely
  • Composition – including the myDate object inside the student structure – student “has-a” myDate

 

What to submit on Demo day:

 

Submit 1 file which will contain ALL of your code: your main program, the Student struct and the myDate class.

Screenshot of the program demo. Select option 1 and then select option 5.

CECS 282-04 Program 4 – Overloading Operators

Create a C++ class called upDate. It should have the following operations:

  • upDate( ) – default constructor. This will set the date to May 11, 1959 (A very important date!!!)
  • upDate(int M, int D, int Y) – overloaded constructor. This will set the date to the values passed in through the parameter list represented by Month, Day and Year. If any one of the parameters is out of range, the date is set to the default date.
  • upDate( int J) – overloaded constructor – create a date using the Julian date
  • ~upDate( ) – destructor. Be sure to de-allocate any memory that was allocated in the constructor.
  • void setDate(int M, int D, int Y) – works just like the constructor
  • int getMonth( ) – return the month in integer form
  • int getDay( ) – return the day of the month
  • int getYear( ) – return the year
  • string getMonthName( ) – return the name of the month

 

Add the necessary class methods (functions) to support the following:

  • upDate D1(10,27,2010); // overloaded constructor
  • upDate D2(D1);               // copy constructor
  • upDate D3 = D2;             // also copy constructor – initialize D3 to be copy of D2
  • D1 = D2;                           // assignment operator
  • D1 += 5;                            // add 5 days to D1, result is stored in D1
  • D1 -= 7;                             // subtract 7 days from D1, result is stored in D1
  • D3 = D2 + 5;                     // add 5 days to D2, assign result to D3
  • D3 = 5 + D2;                     // add 5 days to D2, assign result to D3
  • D3 = D2 – 4;                     // subtract 4 days from D2, assign result to D3
  • int x = D5 – D4;                // days between D5 and D4. Can be negative or positive
  • cout << upDate::GetDateCount(); // a static method that returns the number of upDate objects that currently exist
  • cout << D1;                       // will print “10/27/2010”
  • D1++;                                // increment D1 by one day – postfix style
  • ++D1;                                // also increment D1 by one day – prefix style
  • D1–;                                  // decrement D1 by one day – postfix style
  • –D1;                                  // decrement D1 by one day – prefix style
  • cout << D1.julian();        // print the Julian integer represented by D1
  • Comparison Operators
    • if (D1 == D2)
    • if (D1 < D2)
    • if (D1 > D2)

 

Additional requirements:

You MUST create a pointer in the private data members that points to an integer array. When you create an upDate object (using any constructor) you must dynamically allocate an array of three integers – the Month, Day and Year. Similar details must happen during the assignment operator.

 

Write a driver program that tests each operation. I will provide a test program to you before the due date.

 

 

Prog #4 Learning Objectives

 

  • Operator Overloading
  • Friend functions
  • Deep vs shallow copy – we require deep on this assignment because of dynamic memory in constructors
  • Big 3 – if a class defines any of these, it should define them all
    • Copy constructor
    • Assignment operator
    • destructor
  • Static data members to keep track of how many instances currently exist
  • Static class member functions

 

 

 

 

 

Converting Between Julian Dates and Gregorian Calendar Dates

 

The Julian date (JD) is a continuous count of days from 1 January 4713 BC (= -4712 January 1), Greenwich mean noon (= 12h UT). For example, AD 1978 January 1, 0h UT is JD 2443509.5 and AD 1978 July 21, 15h UT, is JD 2443711.125.

Conversion of Gregorian calendar date to Julian date for years AD 1801-2099 can be carried out with the following formula:

JD = 367K – <(7(K+<(M+9)/12>))/4> + <(275M)/9> + I + 1721013.5 + UT/24 – 0.5sign(100K+M-190002.5) + 0.5

where K is the year (1801 <= K <= 2099), M is the month (1 <= M <= 12), I is the day of the month (1 <= I <= 31), and UT is the universal time in hours (“<=” means “less than or equal to”). The last two terms in the formula add up to zero for all dates after 1900 February 28, so these two terms can be omitted for subsequent dates. This formula makes use of the sign and truncation functions described below:

The sign function serves to extract the algebraic sign from a number.
Examples: sign(247) = 1; sign(-6.28) = -1.

The truncation function < > extracts the integral part of a number.
Examples: <17.835> = 17; <-3.14> = -3.

Example: Compute the JD corresponding to 1877 August 11, 7h30m UT.
Substituting K = 1877, M = 8, I = 11 and UT = 7.5,
JD = 688859 – 3286 + 244 + 11 + 1721013.5 + 0.3125 + 0.5 + 0.5
= 2406842.8125

The formula given above was taken from the U.S. Naval Observatory’s no-longer- published Almanac for Computers for year 1990.

Also see our Julian date converter data service.

Fliegel and van Flandern (1968) published compact computer algorithms for converting between Julian dates and Gregorian calendar dates. Their algorithms were presented in the Fortran programming language, and take advantage of the truncation feature of integer arithmetic. The following Fortran code modules are based on these algorithms. In this code, YEAR is the full representation of the year, such as 1970, 2000, etc. (not a two-digit abbreviation); MONTH is the month, a number from 1 to 12; DAY is the day of the month, a number in the range 1-31; and JD is the the Julian date at Greenwich noon on the specified YEAR, MONTH, and DAY.

 

Conversion from a Gregorian calendar date to a Julian date. Valid for any Gregorian calendar date producing a Julian date greater than zero:

      INTEGER FUNCTION JD (YEAR,MONTH,DAY)                                      C                                                                               C—COMPUTES THE JULIAN DATE (JD) GIVEN A GREGORIAN CALENDAR                    C   DATE (YEAR,MONTH,DAY).                                                      C                                                                                     INTEGER YEAR,MONTH,DAY,I,J,K                                           C                                                                                     I= YEAR                                                                         J= MONTH                                                                        K= DAY                                                                    C                                                                                     JD= K-32075+1461*(I+4800+(J-14)/12)/4+367*(J-2-(J-14)/12*12)                   2    /12-3*((I+4900+(J-14)/12)/100)/4                                      C                                                                                     RETURN                                                                          END

Conversion from a Julian date to a Gregorian calendar date.

      SUBROUTINE GDATE (JD, YEAR,MONTH,DAY)                              C                                                                       C—COMPUTES THE GREGORIAN CALENDAR DATE (YEAR,MONTH,DAY)               C   GIVEN THE JULIAN DATE (JD).                                         C                                                                             INTEGER JD,YEAR,MONTH,DAY,I,J,K                                   C                                                                             L= JD+68569                                                             N= 4*L/146097                                                           L= L-(146097*N+3)/4                                                     I= 4000*(L+1)/1461001                                                   L= L-1461*I/4+31                                                        J= 80*L/2447                                                            K= L-2447*J/80                                                          L= J/11                                                                 J= J+2-12*L                                                             I= 100*(N-49)+I+L                                                 C                                                                             YEAR= I                                                                 MONTH= J                                                                DAY= K                                                            C                                                                             RETURN                                                                  END

Example: YEAR = 1970, MONTH = 1, DAY = 1, JD = 2440588.

Reference: Fliegel, H. F. and van Flandern, T. C. (1968). Communications of the ACM, Vol. 11, No. 10 (October, 1968).

 

CECS 282-04 Program 5 – goldRabbits: BigInt using vectors and maps

I got a pair of rabbits for my birthday.  I did some research and found out that apparently rabbits multiply like… well, Rabbits! So I have a great idea that will help me retire. I’m going to start a rabbit ranch. I need to plan for the future and determine how much land and rabbit food I will need for my rabbits.

Here are the Rabbit Rules:

  • New-born rabbits take one month to mature.
  • One pair of mature rabbits will have a pair of baby rabbits after one month.
  • Mature rabbits will continue to produce a new pair of baby rabbits every month.
  • Rabbits never die

I plan to retire in 10 years. How many rabbits will I have by then?

I did some hand calculations and I came up with this:

At the start of month 0, I receive the baby rabbits so I have 1 pair of rabbits.

At the start of month 1, the baby rabbits are grown and the female becomes pregnant. But I still have only 1 pair of rabbits.

At the start of month 2, the first pair give birth to 1 pair of rabbits, so now I have 2 pairs of rabbits. The first pair (the adults) immediately become pregnant again.

At the start of month 3, the second pair is now mature and the first pair give birth again to 1 pair of rabbits. This gives me 3 pairs of rabbits.

At the start of month 4, the first pair gives birth to a new pair, the second pair gives birth to a new pair, and the third pair are all grown up and ready to start family life. So now I have 5 pairs of rabbits.

By now I was getting confused with counting rabbits, but I noticed a pattern. It seemed like each new month the total number of pairs of rabbits was equal to the total number from the month before plus the total number from 2 months before. That’s really cool that I can predict the number of rabbit pairs with an equation.

I’m gonna call it “Master Gold’s Really Cool Formula for Rapid Rabbit  Population Growth”, or just GoldRabbits for short. (Apparently some Italian dude from the year 1202 named Fibonacci came up with something similar – but I think mine is better…)

Here’s the definition of GoldRabbits:

// this function predicts the number of rabbit pairs I will have after n months

int GoldRabbits( int n )

{

      if (n == 0 || n == 1)

return 1;

else

return GoldRabbits( n-1 ) + GoldRabbits( n–2 );

}

 

 

 

I wanted to see how many rabbits I would have in 10 years so I wrote this little program:

 

#include <iostream>

#include <time.h>

#include <iomanip>

using namespace std;

 

int goldRabbits(int);                                    // prototype or signature

 

int main()

{

int const months = 12 * 10;                      // this is 10 years or 120 months

int start = time(0);                             // number of seconds since Jan 1, 1970

for(int i=0; i<months; i++)

{

int current = time(0);                    // number of seconds since program started

cout << setw(5)<<current-start<<“:”;     // print elapsed seconds

cout << ”  GoldRabbits(“<<setw(2)<<i<<“) = “;

cout << setw(11)<< goldRabbits(i) <<endl;// the call to goldRabbits

}

}

 

// this is the goldRabbits function

int goldRabbits(int n)

{

if (n==0 || n==1)

return 1;

else

return goldRabbits(n-1) + goldRabbits(n-2);

}

 

After 17 minutes, (or 1023 seconds)  here is my output:

 

The first column is the number of seconds that has elapsed since the program started.

The second column shows the month number (how many months into the rabbit farm).

The third column shows the numbers of rabbits I currently have on the rabbit farm.

 

 

As you can see, I have a couple problems:

  • For some reason, the number got real big – it was approaching 2,147,483,647 at goldRabbits(45) – (Actual value was 1,836,311,903 when it suddenly went negative at goldRabbits(46)… That’s weird. Am I right? What is going on????

 

  • It’s taking a long, long time to calculate. At this rate, I will be retired before the calculation is complete…

 

Your assignment is to solve these 3 problems for me.

 

  • Write the goldRabbits(int n) function that throws an exception if it detects integer overflow. The exception will throw a string that indicates the input number (n) which caused the overflow.

 

  • You need to create a new Class called BigInt that will allow me to calculate the goldRabbits(120), or even goldRabbits(2000) so that my grand daughter can take over the rabbit farm. This is the prototype:
    1. BigInt goldRabbits(BigInt )
    2. Use the STL vector to store your digits so you can have BigInts that are infinitely long.
    3. Use the char data type to store “digits” in the vector

 

  • You need to modify the function goldRabbits so that it can calculate goldRabbits(2000) before we all die.
    1. Use the STL map to store the value of goldRabbits(n) so you can quickly use that value when you are trying to calculate goldRabbits(n+1). You will also need to use “static”. In other words, when you try to calculate goldRabbits(n), you should already have goldRabbits(n-1) and goldRabbits(n-2) stored and saved in your static map.
    2. You need to create a new class called BigInt so you can handle numbers greater that 2^31-1 (which is the largest positive integer that C++ can handle using the native data type int.) BigInt needs to handle addition and subtraction, constructor, copy constructor, assignment operator, destructor, and other functions as needed. But don’t create a function if you don’t need to. You will use the vector to store the digits or characters of your BigInt. Your storage for the BigInt class will be a vector of chars. You will treat the chars as if they were ints. The largest int value you can store in a char is 255 – which is way big enough since the largest digit is only 9. You need to implement the minus operator, but you can assume that your result will never be negative. In other words you do not need to support a negative BigInt.

 

 

  • You will write only one file for this program. The header portion for the BigInt class will be declared above main. The implementation of the BigInt class will be written after main. Any additional functions you use will follow the same structure – the prototypes will be before main and the implementation will be after main. Here is an example of how you would write a program that handled Cups:

 

#include <iostream>

using namespace std;

 

class Cup{     // this is the header portion of the Cup class

    private:

        int value;

    public:

        Cup(int);

        friend ostream & operator<<(ostream &, const Cup &);

        Cup operator+(Cup);

};

 

int main()   // this is the main function

{

    Cup c1(23);

    cout << c1<< endl;     // prints 23

    Cup c2(c1);            // copy constructor

    Cup c3 = c1 + c2;

    cout << c3;            // print 46

}

 

// implementation of Cup member and non-member functions below

Cup::Cup(int x){

    value = x;

}

 

ostream & operator<<(ostream &out , const Cup & C){

    cout << C.value;

}

      

Cup Cup::operator+(Cup C){

    Cup temp(*this);

    temp.value += C.value;

    return temp;

}

 

 

 

On demo day, you will run the following program. Notice that this program uses the slow version of goldRabbits and also calculates using int. You have to rewrite the goldRabbits( BigInt) function so it runs fast and uses BigInt. Also notice there are 2 ways to display a BigInt.

 

BigInt B1(“123456789123456789123456789”);

cout << B1;       // this number is more than 12 digits so it will display in scientific notation

B1.print();         // this will display all digits in the BigInt

 

#include <iostream>

#include “BigInt.h”

#include <map>  // you will need this for the goldRabbits function

using namespace std;

 

int goldRabbits(int);

BigInt goldRabbits(BigInt);

void pause() {cout << “Press Enter to continue…”; getchar();}

 

int main()

{

BigInt B1(“123456789123456789123456789123456789”);

BigInt B2(B1);

BigInt MAX(INT_MAX);

cout << “B1:”<<B1<<“\nB2:”<<B2<<“\nMAX:”<<MAX<<endl;

pause();

cout << “\nB1:”;

B1.print();

cout << endl;

pause();

 

//     for(BigInt i=0; i<=3000; i++)      // uncomment this

for(int i=0; i<=3000; i++)         // comment this out

{

cout << “\ngoldRabbits(“<< i <<“) = ” << goldRabbits(i);

}

pause();

 

cout<< “\nThis is the value of goldRabbits(3000)\n\n”;

BigInt gR3000 =  goldRabbits(BigInt(3000));

gR3000.print();

 

pause();

 

int n = 500;

try{

 

cout << “The value of goldRabbits(n) is:”<<goldRabbits(n)<<endl;

}

catch(string error)

{

cout << error << endl;

cout << “Transitioning to BigInt\n”;

cout << goldRabbits(BigInt(n));

}

 

pause();

}

 

// Modify this function so that it accepts BigInt as input parameter and returns a BigInt

// and uses a map for speed

int goldRabbits(int n)

{

if (n==0 || n==1)                                       // base case

return 1;

else

return goldRabbits(n-1) + goldRabbits(n-2);     // general case

}

 

This is the desired output:

 

B1:1.2345678912e36

B2:1.2345678912e36

MAX:2147483647

Press Enter to continue…

B1:123456789123456789123456789123456789

Press Enter to continue…

goldRabbits(0) = 1

goldRabbits(1) = 1

goldRabbits(2) = 2

goldRabbits(3) = 3

goldRabbits(4) = 5

goldRabbits(5) = 8

goldRabbits(6) = 13

goldRabbits(7) = 21

 

(some lines removed)

 

goldRabbits(56) = 365435296162

goldRabbits(57) = 591286729879

goldRabbits(58) = 956722026041

goldRabbits(59) = 1.5480087559e13

goldRabbits(60) = 2.5047307819e13

goldRabbits(61) = 4.0527395378e13

goldRabbits(62) = 6.5574703198e13

goldRabbits(63) = 1.0610209857e14

goldRabbits(64) = 1.7167680177e14

goldRabbits(65) = 2.7777890035e14

goldRabbits(66) = 4.4945570212e14

 

(many lines removed here)

 

goldRabbits(2994) = 3.702521137e626

goldRabbits(2995) = 5.990805043e626

goldRabbits(2996) = 9.693326181e626

goldRabbits(2997) = 1.568413122e627

goldRabbits(2998) = 2.537745740e627

goldRabbits(2999) = 4.106158863e627

goldRabbits(3000) = 6.643904603e627

Press Enter to continue…

 

This is the value of goldRabbits(3000)

 

664390460366960072280217847866028384244163512452783259405579765542621214161219257396449810982999820391132226802809465132446349331994409434926019045342723749188530316994678473551320635101099619382973181622585687336939784373527897555489486841726131733814340129175622450421605101025897173235990662770203756438786517530547101123748849140252686120104032647025145598956675902135010566909783124959436469825558314289701354227151784602865710780624675107056569822820542846660321813838896275819753281371491809004412219124856375121694811728724213667814577326618521478357661859018967313354840178403197559969056510791709859144173304364898001

Press Enter to continue…

 

The value of goldRabbits(500) is: Overflow Error – goldRabbits overflowed using 47

 

Press Enter to continue…

 

 

 

What to submit on demo day:

  • One single file which includes all the source code for this project.
  • One single screenshot similar to the above. In order to fit the output ona single screen, modify the for loop so that only the values of goldRabbits(x) print out where x is in the set of lines that are shown above.

 

The program is due by 8:30 PM on the due date.

CECS 282 Program 6 – Mega War / Inheritance

War is a simple game played with 2 players and one deck of cards. The deck is shuffles and then each player receives half the deck – so 26 cards per player. Then each player lays down one card. The player who owns the highest card wins the other player’s card and the winner puts both cards into his hand. In the event that both cards are the same value, then there is a war. Both players lay down 3 cards, and the fourth card is used as the battle card. The player with the highest battle card wins all 10 cards that are in play. If the battle cards produce another tie, then anther war happens.

 

The winner is the person who eventually obtains all the cards and the loser will have no cards left to play.

 

Your task is to build a card game called Mega War!

 

Mega War is similar to War, but you can play with more than 1 deck and more than 2 players. The winner will be the player who accumulates all the cards.

 

When Mega War starts, the program will ask for the number of decks, and the number of players. You could easily choose 1 deck and 2 players to simulate regular War – but what fun would that be… When you demo the program, you will play with 3 decks and 5 players. The game will continue until there is a single winner (who has all the cards).

 

The game play will be controlled with a loop. Each iteration will cause all the players to have a group battle. The player with the highest card wins all the other cards and adds them to his hand. If 2 or more players have the same highest card, then all players with the highest value card will have a war. The winner of the war will take all the cards. If a player cannot complete the War (because they ran out of cards) then that player loses and the other player acquires the war card pile. If both (or all) players cannot continue a war, then they all lose and the war card pile gets send to Lost and Found. The next time there is a war, the Lost and Found cards go to the winner of the war.

 

The value of each card is as follows: Ace = 1, Two = 2 and so on, Ten = 10, Jack = 11, Queen = 12, and King = 13.

 

There are a several things each player should keep track of.

  1. The number of cards in their hand
  2. The Fierceness of their hand. You can imagine that a hand that has many high-value cards is more likely to win than a hand that has many low-value cards. The Fierceness of a hand is the average value of all cards. A hand that has a King, Queen, 9 and 3 has a Fierceness value of 9.25. A hand that has 3, 8, 5 and Jack has a Fierceness value of 6.75. Based solely on that value, we might expect the first player to win the game.
  3. The number of battles the user played. The winner will probably play the most battles. However, that might not be the case if the winner did not participate on many wars.
  4. The number of battles the user won.

 

The game play will be in a loop until a winner is determined. After each battle, that stats for each player will be displayed like this:

 

Battle 66 Stats:

Player 1: Fierceness = 8.34        Cards = 16        Battles = 45      Won = 12

Player 2: Fierceness = 0             Cards = 0          Battles = 37      Won = 15

Player 3: Fierceness = 5.29        Cards = 38        Battles = 56      Won = 20

Player 4: Fierceness = 9.77        Cards = 102      Battles = 54      Won = 19

 

In the above stats, you can see that Player 2 has lost. Player 4 looks to be a likely winner eventually. Also the total number of cards (add all the player cards together) never changes. The game will stop when a winner has all the cards.

 

Now let’s think about the classes needed for this game. Obviously, a Card. And obviously a Deck. Beyond that we will need a Player, a MegaDeck (in case we user more than one deck), a War pile (when there is War), a Lost & Found pile. But wait – notice that a Deck, a Player, a War pile and Lost & Found are very similar. They are all Card containers. Here is an opportunity for inheritance. Create an Abstract Base Class called a CardPile that has a dynamic storage for Cards (vector) and also a add( )  and remove( ) function. Also include any other functions or data members that are common to ALL Card piles. Then make a concrete class for each of the classes needed.

 

Other Requirements:

    • Your Card class must use enumerated types (enum) for the rank and suit.
    • The Deck (or card pile) must use vector of cards instead of array of cards as you did in Solitaire Prime
    • You need to create a UML diagram for your classes. Show each class UML and also the relationship classes have to each other

 

What to submit to the Drop box:

Program source code.

Screenshot of final result for a game that has 3 decks and 5 players

UML diagrams