Return-Path: <ciortiz@MIT.EDU>
Received: from grand-central-station.mit.edu by po11.mit.edu (8.9.2/4.7) id KAA11690; Fri, 19 Jul 2002 10:07:49 -0400 (EDT)
Received: from manawatu-mail-centre.mit.edu (MANAWATU-MAIL-CENTRE.MIT.EDU [18.7.7.71])
	by grand-central-station.mit.edu (8.9.2/8.9.2) with ESMTP id KAA17743
	for <sipb@MIT.EDU>; Fri, 19 Jul 2002 10:06:56 -0400 (EDT)
Received: from w20-575-4.mit.edu (W20-575-4.MIT.EDU [18.187.0.23])
	by manawatu-mail-centre.mit.edu (8.9.2/8.9.2) with ESMTP id KAA12510
	for <sipb@mit.edu>; Fri, 19 Jul 2002 10:06:56 -0400 (EDT)
Received: (from ciortiz@localhost) by w20-575-4.mit.edu (8.9.3)
	id KAA25808; Fri, 19 Jul 2002 10:06:55 -0400
Message-Id: <200207191406.KAA25808@w20-575-4.mit.edu>
To: sipb@MIT.EDU
Subject: and thanx for the support given throughout
Date: Fri, 19 Jul 2002 10:06:55 -0400
From: Carlos I Ortiz <ciortiz@MIT.EDU>


maybe u guyz didn't noticed but i passed by several times buggin u all a/b elementary C programming mistakes. so thank you for the advice, although i was left a bit overwhelmed after an internal word war w/in sipb folk regarding "which is the most practical intro language" and "what is the best intro textbook for such".

sincerely,

carlos i. ortiz

p.s. yes, the program:

#include <iostream.h>
#include <stdlib.h>
#include <time.h>
#include <iomanip.h>
// i only use iomanip.h for 1 calling of the setprecision function
// is that good coding? i do not know if this is healthy memory management
// then again, setprecision is the only function able to constrain a float num.

using namespace std;

int oper, a, b, c, d; 
// a & b are randomized values in which the math problems are based, c is sort of the solution of oper(a,b) to be chosen, d is the initialized guess
// oper is the initialized value for the desired operation. can be randomized as seen later on
int n=0, e=0, count=0, streak=0, digits=0, power10=0; 
// n = problem counter, e = error count; count = streak counter; streak stores a 'high score';digits=initialized choice of digit size; power10 is associated w/digit
clock_t start, end;
// are used to measure elapsed problem session time
clock_t* pstart = &start;
clock_t* pend = &end;
// are used to store the clock time from time() into their destination addresses (start & end)
bool goodbye=false;
bool start_again=false;
// used to determine quiting & start-from-beginning conditions, respectively
char reply[20] = {0};
// repeatedly used to accept most inputs throughout, and is  processed str => int in is_answer

void init_credits(void) // only prints out the free-of-use message, called right when main() starts
{
  cout << "\nWelcome to Mad Math v2.0. This program is intended for free and unrestricted use, and if you paid to obtain it, please contact ciortiz@mit.edu immediately. You are more than welcomed to improve the current software, provided that you may not acquire exclusive rights to its use and distribution arising from such alterations so as to gain profit or otherwise obstruct other people's right to use this software. This software is designated for personal or school use in the practice of basic arithmetic, and for anyone and everyone interested in excelling in the Basic Four (+ - x %). Please contact the previous address for any comments or suggestions.\n\n";
}

bool is_number(char& c) // determines if argument c is a number (true) or character / otherwise (false) w/in a string
{
  if (c < '0' || c > '9') return false;
  else return true;
}

bool is_answer(char answer[20], int& result) // takes answer string and turns into result, and checks if user is attempting to quit or start-all-over
{
  result=0; // putting a non-garbage value for result which will ultimately become str => int of char answer
  short ndig=0; // a right-to-left digit counter used to compute the tens power
  short wdig; // extracts the integer value from 0 to 9 of the equivalent literal character
  int p10=1; // initialized power of 10 to be incremented using ndig
  goodbye=false;
  start_again=true;

  if (!is_number(answer[0]) && answer[0]=='q' && answer[1]=='u' && answer[2]=='i' && answer[3]=='t') // checks if user entered 'quit' to consequently expedite exit
    {
      goodbye=true;
      start_again=false;
      return true;
    }
  else if (!is_number(answer[0]) && answer[0]=='m' && answer[1]=='e' && answer[2]=='n' && answer[3]=='u') // checks for user input 'menu' to start-all-over
    {
      goodbye=true;
      start_again=true;
      return true;
    }
  else
    {
      for (int i1=19; i1>=0;i1--) // loop will inspect all characters in answer[20], ignore spaces, and iterate the equivalent integer for the answer string
	{
	  if (is_number(answer[i1]))
	    {
	      ndig++;
	      p10 = (ndig==1 ? 1 : p10*10);
	      wdig = int(answer[i1] - '0');    
	      result += wdig*p10;      
	    }
	  else if (!is_number(answer[i1]) && answer[i1] != 0) // if a character is present (assumed mistakenly) in string among numbers, prompt again
	    {
	      result=0;
	      cout << "\nI couldn\'t get that:\n>";
	      return false;
	    }
	}
    }
  return true;
}
      
void addt(int& x,int& y,int& z) // subroutine that takes x & y as references of a & b, computes correct add result, and assigns c to z (oper(a,b)=addition)
{
  z = x + y;
  cout << "\t" << x;
  cout << "\n+\t" << y;
}

void subt(int& x,int& y,int& z) // subroutine that takes x & y as references of a & b, computes correct minus result, and assigns c to z (oper(a,b)=subtraction)
{
  z = x - y;
  cout << "\t" << x;
  cout << "\n-\t" << y;
}

void mult(int& x,int& y,int& z) // subroutine that takes x & y as references of a & b, computes correct times result, and assigns c to z (oper(a,b)=multiplication)
{
  z = x * y;
  cout << "\t" << x;
  cout << "\nx\t" << y;
}

void divt(int& x,int& y,int& z) // subroutine actually inverses the results of the mult(&x,&y,&z) to maximize relevant divisions (no remainders in this case)
{
  z = x * y;
  int temp = z;
  z = y;
  y = x;
  x = temp;
  cout << char(9) << x;
  cout << "\n%\t" << y;
}

int main()
{ 
  init_credits();
  cout << "\n\nHow are you doing today? What is your first name?\n>"; // b.s. name asking
  char name[10] = {0};
  cin >> name;
  cout << "\n\nHey " << name << ", we are going to do some mad math drilling today.\n";
  cout << "Are you up to it? I thought so, so let's get on with it !! :o)";
  cout << "\n\nThis program will practice adding, subtracting, multiplying, and dividing.\n";
  do // will prompt for desired operation, 0 randomized operator & 5 is an exepted exercise
   {
     cout << "\nDo you want to practice any one of them in particular\n";
     cout << ", or do you want to try all the operations at random? Choose:\n";
     cout << "0 for random\n";
     cout << "1 for adding\n";
     cout << "2 for subtracting\n";
     cout << "3 for multiplying\n";
     cout << "4 for dividing\n";
     cout << "5 for times table practice\n";
     cout << "\n>";
     int choice=-1; // REDUNDANT, only to force a false value in the 2nd bool exp in the while(x || y)
     do 
       {
	 for (short dummy=0; dummy<20; dummy++) reply[dummy]=0; 
	 // clears reply characters inputed previously (not necessary in this line, but placed anyway as a precedent to repeated callings of the is_answer function
	 // which requires reply to be all blanks, since let's say a previous reply input with more non-space characters may overlap a newer reply input with less
	 // non-space characters. That will cause the is_answer function to process the incorrect string without remedy
	 // notice in later callings of the is_answer function as part of this do-while loop that the do-while loop is exactly the same for at least ten calls
	 // of is_answer. the reason for doing the do-while loop with the blank character for loop and the cin >> reply functions alone
	 // 10 times in main() instead of including it in is_answer is b/c i was having trouble passing a string (char array) reference as an argument.
	 // perhaps, if it was only a matter of syntax, and someone was kind enough of checking that out, the program can be cleaned up a lot better.
	 cin >> reply; 
       }
     while (!is_answer(reply,choice) || (choice < 0 || choice > 5));
     if (goodbye) continue; 
     // this repeated calling of if (goodbye) continue after the do-while(is_answer) loop serves to skip the rest program as soon as the users requests it
     int finish=0; int amount=-1; // simply initializing these variables to force a partial force condition as done earlier for other variables

     cout << "\n\nRemember to enter \'quit\' at any time to quit,"; // the quit and menu reminders for the user to keep in mind
     cout << "\nor enter \'menu\' to go back to the menu.\n";
     
     // this portion will determine the 2nd operand of the moduli in the rand() callings seen later on for obtaining random numbers of a specified amt. of digits
     cout << "\nWith how many digits do you want to practice (max=5):"; 
     cout << "\n>";

     do 
       {
	 for (short dummy=0; dummy<20; dummy++) reply[dummy]=0;
	 cin >> reply; 
       }
     while ((!is_answer(reply,digits) || (digits < 1 || digits > 5)) && !goodbye);
     if (goodbye) continue;

     power10 = 1;
     for (short i3=1;i3<=digits;i3++) power10 *= 10; // calculates corresponding power of ten given the user inputed 'digit' value

     // if the user is not doing the times tables, he will now choose a limit for the session, either by number of problems or by amount of time. even though
     // the user is technically 'forced' to place a condition for session termination, there is no upper bound on 'amount' input

     if (choice!=5) 
       {
	 cout << "\nNow choose whether to practice a certain amount of problems\n";
	 cout << ", or to practice for a certain amount of time?";
	 cout << "\nEnter 1 to practice x amount of problems,";
	 cout << "\nEnter 2 to practice for an x amount of minutes.";
	 cout << "\n>";
	 for (short dummy=0; dummy<20; dummy++) reply[dummy]=0;
	 do 
	   {
	     for (short dummy=0; dummy<20; dummy++) reply[dummy]=0;
	     cin >> reply; 
	   }
	 while ((!is_answer(reply,finish) || (finish < 1 || finish > 2)) && !goodbye);
       }
  
     if (finish==1)
       { 
	 cout << "How many problems do you want to do?\n>";
	 for (short dummy=0; dummy<20; dummy++) reply[dummy]=0;
	 do 
	   {
	     for (short dummy=0; dummy<20; dummy++) reply[dummy]=0;
	     cin >> reply; 
	   }
	 while ((!is_answer(reply,amount) || amount < 1 ) && !goodbye);
       }
     else if (finish==2)
       {
	 cout << "For how many minutes do you want to practice?\n>";
	 for (short dummy=0; dummy<20; dummy++) reply[dummy]=0;
	 do 
	   {
	     for (short dummy=0; dummy<20; dummy++) reply[dummy]=0;
	     cin >> reply; 
	   }
	 while ((!is_answer(reply,amount) || amount < 1 ) && !goodbye);	 
       }     
     else amount=1; // no real reason except to avoid an uninitialized 'amount' arising from an unforeseen circumstance
     // i've done this sort of redundancy throughout, may delete them and rename the program to see how it functions

     if (goodbye) continue; // second reminder
     cout << "\nOk then - Good luck ...";
     cout << "\n\nRemember to enter \'quit\' at any time to quit,";
     cout << "\nor enter \'menu\' to go back to the menu.";
     bool stay_ticket; // declaring condition in which the user will keep looping over problems
     // involves a variety of factors defined explicitly at the end of this do-while loop
     n=0;e=0;streak=0;count=0; // must set all these b4 the session
     srand(time(pstart)); // i understand there is a need for only one seed per session

     do
       {
	 if (choice==0) oper = rand()%4; // sets random operator that goes into any of the if-else-if statements below
	 else oper = choice - 1; // works for all except 'choice'==5, for which 5-1=4%4 = 0 modulo; exception handled below 
	 a = rand() % (power10-power10/10) + power10/10; // creates a random number from 10^n -> (10^(n+1) - 1)
	 b = rand() % (power10-power10/10) + power10/10; // same as above
	 c = 0;
	 cout << "\n\n";
	 int i1=1; int i2=1; // initializing counters for special times tables choice, if needed
	 if (oper%4==0 && choice != 5) addt(a,b,c); // 1st four basic opers, last is times tables
	 else if (oper%4==1) subt(a,b,c);
	 else if (oper%4==2) mult(a,b,c);
	 else if (oper%4==3 && a !=0) divt(a,b,c);
	 else if (choice==5)
	   {
	     i1 = n/12+1;
	     i2 = ((n+1)%12 == 0 ? 12 : (n+1)%12);
	     mult(i1,i2,c);
	   }
	 cout << "\n__________"; // problems printed vertically for quick column math, this line prints the total bar

	 do // this loop continues until  the user to input an answer that is both valid (all integer) and correct
	   {
	     cout << "\n\t";
	     do 
	       {
		 for (short dummy=0; dummy<20; dummy++) reply[dummy]=0;
		 cin >> reply; 
	       }
	     while (!is_answer(reply,d) && !goodbye);
	     if (goodbye) continue;
	     else if (d != c) // even though redundance lies in this bool exp and the while loop exit condition, this special block takes charge
	       // of both counting the errors and resetting the streak-associated values
	       {
		 e++;
		 if (count > streak) streak = count;
		 count=0;
	       }
	   }
	 while (d != c && !goodbye);

	 if (!goodbye) // streak and total-problems counters are incremented if user does not type 'quit' or 'menu'
	   {
	     n++; 
	     count++;
	   }
	 
	 time(pend); // final time of 1 problem recorded, done consecutively until user exits session
	 stay_ticket = ( !goodbye && ( finish==1 ? n < amount : finish==2 ? int(end-start) < amount*60 : true ) && (choice==5 ? n < 144 : true) );
         //in other words, stay if user doesn't type 'quit' or 'menu' AND, EITHER total-problem amount or total-minutes amount is not reached OR times-tables is not completed
       }
     while (stay_ticket);

     if (goodbye && n==0) break; // if student typed 'quit' and he did no problems, do not show stats and just quit or restart

     time(pend);
     cout << "\n\n" << (start_again ? "Good job, " : "Thanks for practicing, ") << name << ". Here are your stats for the session:";
     cout << "\n\nTotal Problems:\t" << n;
     cout << "\n\nTotal Mistakes:\t" << e;
     cout << "\n\nLongest Streak:\t" << streak;
     cout << "\n\nTotal Time:\t";
     clock_t sect = (end-start);
     int secs = int(sect); // conversions only done to extract # of minutes without tinkering with more advanced time.h functions
     int mins = secs/60;
     secs %= 60;
     cout << mins << " mins : " << secs << " secs.";
     cout << "\n\nAverage Time:\t" << setprecision(2) << float(int(sect)/n)+float(int(sect)%n)/float(n);
     cout << " secs.\n\n";
     if (goodbye) continue; // do not ask user if s/he already typed quit or menu
     cout << "Do you want to try again? Type y or yes and press enter to continue, or otherwise to exit:\n>";
     cin >> reply; 
     if (reply[0] == ('y' || 'Y')) start_again=true;
     else start_again=false;
     cout << endl << endl;
   }
 while (start_again);
 cout << "\n\ngoodbye :p\n\n";
 return EXIT_SUCCESS;
}


