Question

In: Computer Science

This assignment uses a combination of classes and arrays. Instructions: 1) download the 3 program files...

This assignment uses a combination of classes and arrays.

Instructions:

1) download the 3 program files into a new C++ project.    NOTE: if your IDE does not allow you to create projects - or you are not sure how to do it - then you may combine the two cpp files into a single file.

2) Complete the program by adding code the the class methods. You may want to study the existing code first to get a feel for how to access the class attributes. There is no need to modify any of the methods that are already implemented.

UPDATE: You are working with magic_square.cpp. View comments as ref. Thank you.

Attachments ~ (3):

magic.h ~

#ifndef MAGIC_H
#define MAGIC_H

#define SQUARE_SIZE 3
class MagicSquare {
private:
    
    // matrix is a two-dimensional array that holds the 
    // magic square.  
    int matrix[SQUARE_SIZE][SQUARE_SIZE] = {{ 4, 9, 2 }, 
                                            { 3, 5, 7 },
                                            { 8, 1, 6 }};
    
public:
    
    // is_magic - returns true if matrix forms a magic square.  
    // a magic square is one that all the rows and all the cols and 
    // the two diagonals add up to the same number. 
    bool is_magic();
    
    // GIVEN : scramble(int loops) - switch two random elements of the matrix for form
    // a new square. 
    void scramble(int loops=1);
    
    // row_sum(int r) - return the sum of all the elements of row r. 
    int row_sum(int);
    
    // col_sum(int c) - return the sum of all the elements of column c.
    int col_sum(int);
    
    // diagnoal_left() - return the sum of all the elements from the upper-right
    // to lower-left. 
    int diagonal_left();
    
    // diagnoal_right() - return the sum of all the elements from the upper-left
    // to the lower-right. 
    int diagonal_right();
    
    // showMatrix() - Print the values of the matrix in a square format.  
    // For example: 
    //
    //    1 2 3
    //    4 5 6
    //    7 8 9
    //
    void showMatrix();
    
    // GIVEN:  set_matrix(int * array) - create a new matrix using the values
    // of the array.  
    void set_matrix(int *);
    
};

#endif

________________________________________________________________________________________________

magic_square.cpp ~

#include  
#include  
#include 
#include 
#include "magic.h"

using namespace std;
// Replace # after return as row_sum and col_sum 

int MagicSquare::row_sum(int r) {
    return matrix [0][0] + matrix [0][1] + matrix [0][2];
}

int MagicSquare::col_sum(int c) {
    return matrix [0][0] + matrix [1][0] + matrix [2][0];
}

int MagicSquare::diagonal_left() {
   return 0;
}

int MagicSquare::diagonal_right() {
    return 2;
}


bool MagicSquare::is_magic() {
 return false;
}

void MagicSquare::showMatrix() {

}

// Swap two random values of the matrix. 
void MagicSquare::scramble(int loops=1) {
    
    static bool _initialized = false;
   
    if (! _initialized) {
        srand((unsigned)time(0)); 
        _initialized = true;
    }
    while (loops--) { 
        int r1 = (rand()%SQUARE_SIZE);
        int c1 = (rand()%SQUARE_SIZE); 
        int r2 = (rand()%SQUARE_SIZE); 
        int c2 = (rand()%SQUARE_SIZE); 
        int temp = matrix[r1][c1];
        matrix[r1][c1] = matrix[r2][c2];
        matrix[r2][c2] = temp;
    }
}

// Create a new set of values for a magic square. The user should pass in an 
// array of 3 integers. 
void MagicSquare::set_matrix(int *values) {
   

    int a = values[0];
    int b = values[1]; 
    int c = values[2];
    
 matrix[0][0] = a;
 matrix[0][1] = 3 * c - a - b;
 matrix[0][2] = b;
 
 matrix[1][0] = c + b - a;
 matrix[1][1] = c;
 matrix[1][2] = c - b + a;
 
 matrix[2][0] = 2 * c - b;
 matrix[2][1] = a + b - c;
 matrix[2][2] = 2 * c - a;
   
}

_________________________________________________________________________________________________________

main.cpp ~

#include 
#include "magic.h"

using namespace std;
/*
 * 
 */

int main()
{       
    int times = 200000;
    MagicSquare square;
    int my_values[SQUARE_SIZE];
  
    cout << "Here is array \n\n";
    square.showMatrix();

    if (square.is_magic())
        cout << "\nIt is a magic square\n\n";
    else {
        cout << "Program is not working!!" << endl;
        return 1;
    }

    while (times--) {
        square.scramble();
        if (square.is_magic()) {
            cout << "Found one !!" << endl;
            square.showMatrix();
            cout << endl;
        }
    }
    
    cout << "Now you try!  Enter " << SQUARE_SIZE << " values" << endl;
            
    // Collect 3 values from the user and store them in an array called my_values
   
    // Call the set_matrix method and pass in the my_values array.
 
    // Display the new matrix using the showMatrix() method. 

    // Copy the while loop above to search for more versions of this magic square. 

     
    return 0;

} // End main function

Solutions

Expert Solution

magic.h

#ifndef MAGIC_H
#define MAGIC_H

#define SQUARE_SIZE 3
class MagicSquare {
private:

// matrix is a two-dimensional array that holds the
// magic square.
int matrix[SQUARE_SIZE][SQUARE_SIZE] = {{ 4, 9, 2 },
{ 3, 5, 7 },
{ 8, 1, 6 }};

public:

// is_magic - returns true if matrix forms a magic square.
// a magic square is one that all the rows and all the cols and
// the two diagonals add up to the same number.
bool is_magic();

// GIVEN : scramble(int loops) - switch two random elements of the matrix for form
// a new square.
void scramble(int loops=1);

// row_sum(int r) - return the sum of all the elements of row r.
int row_sum(int);

// col_sum(int c) - return the sum of all the elements of column c.
int col_sum(int);

// diagnoal_left() - return the sum of all the elements from the upper-right
// to lower-left.
int diagonal_left();

// diagnoal_right() - return the sum of all the elements from the upper-left
// to the lower-right.
int diagonal_right();

// showMatrix() - Print the values of the matrix in a square format.
// For example:
//
// 1 2 3
// 4 5 6
// 7 8 9
//
void showMatrix();

// GIVEN: set_matrix(int * array) - create a new matrix using the values
// of the array.
void set_matrix(int *);

};

#endif

-------------------------------------------------------------------

magic_square.cpp

//magic_square.cpp ~

#include <iostream>
#include "magic.h"
#include <stdlib.h>
#include <ctime>
using namespace std;
// Replace # after return as row_sum and col_sum

int MagicSquare::row_sum(int r) {
// return matrix [0][0] + matrix [0][1] + matrix [0][2];
return matrix [r][0] + matrix [r][1] + matrix [r][2];
}

int MagicSquare::col_sum(int c) {
//return matrix [0][0] + matrix [1][0] + matrix [2][0];
return matrix [0][c] + matrix [1][c] + matrix [2][c];
}

int MagicSquare::diagonal_left() {
//sum of left diagonal elements
return matrix [0][0] + matrix [1][1] + matrix [2][2];

}

int MagicSquare::diagonal_right() {
//sum of RIGHT diagonal elements
return matrix [0][2] + matrix [1][1] + matrix [2][0];
}


bool MagicSquare::is_magic() {

///first check sum of row(0) == sum of row(1) == sum of row(2)
if(row_sum(0) == row_sum(1) && row_sum((1) == row_sum(2))){
///means all rows have same sum
if(col_sum(0) == col_sum(1) && col_sum(1)== col_sum(2)){
///here all row and cols sum is same
if(diagonal_left() == diagonal_right()){
///here Sum of all rows = Sum of all cols =Sum of all diagonals
return true;
}
}

}

return false;
}
// showMatrix() - Print the values of the matrix in a square format.
void MagicSquare::showMatrix() {
cout<<endl;
for(int i=0;i<SQUARE_SIZE;i++){
for(int j=0;j<SQUARE_SIZE;j++){
cout<<matrix[i][j]<<" ";
}
cout<<endl;

}


}

// Swap two random values of the matrix.
void MagicSquare::scramble(int loops) {

static bool _initialized = false;

if (! _initialized) {
srand((unsigned)time(0));
_initialized = true;
}
while (loops--) {
int r1 = (rand()%SQUARE_SIZE);
int c1 = (rand()%SQUARE_SIZE);
int r2 = (rand()%SQUARE_SIZE);
int c2 = (rand()%SQUARE_SIZE);
int temp = matrix[r1][c1];
matrix[r1][c1] = matrix[r2][c2];
matrix[r2][c2] = temp;
}
}

// Create a new set of values for a magic square. The user should pass in an
// array of 3 integers.
void MagicSquare::set_matrix(int *values) {


int a = values[0];
int b = values[1];
int c = values[2];

matrix[0][0] = a;
matrix[0][1] = 3 * c - a - b;
matrix[0][2] = b;

matrix[1][0] = c + b - a;
matrix[1][1] = c;
matrix[1][2] = c - b + a;

matrix[2][0] = 2 * c - b;
matrix[2][1] = a + b - c;
matrix[2][2] = 2 * c - a;

}

-----------------------------------------------------------------------------------

main.cpp

#include <iostream>
#include "magic.h"

using namespace std;

int main()
{
//int times = 200000;
int times = 5;
MagicSquare square;
int my_values[SQUARE_SIZE];

cout << "Here is array \n\n";
square.showMatrix();

if (square.is_magic())
cout << "\nIt is a magic square\n\n";
else {
cout << "Program is not working!!" << endl;
return 1;
}

while (times--) {
square.scramble();
if (square.is_magic()) {
cout << "Found one !!" << endl;
square.showMatrix();
cout << endl;
}
else{
cout << "NOT Found !!" << endl;
square.showMatrix();
cout << endl;
}
}

cout << "Now you try! Enter " << SQUARE_SIZE << " values" << endl;

// Collect 3 values from the user and store them in an array called my_values
for(int i=0;i<SQUARE_SIZE;i++)
cin>>my_values[i];

// Call the set_matrix method and pass in the my_values array.
square.set_matrix(my_values);

// Display the new matrix using the showMatrix() method.
square.showMatrix();

// Copy the while loop above to search for more versions of this magic square.
if (square.is_magic())
cout << "\nIt is a magic square\n\n";
else {
cout << "Program is not working!!" << endl;
return 1;
}
times=20000; ///set to new value as currently times =0 and it will run in infinite loop
//times=15;
while (times--) {
square.scramble();
if (square.is_magic()) {
cout << "Found one !!" << endl;
square.showMatrix();
cout << endl;
}
else{
cout << "NOT Found !!" << endl;
square.showMatrix();
cout << endl;
}
}


return 0;

} // End main function

----------------------


Related Solutions

Program Assignment 1 C++ please Instructions This assignment will require the use of three arrays, which...
Program Assignment 1 C++ please Instructions This assignment will require the use of three arrays, which will be used in parallel. Create a program that keeps track of the sales of BBQ sauces for a company. The company makes several different types of sauces, Original, Sticky Sweet, Spicy, Sweet Heat, Hickory Bourbon and Smokey Mesquite. One array will contain the names of the different BBQ sauces. This array will be initialized from a text file with the 6 different names....
In this programming assignment, you will implement a SimpleWebGet program for non- interactive download of files...
In this programming assignment, you will implement a SimpleWebGet program for non- interactive download of files from the Internet. This program is very similar to wget utility in Unix/Linux environment.The synopsis of SimpleWebGet is: java SimpleWebGet URL. The URL could be either a valid link on the Internet, e.g., www.asu.edu/index.html, or gaia.cs.umass.edu/wireshark-labs/alice.txt or an invalid link, e.g., www.asu.edu/inde.html. ww.asu.edu/inde.html. The output of SimpleWebGet for valid links should be the same as wget utility in Linux, except the progress line highlighted...
Download and review the PrintNumbers.java program provided in the homework files. This program contains a method...
Download and review the PrintNumbers.java program provided in the homework files. This program contains a method which is designed to read in a number from the user and print it to the screen. The parameter to the method specifies whether the number might contain decimals. There are two helper methods- one that reads in an integer and one that reads in a double. Run the program. As written, it works as long as the user enters what they are supposed...
Objectives:  Write classes in C++  Use dynamic arrays  Write and read from files...
Objectives:  Write classes in C++  Use dynamic arrays  Write and read from files 1. WriteaclassGradeBookcontainingthefollowing: Private attributes: - courseName: a string representing the name of the course. - nbOfStudents: an integer representing the number of students enrolled in the course. The number of students is greater than or equal to 5. - grades: a double dimensional array of integers representing the grades of Test1, Test2 and Final of every student. It should be a dynamic array. Public...
Download this file to your hard drive and follow the instructions in the Module 9 Assignment...
Download this file to your hard drive and follow the instructions in the Module 9 Assignment (Word) document. Prepare two files for your post. The first file should be a text file containing your Python solution. The second file should contain your output file(txt). Complete the following using Python on a single text file and submit your code and your output as separate documents. For each problem create the necessary list objects and write code to perform the following examples:...
Skills needed to complete this assignment: dynamic arrays, classes. PROMPT: In mathematics, a polynomial is an...
Skills needed to complete this assignment: dynamic arrays, classes. PROMPT: In mathematics, a polynomial is an expression consisting of cariables and coefficients which involves only the operation of addition, subtraction, multiplication, and non-negative integer exponents of variables. A polynomial in a single variable can always be written in the form: anxn + an-1xn-1+ ....... + a2x2 + a1x + a0 Where a0 ....., an are coefficients and x is the variable. In this assignment, you will complete a polynomial class...
Assignment 1 – Writing a Linux Utility Program Instructions For this programming assignment you are going...
Assignment 1 – Writing a Linux Utility Program Instructions For this programming assignment you are going to implement a simple C version of the UNIX cat program called lolcat. The cat program allows you to display the contents of one or more text files. The lolcat program will only display one file. The correct usage of your program should be to execute it on the command line with a single command line argument consisting of the name you want to...
C++ please Instructions Download and modify the Lab5.cpp program. Currently the program will read the contents...
C++ please Instructions Download and modify the Lab5.cpp program. Currently the program will read the contents of a file and display each line in the file to the screen. It will also display the line number followed by a colon. You will need to change the program so that it only display 24 lines from the file and waits for the user to press the enter key to continue. Do not use the system(“pause”) statement. Download Source Lab 5 File:...
Download the following zip file Bag and complete the program. You will need to complete files...
Download the following zip file Bag and complete the program. You will need to complete files MyBag and . MyBag uses the java API class ArrayList as the underline data structure. Using the class variables given, complete the methods of the MyBag class. In your BagHand class you should set appropriate default values for select class variables in the constructor in the add method, use the MyBag object to add a PlayingCard type to the bag and find and set...
C++ Program - Arrays- Include the following header files in your program:     string, iomanip, iostream Suggestion:...
C++ Program - Arrays- Include the following header files in your program:     string, iomanip, iostream Suggestion: code steps 1 thru 4 then test then add requirement 5, then test, then add 6, then test etc. Add comments to display assignment //step 1., //step 2. etc. This program is to have no programmer created functions. Just do everything in main and make sure you comment each step so I can grade more easily. Also, this program will be expanded in Chapter...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT