when i put the code below in my solution and then debug it, a massage containing this "Unhandled exception at 0x0016ec86 in Q2.exe: 0xC0000005: Access violation reading location 0x00000000." come up on my screen.
i think it's due to "cout" but i don't know how to solve it
""code is written in "systemC" a library of c++""
#ifndef IF_classes
#define IF_classes
#include "systemc.h"
#include <iostream>
class put_if : virtual public sc_interface
{
public:
virtual void put(sc_lv<8>[16], int) = 0;
};
class get_if : virtual public sc_interface
{
public:
int d;
virtual void get(sc_lv<8>[16], int) = 0;
};
#endif
#include "IF_classes.h"
class router : public put_if, public get_if
{
bool full[4];
sc_lv<8> reg[4];
int rf;
sc_signal<bool> getD_ev[4], putD_ev[4], timeout_ev;
public:
router() {};
~router() {};
void put(sc_lv<8> data[16], int RF);
void get(sc_lv<8> data[16], int d);
};
#include "router.h"
void router::put(sc_lv<8> data[16], int RF)
{
rf = RF;
if (rf < 0) //////////////////////////Routing Field < 0
{
rf = abs(rf+1)%4;
for(int i = 0; i<= 15; i++)
{
if (full[rf] == true)
wait (getD_ev[rf].posedge());
reg[rf] = data[i];
full[rf] = true;
getD_ev[rf] = 0;
putD_ev[rf] = 1;
}
}
else if (rf == 0) ////////////////////Routing Field == 0
{
int i = 0;
while ( i < 16)
{
if (full[0] = false)
for(i = 0; i <= 15; i++)
{
if (full[0] == true)
wait (getD_ev[0].posedge());
reg[0] = data[i];
full[0] = true;
getD_ev[0] = 0;
putD_ev[0] = 1;
}
else if (full[1] = false)
for(i = 0; i <= 15; i++)
{
if (full[1] == true)
wait (getD_ev[1].posedge());
reg[1] = data[i];
full[1] = true;
getD_ev[1] = 0;
putD_ev[1] = 1;
}
else if (full[2] = false)
for(i = 0; i <= 15; i++)
{
if (full[2] == true)
wait (getD_ev[2].posedge());
reg[2] = data[i];
full[2] = true;
getD_ev[2] = 0;
putD_ev[2] = 1;
}
else if (full[3] = false)
for(i = 0; i <= 15; i++)
{
if (full[3] == true)
wait (getD_ev[3].posedge());
reg[3] = data[i];
full[3] = true;
getD_ev[3] = 0;
putD_ev[3] = 1;
}
}
}
else /////////////////////////////////Routing Field > 0
{
for(int j = 0; j < rf; j++)
{
if (full[0] = false)
for(int i = 0; i <= 15; i++)
{
if (full[0] == true)
wait (getD_ev[0].posedge());
reg[0] = data[i];
full[0] = true;
getD_ev[0] = 0;
putD_ev[0] = 1;
}
else if (full[1] = false)
for(int i = 0; i <= 15; i++)
{
if (full[1] == true)
wait (getD_ev[1].posedge());
reg[1] = data[i];
full[1] = true;
getD_ev[1] = 0;
putD_ev[1] = 1;
}
else if (full[2] = false)
for(int i = 0; i <= 15; i++)
{
if (full[2] == true)
wait (getD_ev[2].posedge());
reg[2] = data[i];
full[2] = true;
getD_ev[2] = 0;
putD_ev[2] = 1;
}
else if (full[3] = false)
for(int i = 0; i <= 15; i++)
{
if (full[3] == true)
wait (getD_ev[3].posedge());
reg[3] = data[i];
full[3] = true;
getD_ev[3] = 0;
putD_ev[3] = 1;
}
if (j = rf)
timeout_ev = 1;
}
}
}
void router :: get( sc_lv<8> data[16],int d)
{
for(int i = 0; i <= 15; i++)
{
if (full[d] == false)
wait (putD_ev[d].posedge());
data[i] = reg[d];
full[d] = false;
putD_ev[d] = 0;
getD_ev[d] = 1;
}
}
#ifndef transfer
#define transfer
#include "router.h"
SC_MODULE (source)
{
sc_port<put_if> out;
void putting();
SC_CTOR(source)
{
SC_THREAD(putting);
}
};
SC_MODULE (drain)
{
sc_port<get_if> in1, in2, in3, in4;
void getting();
SC_CTOR(drain)
{
SC_THREAD(getting);
}
};
#endif
#include "transfer.h"
void source :: putting()
{
sc_lv<8> to_put[16];
int routing_field;
for (int i = 0; i < 128 ; i++)
{
wait(2, SC_NS);
to_put[i%16] = (sc_lv<8>) i;
if (i%16 == 0 && i != 0)
{
routing_field = ((-1)^(i))*(rand()%4);
out->put(to_put, routing_field);
cout << "At: " << sc_time_stamp() << "\n" << to_put[0]
<< "\n" << to_put[1]
<< "\n" << to_put[2]
<< "\n" << to_put[3]
<< "\n" << to_put[4]
<< "\n" << to_put[5]
<< "\n" << to_put[6]
<< "\n" << to_put[7]
<< "\n" << to_put[8]
<< "\n" << to_put[9]
<< "\n" << to_put[10]
<< "\n" << to_put[11]
<< "\n" << to_put[12]
<< "\n" << to_put[13]
<< "\n" << to_put[14]
<< "\n" << to_put[15]
<< "\n" << " was transmitted to: rf" << routing_field+1 << ".\n";
}
}
}
void drain :: getting()
{
sc_lv<8> what_got[16];
for (int i = 0; i < 128; i++)
{
wait(2,SC_NS);
in1->get(what_got, 0);
in2->get(what_got, 1);
in3->get(what_got, 2);
in4->get(what_got, 3);
if (i%16 == 0 && i != 0)
{
cout << "At: " << sc_time_stamp() << "\n" << what_got[0]
<< "\n" << what_got[1]
<< "\n" << what_got[2]
<< "\n" << what_got[3]
<< "\n" << what_got[4]
<< "\n" << what_got[5]
<< "\n" << what_got[6]
<< "\n" << what_got[7]
<< "\n" << what_got[8]
<< "\n" << what_got[9]
<< "\n" << what_got[10]
<< "\n" << what_got[11]
<< "\n" << what_got[12]
<< "\n" << what_got[13]
<< "\n" << what_got[14]
<< "\n" << what_got[15]
<< "was recieved at: " << "\n";
}
}
}
#include "transfer.h"
SC_MODULE (transfer_tb)
{
router *rout;
source *S;
drain *D1, *D2, *D3, *D4;
SC_CTOR (transfer_tb)
{
//rout = new router();
S = new source("source");
S->out(*rout);
D1 = new drain("drain1");
D1->in1(*rout);
D2 = new drain("drain2");
D2->in2(*rout);
D3 = new drain("drain3");
D3->in3(*rout);
D4 = new drain("drain4");
D4->in4(*rout);
}
};
#include "transfer_tb.h"
int sc_main (int argc, char* argv[])
{
transfer_tb T_tb1("transfer_tb");
sc_start(1000, SC_NS);
return 0;
}
what_got is not being initialized.
Related
As the title states i'm having trouble finding the error with the way in which my queue is being populated. It should be holding every visited state node until they have been processed. but the queue is not being populated as it should be. Can anyone help me find the bug? Below is my implementation file for the PuzzleStateNode class and source.cpp
EDIT: After more debugging it would seem that the problem lies with the following chunk of code from the solvePuzzle function. The items are never pushed to my queue, and I don't understand why. Could it be an issue with my unordered_set?
void solvePuzzle(string stateArray[3][3]) {
ofstream oFile("output.txt");
PuzzleStateNode pState(stateArray);
queue<PuzzleStateNode> puzzleQueue;
unordered_set<string> visitedPuzzleStateSet;
if (pState.parityCheck() == true) {
puzzleQueue.push(pState);
for(int i = 0; i < 31; i++){
PuzzleStateNode myTempState(puzzleQueue.front());
//puzzleQueue.pop();
if (visitedPuzzleStateSet.find(myTempState.getPuzzleID()) == visitedPuzzleStateSet.end()) { // is our value in the set? if not then do the following
visitedPuzzleStateSet.emplace(myTempState.getPuzzleID()); // add to the list of visited states.
if (myTempState.getEmptyXArrayPos() == 0 || myTempState.getEmptyXArrayPos() == 1) { // if a move to the right is available
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareRight(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl << endl << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this already" << endl;
system("pause");
}
}
END EDIT:
PuzzleStateNode.h
#pragma once
#include<queue>
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
using namespace std;
class PuzzleStateNode
{
public:
PuzzleStateNode();
PuzzleStateNode(string tempArray[3][3]);
PuzzleStateNode(const PuzzleStateNode &other);
int getEmptyXArrayPos();
int getEmptyYArrayPos();
int getMoveCounter();
string getPuzzleID();
bool parityCheck();
bool checkForSolve();
void setPuzzleID();
void setEmptyXArrayPos(int x);
void setEmptyYArrayPos(int y);
void incrimentMoveCounter();
void pushToMoveQueue(string move);
void moveEmptySquareDown(int xEmptyPos, int yEmptyPos);
void moveEmptySquareUp(int xEmptyPos, int yEmptyPos);
void moveEmptySquareRight(int xEmptyPos, int yEmptyPos);
void moveEmptySquareLeft(int xEmptyPos, int yEmptyPos);
void printState(ofstream &oFile);
void printMoves(ofstream &oFile);
~PuzzleStateNode();
private:
string puzzleStateArray[3][3];
int moveCounter;
queue<string> moveQueue;
int emptyXArrayPos;
int emptyYArrayPos;
string puzzleID;
};
PuzzleStateNode.cpp
#include "PuzzleStateNode.h"
using namespace std;
PuzzleStateNode::PuzzleStateNode()
{
}
PuzzleStateNode::PuzzleStateNode(string tempArray[3][3])
{
puzzleID = "";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleStateArray[i][j] = tempArray[i][j];
puzzleID += tempArray[i][j];
if (puzzleStateArray[i][j] == "E") {
emptyXArrayPos = j;
emptyYArrayPos = i;
}
}
}
moveCounter = 0;
moveQueue.push("The following lists the movement of the Empty or 'E' square until the puzzle is solved: ");
}
PuzzleStateNode::PuzzleStateNode(const PuzzleStateNode &other) {
{ puzzleID = "";
moveCounter = other.moveCounter;
moveQueue = other.moveQueue;
emptyXArrayPos = other.emptyXArrayPos;
emptyYArrayPos = other.emptyYArrayPos;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleStateArray[i][j] = other.puzzleStateArray[i][j];
puzzleID += other.puzzleStateArray[i][j];
}
}
}
}
int PuzzleStateNode::getEmptyXArrayPos() {
return emptyXArrayPos;
}
int PuzzleStateNode::getEmptyYArrayPos() {
return emptyYArrayPos;
}
int PuzzleStateNode::getMoveCounter() {
return moveCounter;
}
string PuzzleStateNode::getPuzzleID() {
return puzzleID;
}
bool PuzzleStateNode::checkForSolve() {
if (puzzleStateArray[0][0] == "1" && puzzleStateArray[0][1] == "2" && puzzleStateArray[0][2] == "3" && puzzleStateArray[1][0] == "4" && puzzleStateArray[1][1] == "5" && puzzleStateArray[1][2] == "6" && puzzleStateArray[2][0] == "7" && puzzleStateArray[2][1] == "8" && puzzleStateArray[2][2] == "E") {
return true;
}
return false;
}
void PuzzleStateNode::setPuzzleID() {
puzzleID = "";
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
puzzleID += puzzleStateArray[i][j];
}
}
}
void PuzzleStateNode::setEmptyXArrayPos(int x) {
emptyXArrayPos = x;
}
void PuzzleStateNode::setEmptyYArrayPos(int y) {
emptyXArrayPos = y;
}
void PuzzleStateNode::incrimentMoveCounter() {
moveCounter++;
}
void PuzzleStateNode::pushToMoveQueue(string move) {
moveQueue.push(move);
}
void PuzzleStateNode::printMoves(ofstream &oFile) {
string tempString;
for (int i = 0; i < moveQueue.size(); i++) {
cout << moveQueue.front() << endl;
moveQueue.push(moveQueue.front());
moveQueue.pop();
}
cout << endl << endl;
}
void PuzzleStateNode::printState(ofstream &oFile) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << puzzleStateArray[i][j];
}
cout << endl;
}
cout << endl;
}
void PuzzleStateNode::moveEmptySquareDown(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos + 1][xEmptyPos];
puzzleStateArray[yEmptyPos + 1][xEmptyPos] = "E";
moveQueue.push("Down");
moveCounter++;
cout << "Moving Down" << endl;
emptyYArrayPos = yEmptyPos + 1;
}
void PuzzleStateNode::moveEmptySquareUp(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos - 1][xEmptyPos];
puzzleStateArray[yEmptyPos - 1][xEmptyPos] = "E";
moveQueue.push("Up");
moveCounter++;
cout << "Moving Up" << endl;
emptyYArrayPos = yEmptyPos - 1;
}
void PuzzleStateNode::moveEmptySquareLeft(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos][xEmptyPos - 1];
puzzleStateArray[yEmptyPos][xEmptyPos - 1] = "E";
moveQueue.push("Left");
moveCounter++;
cout << "Moving Left" << endl;
emptyXArrayPos = xEmptyPos - 1;
}
void PuzzleStateNode::moveEmptySquareRight(int xEmptyPos, int yEmptyPos) {
puzzleStateArray[yEmptyPos][xEmptyPos] = puzzleStateArray[yEmptyPos][xEmptyPos + 1];
puzzleStateArray[yEmptyPos][xEmptyPos + 1] = "E";
moveQueue.push("Right");
moveCounter++;
cout << "Moving Right" << endl;
emptyXArrayPos = xEmptyPos + 1;
}
bool PuzzleStateNode::parityCheck() // counts number of swaps for a bubble sort excluding swaps involving the empty space
{
enter code here
// Puzzles with odd swaps have odd parity and are unsolvable.
string parityCheckString = "";
char tempChar;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
parityCheckString += puzzleStateArray[i][j];
}
}
int counter = 0;
for (int j = 0; j < 8; j++) {
for (int i = 0; i < 8; i++) {
if (parityCheckString[i] > parityCheckString[i + 1]) {
if (parityCheckString[i] == 'E') {
tempChar = parityCheckString[i];
parityCheckString[i] = parityCheckString[i + 1];
parityCheckString[i + 1] = tempChar;
}
else {
tempChar = parityCheckString[i];
parityCheckString[i] = parityCheckString[i + 1];
parityCheckString[i + 1] = tempChar;
counter += 1;
}
}
}
}
if (counter % 2 == 0) {
cout << "Even Parity, solving the 8 puzzle!" << endl;
return true;
}
else {
cout << "Parity is odd and puzzle is unsolvable. Skipping to next Puzzle." << endl;
return false;
}
}
PuzzleStateNode::~PuzzleStateNode()
{
}
source.cpp
#include"PuzzleStateNode.h"
#include<string>
#include<fstream>
#include<iostream>
#include<unordered_set>
using namespace std;
int main() {
void solvePuzzle(string stateArray[3][3]);
ifstream inFile("input.txt");
ofstream outFile("output.txt");
string puzNum;
int numberOfPuzzles;
string junk;
getline(inFile, puzNum); // read number of puzzles
numberOfPuzzles = stoi(puzNum); // convert value to int.
for (int i = 0; i < numberOfPuzzles; i++) {
string stateArray[3][3]; // populates a temporary puzzle state.
string temp;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
while (temp != "1" && temp != "2" && temp != "3" && temp != "4" && temp != "5" && temp != "6" && temp != "7" && temp != "8" && temp != "E") {
temp = inFile.get();
}
stateArray[i][j] = temp;
temp = inFile.get();
}
}
solvePuzzle(stateArray);
}
system("pause");
return 0;
}
void solvePuzzle(string stateArray[3][3]) {
ofstream oFile("output.txt");
PuzzleStateNode pState(stateArray);
queue<PuzzleStateNode> puzzleQueue;
unordered_set<string> visitedPuzzleStateSet;
if (pState.parityCheck() == true) {
puzzleQueue.push(pState);
for(int i = 0; i < 31; i++){
PuzzleStateNode myTempState(puzzleQueue.front());
//puzzleQueue.pop();
if (visitedPuzzleStateSet.find(myTempState.getPuzzleID()) == visitedPuzzleStateSet.end()) { // is our value in the set? if not then do the following
visitedPuzzleStateSet.emplace(myTempState.getPuzzleID()); // add to the list of visited states.
if (myTempState.getEmptyXArrayPos() == 0 || myTempState.getEmptyXArrayPos() == 1) { // if a move to the right is available
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareRight(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl << endl << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this already" << endl;
system("pause");
}
}
if (myTempState.getEmptyXArrayPos() == 1 || myTempState.getEmptyXArrayPos() == 2) {
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareLeft(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
tempState.incrimentMoveCounter();
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have visited this state" << endl;
system("pause");
}
}
if (myTempState.getEmptyYArrayPos() == 0 || myTempState.getEmptyYArrayPos() == 1) {
PuzzleStateNode tempState;
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareDown(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "you have this state already" << endl;
system("pause");
}
}
if (myTempState.getEmptyYArrayPos() == 1 || myTempState.getEmptyYArrayPos() == 2) {
PuzzleStateNode tempState(myTempState);
tempState = PuzzleStateNode(myTempState);
tempState.moveEmptySquareUp(tempState.getEmptyXArrayPos(), tempState.getEmptyYArrayPos());
if (tempState.checkForSolve() == true) {
tempState.printState(oFile);
oFile << "Puzzle Solved in " << tempState.getMoveCounter() << " movements of the emtpy tile which are listed below." << endl;
tempState.printMoves(oFile);
cout << "Puzzle Solved!" << endl;
oFile.close();
return;
}
else if (tempState.checkForSolve() != true && visitedPuzzleStateSet.find(tempState.getPuzzleID()) == visitedPuzzleStateSet.end()) {
puzzleQueue.push(tempState);
}
else {
cout << "have visited this state already" << endl;
system("pause");
}
}
}
}
}
else
oFile.close();
return;
}
I found the problem! I was never resetting puzzle id's after copying so all puzzle states had the same ID for my set.
I'm trying to get this code to sort names but it doesn't seem to work for me. What could be wrong? I have a class named Student and want to pass the names and sort them in ascending order. So what I am trying to do is pass the 4 object firstname onto the the sort_list function and sort them in ascending order and display them afterwards. However when I run the code it shows me the same order I had and the sort function didn't seem to have done anything. See if you guys can help me out here.
#include <iostream>
#include<string>
using namespace std;
//***************************************************************************
//STUDENT CLASS
//***************************************************************************
class Student
{
private:
string firstname;
string lastname;
string studentID;
string phoneNumber;
double gpa;
public:
Student();
Student(const string&, const string&, const string&, const string&, const double&);
string getfirstName() const;
string getlastName() const;
string getstudentId() const;
string getphoneNumber() const;
double getGPA() const;
void setfirstName(string&);
void setlastName(string&);
void setstudentId(string&);
void setphoneNumber(string&);
void setGAP(double&);
};
Student::Student()
{
firstname = " ";
lastname = " ";
studentID = " ";
phoneNumber = " ";
gpa = 0;
}
Student::Student(const string&a, const string&b, const string&c, const string&d, const double&e)
{
firstname = a;
lastname = b;
studentID = c;
phoneNumber = d;
gpa = e;
}
string Student::getfirstName()const
{
return firstname;
}
string Student::getlastName()const
{
return lastname;
}
string Student::getstudentId() const
{
return studentID;
}
string Student::getphoneNumber() const
{
return phoneNumber;
}
double Student::getGPA() const
{
return gpa;
}
void Student::setfirstName(string&u)
{
firstname = u;
}
void Student::setlastName(string&v)
{
lastname = v;
}
void Student::setstudentId(string&x)
{
studentID = x;
}
void Student::setphoneNumber(string&y)
{
phoneNumber = y;
}
void Student::setGAP(double&z)
{
gpa = z;
}
//***************************************************************************
//COURSE CLASS
//***************************************************************************
class Course :public Student
{
private:
string code;
int section;
int capacity;
int numStudents;
Student *list;
public:
Course();
Course(string, int, int);
~Course();
string getCourseCode();
int getSection();
int getCapacity();
int getNumStudents();
void setCourseCode(string);
void setSection(int);
void add(const Student&);
void display();
void display(const string, const int);
void remove(const string m, const int n);
void sort_list();
};
Course::Course()
{
code = "CMPT1020";
section = 1;
capacity = 35;
numStudents = 0;
list = new Student[35];
}
Course::Course(string a, int b, int c)
{
code = a;
section = b;
capacity = c;
numStudents = 0;
list = new Student[c];
}
Course::~Course()
{
delete[] list;
list = nullptr;
}
string Course::getCourseCode()
{
return code;
}
int Course::getSection()
{
return section;
}
int Course::getCapacity()
{
return capacity;
}
int Course::getNumStudents()
{
return numStudents;
}
void Course::setCourseCode(string a)
{
code = a;
}
void Course::setSection(int b)
{
section = b;
}
void Course::add(const Student& s)
{
if (numStudents == capacity)
{
cout << "Course is full" << endl;
return;
}
list[numStudents] = s;
numStudents++;
int i = numStudents - 2;
while (i >= 0 && (s.getGPA() > list[i].getGPA()))
{
list[i + 1] = list[i];
i--;
}
list[i + 1] = s;
}
void Course::display()
{
for (int i = 0; i < numStudents; i++)
{
cout<<list[i].getfirstName() <<" "<< list[i].getlastName() <<" "<< list[i].getstudentId() <<" "<< list[i].getphoneNumber() <<" "<< list[i].getGPA() << endl;
}
}
void Course::display(const string x, const int y)
{
if (y == 1)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getfirstName() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 2)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getlastName() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 3)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getstudentId() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
if (y == 4)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getphoneNumber() == x)
{
cout << list[i].getfirstName() << " " << list[i].getlastName() << " " << list[i].getstudentId() << " " << list[i].getphoneNumber() << " " << list[i].getGPA() << endl;
}
}
}
}
void Course::remove(const string a, const int b)
{
if (b == 1)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getfirstName() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 2)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getlastName() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 3)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getstudentId() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
if (b == 4)
{
for (int i = 0; i < numStudents; i++)
{
if (list[i].getphoneNumber() == a)
{
for (int j = i; j < numStudents; j++)
{
list[j] = list[j + 1];
}
numStudents--;
}
}
}
}
void Course::sort_list()
{
string temp;
for (int i = 0; i < numStudents; i++)
{
for (int j = 0; j < numStudents-1; j++)
{
if(list[j].getfirstName() >list[j+1].getfirstName())
{
temp = list[j].getfirstName();
list[j].getfirstName() = list[j+1].getfirstName();
list[j+1].getfirstName() = temp;
}
}
}
}
int main()
{
Student a("Kevin", "Chen", "300215915", "7788408028", 2);
Student b("Mickey", "Mouse", "12345678", "2222222222", 2.5);
Student c("Donald", "Duck", "24681012", "3333333333", 3.0);
Student d("Goofy", "Dog", "3579111315", "5555555555", 3.5);
Course x;
x.add(a);
x.add(b);
x.add(c);
x.add(d);
x.display();
cout << endl;
x.sort_list();
x.display();
/*cout << " " << endl;
x.remove("kevin", 1);
x.remove("Chen", 2);
x.remove("300215915", 3);
x.remove("7788408028", 4);
x.display();
cout << endl;
x.display("kevin", 1);
x.display("Mouse", 2);
x.display("24681012", 3);
x.display("5555555555", 4);*/
system("pause");
return 0;
}
It is true that your sorting code doesn't do anything.
Here is the core of it:
temp = list[j].getfirstName();
list[j].getfirstName() = list[j+1].getfirstName();
list[j+1].getfirstName() = temp;
getfirstName() returns the first name by value so all your assignments are doing is swapping temporary copies of the first names. There is no effect on the actual list elements.
I think you meant:
temp = list[j];
list[j] = list[j+1];
list[j+1] = temp;
This also means temp must be declared as a Student, not a std::string.
Also, unless I'm misremembering how Bubble Sort works (which is certainly possible — given its uselessness in the real world, it's been a long time since I've written one), your outer loop needs as many iterations as it takes for the inner loop not to be doing any swaps any more. If that's somehow inherently capped at numStudents iterations, I can't see why, nor see any evidence of it on the Wikipedia article.
Assuming I am on the right lines with that, I'd have the function looking like this:
void Course::sort_list()
{
bool go_again = false;
do {
go_again = false;
for (int i = 0; i < numStudents-1; i++) {
if (list[i].getfirstName() > list[i+1].getfirstName()) {
Student temp = list[i];
list[i] = list[i+1];
list[i+1] = temp;
go_again = true;
}
}
} while(go_again);
}
(live demo)
Ok, so I was doing a tiny project for school and I can't find the answer anywhere to why this small change in code makes it finish in no time when number m gets higher. Look at the variable "k" I change it from int to long.
I'm trying to find the longest sequence in the Collatz sequence between 1 and 1000000
void lengstaRuna() {
cout << "Hæsta tala?:";
int m;
cin >> m;
int lengstaRuna = 0;
int talaLengstuRunu = 0;
int k;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
void lengstaRuna() {
cout << "Hæsta tala?:";
int m;
cin >> m;
int lengstaRuna = 0;
int talaLengstuRunu = 0;
long k;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
The question is simple: Why does it run so much faster when input m==1000000?
I see what's happening here. Basically, above certain value for your input, the int is overflowing since you are doing k*3.
I modified your code to check this (see below). Upto input value of around 113000, the max your 'k' has to hold is 1570824735 (close to INT_MAX 2147483647). Anything 114000 or above, 'k' overflows and the code goes into uncharted territory. That problem doesn't happen when you use long of course.
./a.out 113000
j: 1570824735
Lengsta runa: 354
Tala lengstu runu: 106239
#include <iostream>
#include <string>
using namespace std;
void lengstaRuna(int m) {
int lengstaRuna = 0;
int talaLengstuRunu = 0;
int k;
long j = 0;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
if (k*3 > j)
j = k*3;
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "j: " << j << endl;
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
int main (int ac, char** av) {
std::string::size_type sz;
lengstaRuna(std::stoi(av[1]));
}
Can someone please help me. I am struggling to find in my code why the last value in column B always gets incremented by one. I have written some code since its an assignment due today. I also cant figure out why the last value in column B is not equal to 196 because in the reset function it sets all the values in the array to 196 . Any suggestion would be appreciated. Thank you in advance
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main() { //main starts
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats) {
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++) {
if (i == 0) {
cout << " " << static_cast<char>(j + 65) << " ";
} else {
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]) {
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++) {
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++) {
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats) {
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS))) {
if (seats[(seatChoiceNumber)][(letter - 65)] == 82) {
} else {
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats) {
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats) {
printAllSeats(seats);
anyFreeSeats = false;
}
}
} else {
}
}
I kind of cleaned up the code a bit. It seems you found your answer in the comments, so I just did some indentation. Try and eliminate whitespaces in your code (mind you, the one I am putting here is not perfect either, but you get the point). Clean and easy to read code doesn't only make it better for you, but as you get higher up in the industry and other people begin reading and working on your code, having clean and easy to read code really helps :)
#include <iostream> //includes cin cout
#include <iomanip>
using namespace std; //setting up the environment
const int NUMBER_OF_ROWS = 3;
const int NUMBER_OF_COLUMNS = 3;
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats);
bool isFull(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
bool isEmpty(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS]);
int main()
{
int maxSeats;
int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
int SeatCountNumber = 0;
bool anyFreeSeats;
reset(seats);
anyFreeSeats = true;
SeatCountNumber = 0;
while (anyFreeSeats)
{
printAllSeats(seats);
askForUsersSeat(seats, SeatCountNumber, anyFreeSeats);
}
system("pause");
return 0;
} //main ends
void printAllSeats(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
cout << endl;
cout << setw(10) << " - = Available R = Reserved\n\n";
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
cout << setw(15) << i << " ";
for (int j = 0; j < NUMBER_OF_COLUMNS; j++)
{
if (i == 0)
{
cout << " " << static_cast<char>(j + 65) << " ";
}
else
{
cout << " " << static_cast<char>(seats[i][j]) << " ";
}
}
cout << endl;
}
cout << endl;
}
void reset(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS])
{
//set all values in array to 196
for (int i = 0; i <= NUMBER_OF_ROWS; i++)
{
for (int j = 0; j <= NUMBER_OF_COLUMNS; j++)
{
seats[i][j] = 196;
}
}
}
void askForUsersSeat(int seats[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS], int &SeatCountNumber, bool &anyFreeSeats)
{
int seatChoiceNumber;
char seatChoiceLetter;
int letter;
int maxSeats = NUMBER_OF_ROWS * NUMBER_OF_COLUMNS;
cout << "Seat (Row, Column): ";
cin >> seatChoiceNumber >> seatChoiceLetter;
letter = static_cast<int>(toupper(seatChoiceLetter));
if (((letter >= 65) && (letter < (65 + NUMBER_OF_COLUMNS))) && ((seatChoiceNumber > 0) && (seatChoiceNumber <= NUMBER_OF_ROWS)))
{
if (seats[(seatChoiceNumber)][(letter - 65)] == 82)
{
}
else
{
seats[(seatChoiceNumber)][(letter - 65)] = 82;
SeatCountNumber++; //this changes last value in column B for some reason
if (SeatCountNumber < maxSeats)
{
anyFreeSeats = true;
}
else if (SeatCountNumber > maxSeats)
{
printAllSeats(seats);
anyFreeSeats = false;
}
}
}
else {
}
}
Note: Some more whitespaces could even come out but I generally like to have spaces after certain statements (personal preference).
When I execute this code in Code::Blocks I get a segmentation fault. Why? I've used debug and haven't found why. Any help is useful.
The debugger showed it was from the vector push_back method, but specifically on the "this" pointer used in the copy constructor.
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <cmath>
const int MAX_COL = 7, MAX_ROW = 6;
const int NOPLAYER = 0, PLAYER1 = 1, PLAYER2 = 2;
const int NOTHING = 123;
int movesBeingStored = 0;
int movesCreated = 0;
class Move{
public:
Move() : row(-1), col(-1), plr(-1) {
//std::cout << "Placed #" << col << "," << row << std::endl;
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
};
Move(int r, int c, int p) : row(r), col(c), plr(p) {
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
};
~Move() {
--movesBeingStored;
std::cout << "-Now " << movesBeingStored << " move(s)" << std::endl;
};
int getRow() const { return row; }
int getCol() const { return col; }
int getPlayer() const { return plr; }
Move(const Move* other) {
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
col = other->getCol();
row = other->getRow();
plr = other->getPlayer();
}
Move(const Move& other) {
++movesBeingStored;
++movesCreated;
std::cout << "+Now " << movesBeingStored << " move(s), Created " << movesCreated << std::endl;
col = other.getCol(); //This line causes a segment fault
row = other.getRow();
plr = other.getPlayer();
}
bool operator== (const Move& other) const {
return (&other == this);
}
private:
int row, col, plr;
};
int board[MAX_COL * MAX_ROW];
std::vector<Move> moves;
bool isFull[MAX_COL];
int tops[MAX_COL];
int currentPlayer = PLAYER1;
int checkedCollumns = 0;
void randomize( void ) { srand(time(NULL)); }
void startBoard( void );
void placeMove(int col, int player);
void popMove();
int checkwin(int curPlayer);
int checkMove(int depth, int& bestCol, int curP, int checkP);
int randomInt(int min, int max);
void printMoves( void );
int main()
{
startBoard();
randomize();
int col = -1;
int pts = checkMove(2, col, PLAYER1, PLAYER1);
if(col == -1) {
std::cout << "No best move" << std::endl;
} else {
std::cout << "Best move: Col " << col << std::endl;
if(pts == NOTHING) {
std::cout << "Nothing happens" << std::endl;
} else {
std::cout << "Gives " << pts << " points" << std::endl;
}
}
}
void startBoard( void ) {
for(int i = 0; i < MAX_COL; ++i) {
isFull[i] = false;
tops[i] = 0;
}
for(int p = 0; p < MAX_COL * MAX_ROW; ++p) {
board[p] = NOPLAYER;
}
}
void placeMove(int col, int player) {
if(col < 0 || col >= MAX_COL)
return;
if(isFull[col])
return;
if(player != PLAYER1 && player != PLAYER2)
player = PLAYER1;
moves.push_back(Move(col, tops[col], player));
board[col + tops[col] * MAX_COL] = player;
++tops[col];
isFull[col] = (tops[col] == MAX_ROW);
}
void popMove() {
if(moves.empty())
return;
Move move = moves.back();
moves.pop_back();
int col = move.getCol(), row = move.getRow();
board[col + row * MAX_COL] = NOPLAYER;
tops[col] = row;
isFull[col] = (tops[col] == MAX_ROW);
}
int checkwin(int curPlayer) {
if(randomInt(0,5) != 1)
return NOTHING;
return randomInt(0,4);
}
int checkMove(int depth, int& bestCol, int curP, int checkP) {
int pts = NOTHING, col = -1, p = NOTHING, c = -1;
if(depth <= 0) {
if(moves.empty()) {
bestCol = -1;
return NOTHING;
}
Move move = moves.back();
bestCol = move.getCol();
pts = checkwin((move.getPlayer());
if(move.getPlayer() != checkP && pts != NOTHING)
pts = -pts;
return pts;
}
for(int i = 0; i < MAX_COL; ++i) {
std::cout << "C: " << checkedCollumns;
std::cout << "\tD: " << depth;
std::cout << "\tM: " << moves.size();
std::cout << std::endl;
if(isFull[i])
continue;
++checkedCollumns;
placeMove(i, curP);
p = checkMove(depth - 1, c, ((curP == PLAYER1)?PLAYER2:PLAYER1), checkP);
popMove();
if(p != NOTHING && checkP != curP)
p = -p;
if(col == -1) {
col = i;
pts = p;
continue;
}
if(pts == NOTHING && p != NOTHING && p >= 0) {
col = i;
pts = p;
continue;
}
if(pts != NOTHING && p != NOTHING && p > pts) {
col = i;
pts = p;
}
}
bestCol = col;
return pts;
}
int randomInt(int min, int max) {
double per = (double)(rand() % RAND_MAX) / RAND_MAX;
return min + (max - min) * per;
}
void printMoves( void ) {
std::cout << "M:";
if(moves.empty()) {
std::cout << " --\t" << moves.size();
return;
}
Move m;
for(unsigned int i = 0; i < moves.size(); ++i) {
m = moves.at(i);
std::cout << " {" << m.getCol() << "," << m.getRow() << "}";
}
std::cout << "\t" << moves.size();
}
A very trivial error, manifesting in a very obscure way. The segment fault is caused by the vector trying to construct an object at an invalid location. Why? Because of the following line in void popMove():
board[col + row * MAX_COL] = NOPLAYER;
This line has a buffer overflow caused by invalid coordinates (0, 6), which overwrites the internal memory pointer in moves. That's the problem, the solution is up to you.