Wednesday, November 30, 2016

Homework 21

Homework 21 has you add a few things to the code we wrote in class last Monday night.

Homework 21

There may be one or two more quick homework assignments, one dealing with Merge Sort, after next Monday, and one dealing with pointers, which we may talk about next Monday.


Monday, November 28, 2016

Lab materials for Nov. 28

Presentation:
Shuffle Code
Code
//
//  main.cpp
//  Nov28Cards
//
#include <iostream>
#include <vector>
#include <string>
using namespace std;

enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES };

enum Rank { ACE=1, TWO, THREE, FOUR, FIVE, SIX, SEVEN,
    EIGHT, NINE, TEN, JACK, QUEEN, KING };

struct Card {
    Suit suit;
    Rank rank;
    
    Card();
    Card(Suit suit, Rank rank);
    void print();
    bool equals (const Card &c2) const;
    bool isGreater (const Card &c2) const;
};

// --------------------------------------------------
// Card methods
// --------------------------------------------------
bool Card::isGreater(const Card &c2) const {
    if (suit > c2.suit) return true;
    if (suit < c2.suit) return false;
    
    return (rank > c2.rank);
}

Card::Card() {
    suit = CLUBS;
    rank = ACE;
}

Card::Card(Suit suit, Rank rank) {
    this->suit = suit;
    this->rank = rank;
}

void Card::print () {
    vector <string> suits (4);
    vector <string> ranks (14);
    suits[0] = "Clubs";
    suits[1] = "Diamonds";
    suits[2] = "Hearts";
    suits[3] = "Spades";
    
    ranks[1] = "Ace";
    ranks[2] = "2";
    ranks[3] = "3";
    ranks[4] = "4";
    ranks[5] = "5";
    ranks[6] = "6";
    ranks[7] = "7";
    ranks[8] = "8";
    ranks[9] = "9";
    ranks[10] = "10";
    ranks[11] = "Jack";
    ranks[12] = "Queen";
    ranks[13] = "King";
    
    cout << ranks[rank] << " of " << suits[suit] << endl;
}

bool Card::equals(const Card &c2) const {
    return (suit == c2.suit && rank == c2.rank);
}

// --------------------------------------------------
// other methods
// --------------------------------------------------
bool equals (const Card &c1, const Card &c2) {
    return (c1.suit == c2.suit && c1.rank == c2.rank);
}

vector <Card> deck (52);

void printDeck(vector <Card> &deck) {
    for (int i=0; i<deck.size(); i++) {
        deck[i].print();
    }
}
// --------------------------------------------------
// Binary search
// --------------------------------------------------

int findBisect (const Card &card,
                const vector<Card> &deck,
                int low,
                int high) {
    
    cout << low << ", " << high << endl; // debug
    
    if (high < low) return -1;
    
    int mid = (low + high) / 2;
    
    if (equals (deck[mid], card)) return mid;
    
    if (deck[mid].isGreater(card)) {
        return findBisect (card, deck, low, mid-1);
    } else {
        return findBisect(card, deck, mid+1, high);
    }
}

int myrandom(int i) { return rand() % i; }

// --------------------------------------------------
// start here
// --------------------------------------------------

int main(int argc, const char * argv[]) {

    Card threeOfClubs (CLUBS, THREE);
    threeOfClubs.print();
    
    Card jack (DIAMONDS, JACK);
    jack.print();
    
    cout << threeOfClubs.equals(jack) << endl;
    
    cout << equals (threeOfClubs, jack) << endl;
    
    Card another3clubs (CLUBS, THREE);
    cout << threeOfClubs.equals(another3clubs) << endl;
    
    cout << jack.isGreater(threeOfClubs) << endl;
    
    // nested loop
    int i = 0;
    for (Suit suit = CLUBS; suit <=SPADES; suit = Suit(suit+1)) {
        for (Rank rank=ACE; rank<=KING; rank = Rank(rank+1)) {
            deck[i].rank = rank;
            deck[i].suit = suit;
            i++;
        }
    }
    
    printDeck(deck);
    
    cout << findBisect(deck[24], deck, 0, 51);
    
    Card fake (DIAMONDS, Rank(15));
    cout << findBisect (fake, deck, 0, 51);
    
    srand(time(0));
    random_shuffle(deck.begin(), deck.end(), myrandom);
    printDeck(deck);
    
    return 0;
}

Friday, November 25, 2016

Coding Assignments 19 and 20

Assignment 19. Finish and extend the complex number class.

Assignment 20. Create a rational number class with arithmetic functions.

These assignments will be due one week from tonight, Friday night, Dec. 2.


Homework answers

This is my code that accomplishes some of the assignments. In general, my code is much simpler than yours.

I'm sorry, I posted this a few days ago, but to the wrong blog!

Because I am posting this code, as of today I will not accept late or resubmitted work for assignments 3, 4, 5, 7, 8, or 9.

I intend to post the rest of the assignments shortly. I want you to be able to study my code as you study for the final exam. If you intend to turn in assignments 10 through 15, please do so right now. Once I publish the code for those assignments, I will no longer accept your work for credit.





Monday, November 21, 2016

Complex Number Class

//
//  main.cpp
//  complex
//
//  Created by Mark Brautigam on 11/21/16.
//  Copyright © 2016 Mark Brautigam. All rights reserved.
//

#include <iostream>
#include <cmath>
#include <assert.h>
using namespace std;

class Complex {
private:
    double real, imag; // rectangular coordinates
    double mag, theta; // polar coordinates
    bool cartesian, polar; // which set is valid?
    
    void calculateCartesian();
    void calculatePolar();
    
public:
    Complex();
    Complex(double r, double i);
    double getReal();
    double getImag();
    double getMag();
    double getTheta();
    void printCartesian();
    void printPolar();
    void setPolar (double m, double t);
};

void Complex::setPolar (double m, double t) {
    mag = m;
    theta = t;
    cartesian = false;
    polar = true;
}


void Complex::printCartesian() {
    cout << getReal() << " + " << getImag() << "i\n";
}

void Complex::printPolar() {
    cout << getMag() << " e^ " << getTheta() << "i\n";
}

void Complex::calculateCartesian() {
    assert(polar);
    real = mag * cos (theta);
    imag = mag * sin (theta);
    cartesian = true;
}

// not in textbook
void Complex::calculatePolar() {
    assert (cartesian);
    mag = sqrt (real * real + imag * imag);
    theta = atan ( imag / real );
    polar = true;
}

Complex::Complex () {
    cartesian = false;
    polar = false;
}

Complex::Complex (double r, double i) {
    real = r;
    imag = i;
    cartesian = true;
    polar = false;
}

double Complex::getReal() {
    if (cartesian == false)
        calculateCartesian();
    return real;
}

// not in textbook
double Complex::getImag() {
    if (cartesian == false)
        calculateCartesian();
    return imag;
}

// not in textbook
double Complex::getMag() {
    if (polar == false)
        calculatePolar();
    return mag;
}

// not in textbook
double Complex::getTheta() {
    if (polar == false)
        calculatePolar();
    return theta;
}

Complex add (Complex a, Complex b) {
    double real = a.getReal() + b.getReal();
    double imag = a.getImag() + b.getImag();
    Complex sum (real, imag);
    return sum;
}

Complex multiply (Complex a, Complex b) {
    double mag = a.getMag() * b.getMag();
    double theta = a.getTheta() + b.getTheta();
    Complex product;
    product.setPolar (mag, theta);
    return product;
}

int main(int argc, const char * argv[]) {
    
    Complex c (2.0, 3.0);
    c.printCartesian();
    c.printPolar();
    
    Complex d (17.0, 42.0);
    Complex sum = add (c, d);
    sum.printCartesian();
    
    Complex e (2, 2);
    Complex product = multiply (c, e);
    product.printCartesian();
    
    Complex bad;
    bad.printCartesian();
    
    cout << "I got this far!";
    
    return 0;
}

Presentation and code for Nov. 21 - Classes

Presentations:

Starting point code for tonight:
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
using namespace std;

struct Point {
    double x, y;
    
    Point (double xx, double yy);
    Point (Point &p);
    Point ();
    
    double distanceTo (Point other);
    string contents ();
    void print ();
};

struct Triangle {
    Point a, b, c;
    
    Triangle (Point aa, Point bb, Point cc);
    string contents ();
    double area ();
};

// POINT functions
//
// this causes problems and I didn't figure out why
//
Point::Point (double xx, double yy) {
  x = xx;
  y = yy;
}
 
Point::Point (Point &p) {
  x = p.x;
  y = p.y;
}

Point::Point () {
    x = 0; y = 0;
}

double Point::distanceTo (Point other) {
    // Pythagoream Theorem a^2 + b^2 = c^2
    double dx = other.x - x;
    double dy = other.y - y;
    return (sqrt (dx * dx + dy * dy));
}

string Point::contents () {
    return  "{ " + to_string(x) + ", " +
    to_string(y) + " }";
}

void Point::print () {
    cout << contents ();
}

// TRIANGLE functions
//
// Constructor
//
Triangle::Triangle (Point aa, Point bb, Point cc) {
    a = aa;
    b = bb;
    c = cc;
}

string Triangle::contents () {
    return "{ " + a.contents() + ", " +
    b.contents() + ", " +
    c.contents() + " }";
}

double Triangle::area () {
    // Compute the area of a triangle from its corner points
    
    // 1. Compute the lengths of the side
    double dbc = b.distanceTo(c);
    double dac = a.distanceTo(c);
    double dab = a.distanceTo(b);
    
    // 2. Plug the lengths into the standard formula
    double s = (dbc + dac + dab) / 2;
    double t = s * (s-dbc) * (s-dac) * (s-dab);
    return sqrt (t); // <cmath>
}

int main(int argc, const char * argv[]) {
    
    Point p ( 42, 17 );
    Point q ( 17, 42 );
    double d = p.distanceTo(q);
    cout << d << endl;
    d = q.distanceTo(p);
    cout << d << endl;
    cout << p.contents();
    cout << endl;
    
    Triangle t ( p, q, { 100, 100 } );
    cout << t.area();
    cout << endl;

    return 0;
}

Tuesday, November 15, 2016

Materials for Monday Nov. 14 Lab

Last night's topic was reading and writing files. There is no PowerPoint presentation this week. Here is a list of the main points:

  • Copy the colors in the next post into four text files: English.txt, French.txt, German.txt, and Spanish.txt.
  • Put the files in a place that you can easily type out the full path to. I suggest using your desktop or a folder on your desktop.
    • Mac desktop file example: /Users/markb/Desktop/French.txt
    • Windows desktop file example: c:\\Users\\davidf\\Desktop\\German.txt
    • Not that the Windows version has double backslashes. The backslash is an escape character in C++. In order to circumvent this, we escape the backslash itself by putting another backslash before it. You can look this up on the interwebs.
  • You must also have write permissions to the folder where you are going to put your files, if you are going to write new files into that folder.
  • Include <fstream> at the top of your code to get the file stream library functions.
  • An input file stream (reading a file) uses ifstream.
  • An output file stream (writing a file) uses ofstream.
Code for reading a file into a vector and using its data:
//
//  main.cpp
//  Nov14
//

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;

// This is a forward declaration
int lookupColor (vector<string> , string );

int main(int argc, const char * argv[]) {
    
    vector<string> colors;
    vector<int> colorNumbers;
    
    string s;
    cout << "What language would you like to use?";
    cout << "([E]nglish, [F]rench, [G]erman, [S]panish)\n";
    cin >> s;
    
    // Choose the file based on the user choice.
    // Could you put this in a separate function?
    // Remember, the function should not open the file,
    // because we don't do I/O operations in a function.
    // Instead, the function should return the file name
    // so the main function can open it.
    ifstream infile;
    switch (s[0]) {
        case 'E':
        default :
            infile.open("/Users/markb/Desktop/English.txt");
            break;
        case 'F':
            infile.open("/Users/markb/Desktop/French.txt");
            break;
        case 'G':
            infile.open("/Users/markb/Desktop/German.txt");
            break;
        case 'S':
            infile.open("/Users/markb/Desktop/Spanish.txt");
            break;
    }

    // Example of Windows path using escaped backslashes
    // c:\\Users\\davidf\\Desktop

    // Could we make the following block into a function that 
    // reads the contents of the file into a vector?

    // Check first to make sure we actually opened the file successfully
    if (infile.good()) {

        // Loop through all lines of the file until we reach the end of the file
        while (!infile.eof()) {
            // infile >> s;
            getline (infile, s);
            // cout << s << endl;
            colors.push_back(s);
        }
    }
    
    // Get the user's input (3 colors)
    // Could this be made into a function? Should it be?
    cout << "Please enter the color names: ";
    
    for (int i=1; i<=3; i++) {
        cout << i << ":";
        cin >> s;
        colorNumbers.push_back(lookupColor(colors, s));
    }
    
    // cout << colorNumbers[0] << " " << colorNumbers[1] << " " << colorNumbers[2];
    
    // cout << s << " has value " << lookupColor(colors, s) << endl;
    
    // Do the computation to get the resistor value.
    // Could this be made into a function? Should it be?
    // Remember, we shouldn't actually write to the output (cout)
    // from inside a function. 
    cout << "Resistance is " <<
        (colorNumbers[0] * 10 + colorNumbers[1]) *
        pow (10, colorNumbers[2]) << " ohms." << endl;
    
    return 0;
}

// Why does this function need both the haystack (vector)
// and the needle? Couldn't we just make the colors vector
// global and access the global variable? 
int lookupColor (vector<string> haystack, string needle) {
    for (int i=0; i<haystack.size(); i++) {
        if (haystack[i] == needle) {
            return i;
        }
    }
    return -1;
}



Code for writing a file to the disk:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(int argc, const char * argv[]) {
    
    ofstream outfile;
    outfile.open ("/Users/markb/Desktop/names.txt");
    
    cout << "Please input names or a blank line when finished.\n";
    string s;
    
    do  {
        getline (cin, s);
        // cout << "ok";
        outfile << s << endl;
    }
        while (s != "");
    
    return 0;
}


Here is the main function composed of other functions that do all the work. Is this main function easier to read? If you want to complete it, you just need to write all the other functions that get invoked.
int main(int argc, const char * argv[]) {
    
    vector<string> colors;
    vector<long> colorNumbers;
    
    // This function will prompt user for language, which
    // is OK because that is its primary purpose.
    string lang = getLanguage();
    
    ifstream infile;
    infile.open (getFileName(lang));
    
    if (infile.good()) {
        readFileIntoVector (infile, colors);
    }
    
    // This function will prompt user for colors, which
    // is OK because that is its primary purpose.
    getUserColorsIntoVector (colors, colorNumbers);
    
    cout << "Resistance is " << computeResistance(colorNumbers) << " ohms\n";
    
    return 0;
}


Monday, November 14, 2016

Colors in various languages

English
Black
Brown
Red
Orange
Yellow
Green
Blue
Violet
Gray
White
Spanish
Negro
Marron
Rojo
Anaranjado
Amarillo
Verde
Azul
Violeta
Gris
Blanco
French
Noir
Marron
Rouge
Orange
Jaune
Vert
Bleu
Violet
Gris
Blanc
German
Schwartz
Braun
Rot
Orange
Gelb
Grun
Blau
Lila
Grau
Weiss

Friday, November 11, 2016

Coding Assignment 16

Here is your assignment using structs with functions. You will create a Circle struct, with functions, similar to the Triangle struct we created in class last Monday night.

This assignment is due one week from tonight (Friday, Nov. 18).

Coding Assignment 16


Monday, November 7, 2016

Presentation and Code for Week 11

Presentations:
Starting point code:
#include <iostream>
#include <cmath>
using namespace std;

double PI = acos(-1);

struct Point {
    double x, y;
};

struct Triangle {
    Point a, b, c;
};

double dist (Point a, Point b) {
    // Pythagoream Theorem a^2 + b^2 = c^2
    double dx = a.x - b.x;
    double dy = a.y - b.y;
    return (sqrt (dx * dx + dy * dy));
}

double triangleArea (Triangle triangle) {
    // Compute the area of a triangle from its corner points
    
    // 1. Compute the lenghts of the side
    double a = dist(triangle.b, triangle.c);
    double b = dist(triangle.a, triangle.c);
    double c = dist(triangle.a, triangle.b);
    
    // 2. Plug the lengths into the standard formula
    double s = (a + b + c) / 2;
    double t = s * (s-a) * (s-b) * (s-c);
    return sqrt (t); // <cmath>
}

string pointContents (Point p) {
    return  "{ " + to_string(p.x) + ", " + 
                   to_string(p.y) + " }";
}

// NOT ADVISED
string printContents (Point p) {
    cout  "{ " << to_string(p.x) << ", " << 
                  to_string(p.y) << " }";
}

string triangleContents (Triangle t) {
    return "{ " + pointContents(t.a) + ", " + 
                  pointContents(t.b) + ", " + 
                  pointContents(t.c) + " }";
}

Code at end of class.

Triangle.hpp:
//
//  Triangle.hpp
//  Nov07
//

#ifndef Triangle_hpp
#define Triangle_hpp

#include <string>
using namespace std;

struct Point {
    double x, y;
    
    double distanceTo (Point other);
    string contents ();
    void print ();
};

struct Triangle {
    Point a, b, c;
    
    Triangle (Point aa, Point bb, Point cc);
    string contents ();
    double area ();
};

#endif /* Triangle_hpp */


Triangle.cpp:
//
//  Triangle.cpp
//  Nov07
//
//  Created by Mark Brautigam on 11/7/16.
//  Copyright © 2016 Mark Brautigam. All rights reserved.
//

#include <iostream>
#include <string>
#include <cmath>
#include "Triangle.hpp"
using namespace std;
 
     // POINT functions
     //
     // this causes problems and I didn't figure out why
     //
     /*Point (double xx, double yy) {
     x = xx;
     y = yy;
     }
     
     Point (Point &p) {
     x = p.x;
     y = p.y;
     }*/
    
    double Point::distanceTo (Point other) {
        // Pythagoream Theorem a^2 + b^2 = c^2
        double dx = other.x - x;
        double dy = other.y - y;
        return (sqrt (dx * dx + dy * dy));
    }
    
    string Point::contents () {
        return  "{ " + to_string(x) + ", " +
        to_string(y) + " }";
    }
    
    void Point::print () {
        cout << contents ();
    }


     // TRIANGLE functions
     //
     // Constructor
     //
    Triangle::Triangle (Point aa, Point bb, Point cc) {
        a = aa;
        b = bb;
        c = cc;
    }
    
    string Triangle::contents () {
        return "{ " + a.contents() + ", " +
        b.contents() + ", " +
        c.contents() + " }";
    }
    
    double Triangle::area () {
        // Compute the area of a triangle from its corner points
        
        // 1. Compute the lengths of the side
        double dbc = b.distanceTo(c);
        double dac = a.distanceTo(c);
        double dab = a.distanceTo(b);
        
        // 2. Plug the lengths into the standard formula
        double s = (dbc + dac + dab) / 2;
        double t = s * (s-dbc) * (s-dac) * (s-dab);
        return sqrt (t); // <cmath>
    }


main.cpp:
//
//  main.cpp
//  Nov07
//
#include <iostream>
#include <cmath>
#include <vector>
#include "Triangle.hpp"
using namespace std;

// Swap function does not work unless the parameters
// are passed by reference using &
// 
void swap (int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

int main(int argc, const char * argv[]) {
    
    vector<int> tester = { 1, 2, 3, 4, 5 };
    for (int i=0; i<tester.size(); i++) {
        cout << tester[i] << " ";
    }
    swap (tester[1], tester[2]);
    for (int i=0; i<tester.size(); i++) {
        cout << tester[i] << " ";
    }
    
    Point p = { 42, 17 };
    Point q = { 17, 42 };
    double d = p.distanceTo(q);
    cout << d;
    d = q.distanceTo(p);
    cout << d;
    cout << p.contents();
    cout << endl;
    
    Triangle t ( p, q, { 100, 100 } );
    cout << t.area();
    cout << endl;

    return 0;
}


Wednesday, November 2, 2016

Coding Assignments 13, 14, 15

These assignments are due at 11:59 pm next Wednesday night, Nov. 9.

Coding Assignment 13

This assignment uses random numbers and a for loop to create random hexadecimal colors.


Coding Assignment 14

This assignment uses two vectors and a for loop to translate color names from English to Spanish.


Coding Assignment 15

This assignment uses a vector and two nested for loops to sort strings entered by the user.


Extra Credit:

Look up the more optimized version of Bubblesort and modify Assignment 15 to use it. I suggest you use a standard data structures reference book such as Aho, Hopcroft, and Ullman. If you find code on the internet, it may or may not be correct.