Monty Hall Project - c++

I am currently in the process of writing a C++ Monty Hall Problem Simulation and have run into some trouble. The error I keep getting is:
source.cpp(23): error C4700: uninitialized local variable 'doorReveal' used
source.cpp(25): error C4700: uninitialized local variable 'doorSwitch' used
source.cpp(52): error C4700: uninitialized local variable 'stayWin' used
source.cpp(56): error C4700: uninitialized local variable 'switchWin' used
I can't seem to figure out what is wrong. The project is supposed to simulate the wins by first staying with the original door choice on the first 100 tries and then switching when door is revealed on the next 100 tries. Thank you all for your help in advance.
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
int doorChoice;
int prizeDoor;
int doorReveal;
int doorSwitch;
int count;
int switchWin;
int stayWin;
srand((unsigned int) time(0));
for (count = 0; count <= 200; count++)
{
prizeDoor = (rand() % 3) + 1;
doorChoice = (rand() % 3) + 1;
cout << "The prize door is door number " << prizeDoor << " ." << endl;
cout << "The door the contestant chose was door " << doorChoice << endl;
doorReveal != prizeDoor || doorChoice;
cout << "The host revealed door number " << doorReveal << " ." << endl;
doorSwitch != doorChoice || doorReveal;
while (count < 101)
{
if (doorChoice == prizeDoor)
{
cout << "Great Job! You won!" << endl;
}
else {
cout << "Not this time!" << endl;
}
}
while (count < 201)
{
if (doorSwitch == prizeDoor)
{
cout << "You switched and won!" << endl;
}
else {
cout << "You switched and lost!" << endl;
}
}
if (doorChoice == prizeDoor)
{
stayWin++;
}
if (doorSwitch == prizeDoor)
{
switchWin++;
}
count++;
}
cout << "Your win percentage when staying was " << stayWin << "%!" << endl;
cout << "Your win percentage when switching was " << switchWin << "%!" << endl;
return 0;
}

Problem 1: operator!=
operator != doesn't do what you think it does.
Did you mean
doorReveal = !(prizeDoor || doorChoice);
cout << "The host revealed door number " << doorReveal << " ." << endl;
doorSwitch = (doorChoice || doorReveal);
I sense another logic issue in determining the doorReveal. I'll have to think about that later.Edit: see problem 5
Problem 2: while
There's also a problem with the while loops:
while(count < 101)
// ...
while(count < 201)
They're infinite loops, because count isn't increased during the loop. I think you meant if there, instead of while.
Problem 3: Initiliazing switchWin and stayWin
These variables are only being incremented. Like #KonradRudolph suggested,
declare your variables where they are first needed
initialize them
while you're at it, mark them const as appropriate
Problem 4: rand()%3 is biased
You should probably use a uniform distribution.
See
http://eternallyconfuzzled.com/arts/jsw_art_rand.aspx
I'll leave using std::uniform_int_distribution as an exercise for the reader here, as it is likely beyond the scope of your course. Remember to use it though, in any real life code.
Problem 5: Fix your door 'derivation'
Booleans aren't sets. Even if they were, you'd be stuck to binary sets. I propose the following model:
enum doors { door1 = 1, door2 = 2, door3 = 4, any = door1|door2|door3 };
so you can say:
doors const doorReveal = doors(~(prizeDoor | doorChoice) & any);
doors const doorSwitch = doors(~(doorChoice | doorReveal) & any);
Fixing that results in a program that appears to work:
#include <iostream>
#include <time.h>
using namespace std;
enum doors { door1 = 1, door2 = 2, door3 = 4, any = door1|door2|door3 };
static inline std::ostream& operator<<(std::ostream& os, doors val) {
switch(val) {
case door1: return os << "door #1";
case door2: return os << "door #2";
case door3: return os << "door #3";
case any: return os << "any door";
}
return os << "OOPS";
}
int main()
{
unsigned switchWin = 0;
unsigned stayWin = 0;
srand((unsigned int) time(0));
for(int count = 0; count <= 200; count++)
{
doors const prizeDoor = doors(1 << rand() / ( RAND_MAX / 3 ));
doors const doorChoice = doors(1 << rand() / ( RAND_MAX / 3 ));
cout << "The prize door is door number " << prizeDoor << " ." << endl;
cout << "The door the contestant chose was door " << doorChoice << endl;
doors const doorReveal = doors(~(prizeDoor | doorChoice) & any);
doors const doorSwitch = doors(~(doorChoice | doorReveal) & any);
cout << "The host revealed door number " << doorReveal << " ." << endl;
if(count < 101)
{
if(doorChoice == prizeDoor)
{
cout << "Great Job! You won!" << endl;
}
else
{
cout << "Not this time!" << endl;
}
};
if(count < 201)
{
if(doorSwitch == prizeDoor)
{
cout << "You switched and won!" << endl;
}
else
{
cout << "You switched and lost!" << endl;
}
};
if(doorChoice == prizeDoor)
{
stayWin++;
}
if(doorSwitch == prizeDoor)
{
switchWin++;
};
count++;
}
cout << "Your win percentage when staying was " << stayWin << "%!" << endl;
cout << "Your win percentage when switching was " << switchWin << "%!" << endl;
return 0;
}

Related

Console game not working properly

I am making a simple game for learning purposes mostly and I recently ran into this problem. Keep in mind that I'm still a huge beginner. When I go into the game from the menu and write anything in the "Command Line" I instantly starve and dehydrate. I haven't been able to connect to the internet for a couple of days and I've read through the entire program but I can't find anything wrong.
menu.h
#include <iostream>
#include <stdlib.h>
#include <string>
#include <time.h>
#include <dos.h>
#include <windows.h>
#include <WinBase.h>
//-------------//
#include "tutorial.h"
#include "game.h"
void menu() {
std::cout << "-------MENU------- \n";
std::cout << " 1.Play \n";
std::cout << " 2.Tutorial \n";
std::cout << " 3.Exit \n";
std::cout << " \n";
std::cout << " \n";
std::cout << " \n";
std::cout << "Choose Option: ";
int menuOption;
std::cin >> menuOption;
int menuLoop = 0;
while (menuLoop != 1) {
if (menuOption == 1) {
menuLoop = 1;
play();
}
if (menuOption == 2) {
menuLoop = 1;
system("CLS");
tutorial();
}
if (menuOption == 3) {
menuLoop = 1;
std::cout << "Bye!";
Sleep(1000);
}
if (menuOption > 3)
std::cout << "\"" << menuOption << "\"" << " is not a valid option.\n";
}
}
game.h
#include <iostream>
#include <string>
#include <windows.h>
#include <WinBase.h>
//initiating functions
void step();
void run();
void theme();
void starve();
void die();
void dehydrate();
void b();
//globals
std::string name;
std::string commandLine;
int onRoad = 1; // 1 = True, 0 = False
int steps = 0;
double hunger = 0.0;
double thirst = 0.0;
int energy = 5;
void play() {
system("CLS");
std::cout << "Enter your name: \n";
std::cin >> name;
system("CLS");
theme();
Sleep(350);
std::cout << " " << name << "'s Roadtrip\n";
std::cout << "Type \"/help\" for help\n";
std::cout << "---------Command Line---------\n";
std::cin >> commandLine;
while (onRoad != 0){
//------------------Conditions start------------------
// Hunger Conditions
if (hunger = 0){
if (hunger < 0){
std::cout << "You can't eat that, you're not hungry.\n";
b();
}
}
if (hunger > 100){
hunger = 100;
}
if (hunger < 0){
hunger = 0;
}
if (hunger = 100){
starve();
}
else if (hunger > 96){
std::cout << "You're extremely hungry! If you don't eat something quick you're going to die!\n";
b();
}
else if (hunger > 90) {
std::cout << "You're very hungry.\n";
b();
}
else if (hunger > 80) {
std::cout << "You're hungry.\n";
b();
}
// Thirst Conditions
if (thirst = 0){
if (thirst < 0){
std::cout << "You can't drink that, you're not thirsty.\n";
}
}
if (thirst < 0){
thirst = 0;
}
if (thirst > 100) {
thirst = 100;
}
if (thirst = 100){
dehydrate();
}
else if (thirst > 90){
std::cout << "You're extremely thirsty! If you don't drink something quick you're going to die!\n";
b();
}
else if (thirst > 75) {
std::cout << "You're very thirsty.\n";
b();
}
else if (thirst > 50){
std::cout << "You're thirsty.\n";
b();
}
//Energy Conditions
if (energy > 10){
energy = 10;
}
if (energy < 0){
energy = 0;
}
//-------------------Conditions end-------------------
if (commandLine == "/commands"){
std::cout << "-Command- -Action-\n";
std::cout << " /help Displays this menu.\n";
std::cout << " /commands Displays list of commands.\n";
std::cout << " /step Take a step and display total amount of steps.\n";
std::cout << " /run Take 5 steps and consume 5 energy.\n";
std::cout << " Doesn't increase hunger or thirst.\n";
std::cout << " /inventory Displays inventory.\n";
std::cout << " /info Displays stats.\n";
b();
}
if (commandLine == "/step") {
step();
b();
}
if (commandLine == "/info") {
std::cout << name << "'s stats\n";
std::cout << "Hunger: " << hunger << std::endl;
std::cout << "Thirst: " << thirst << std::endl;
std::cout << "Energy: " << energy << std::endl;
b();
}
else {
std::cout << commandLine << " is not a valid command. Type /commands to display commands.\n";
b();
}
}
}
void step(){
steps += 1;
std::cout << steps;
hunger += 5;
thirst += 5;
}
void run() {
steps += 5;
std::cout << steps;
}
void starve(){
std::cout << "You starved to death!\n";
die();
}
void dehydrate(){
std::cout << "You dehydrated!\n";
die();
}
void die(){
std::cout << "Steps taken: " << steps << std::endl;
onRoad = 0;
}
void theme(){
Beep(600, 200);
Beep(500, 200);
Beep(800, 400);
}
// b takes you back to the command line
void b(){
std::cin >> commandLine;
}
main.cpp
#include <iostream>
#include "menu.h"
#include <WinBase.h>
#include <windows.h>
int main(){
menu();
system("PAUSE");
return 0;
}
**EDIT: ** Pic: http://i.imgur.com/yu1V1pq.png (need 10 rep to post picture)
This is really weird. I entered /step and it worked, and then i entered /run and it also worked. I don't understand...
Some of your if statements do assignment instead of comparison
if (hunger = 100){
starve();
}
You probably need to change = to ==
Enable warnings while compiling, if you have not already done so.
Because
// b takes you back to the command line
void b(){
std::cin >> commandLine;
}
b doesn't take you back to the command line just wait for a character to be read and then it returns. If you want to go back, you should follow the way you came from. For example exiting play will return you to the menu loop, obviously with menuLoop = 1 so it will exit the whole program but with modifications this is not a bad looping system.
Edit: I've seen what you do mean in the "command line".
Like others said, you have a load of conditions accidentally spelled as assignments.
Also, indeed, the b() function is eating subsequent commands.
Maybe you should
use std::getline() to read a command one line at a time
or use std::cin.ignore() inside b() to actually consume until the end of the line
PS. Due to the use of globals I have a hard time verifying the game loop logic. I just know that /step after /step gets ignored without effect right now. Separate your input from the loop control and try to remove the global variables.
INFO
Instead of writing std::cout every single time you can just write using namespace std; on the beginning after that you dont need to write std::cout just write cout << "" ;

fread hanging, C++ with pipes

I'm writing a tictactoe application which communicates between a server and client file. Currently, my program hangs when trying to read in the players move. The client is showing successful write to the pipe but the server is not reading the information. Any help would be appreciated. Heres the offending code from both portions. Edit: I just realized the formatting got completely buggered in the copy/paste, I am sorry.
client main() :
//used to define int holder for server read in
const int MAX = 2;
//used to define buffers to transfer information
const int BUFFERS = 10;
//path of the global pipe
const string PRIMARY = "/home/mking/GPipe";
int main() {
//variables
size_t result;
srand(time(NULL) );
int s = rand() % 10000;
if (s < 1000) { s += 1000; }
cout << s << endl;
string userWrite = "/temp/" + to_string(s);
s = rand() % 10000;
if (s < 1000) { s += 1000; }
cout << s << endl;
string serverWrite = "/temp/" + to_string(s);
cout << PRIMARY << endl;
cout << "User pipe is " << userWrite << endl;
cout << "Server pipe is " << serverWrite << endl;
// send personal pipe information through global pipe to server
FILE * comms = fopen(PRIMARY.c_str(), "w");
cout << "Comms open" << endl;
result = fwrite(userWrite.c_str(), 1, userWrite.length(), comms);
if (result < userWrite.length()) { cout << endl << endl << endl << endl << endl << "write error, userfifo" << endl; }
result = fwrite(serverWrite.c_str(), 1, serverWrite.length(), comms);
if (result < userWrite.length()) { cout << endl << endl << endl << endl << endl << "write error, serverfifo" << endl; }
cout << "Comms written to" << endl;
//done with comms so close it
fclose(comms);
// for some reason sending /tmp/ caused a hang also, so i improvised
userWrite.erase(2,1);
serverWrite.erase(2,1);
// make the personal pipes
cout << userWrite << " " << serverWrite << endl;
mkfifo(userWrite.c_str(), 0777);
mkfifo(serverWrite.c_str(), 0777);
// open the personal pipes with read or write privelege
cout << "fifos made" << endl;
FILE * pwrite = fopen(userWrite.c_str(), "w");
cout << "pwrite open" << endl;
FILE * pread = fopen(serverWrite.c_str(), "r");
cout << "pread open" << endl;
// if either pipe did not get made correctly, print an error
if (pwrite == NULL ) { cout << "pwrite is wrong" << endl; }
if (pread == NULL ) { cout << "pread is wrong" << endl; }
// used to transfer information between pipes
string buffer = "/temp/0000";
string catcher = "/temp/0000";
// initialize curses functions
initscr();
noecho();
keypad(stdscr,TRUE);
cbreak();
WINDOW * screen = newwin(LINES/2, COLS/2, 0, 0);
wclear(screen);
keypad(screen,TRUE);
//wait for input before playing the game
int c = getch();
displayOpening(screen);
c = getch();
//initialize the game data types
int row = 0;
int column = 0;
vector<pair<int, int> > userMoves;
vector<pair<int,int> > serverMoves;
int charInt[MAX];
bool invalid = 0;
//until game is over or user exits
while (1) {
// update the board
displayBoard(screen,userMoves,serverMoves, row, column, invalid);
// based on user input, do stuff, supports wsad or arrow keys
switch(c = getch() ) {
// if go up, move up a row or go back to bottom if at top
case KEY_UP:
case 'w':
if (row == 0) { row = 2; }
else { row--; }
break;
// if go down, move down a row or go back to the top if at bottom
case KEY_DOWN:
case 's':
if (row == 2) { row = 0; }
else { row++; }
break;
// if go left, move left a column or go back to the far right if at far left
case KEY_LEFT:
case 'a':
if (column == 0) { column = 2; }
else { column--; }
break;
// if go right, move right a column or go back to the far left if at far right
case KEY_RIGHT:
case 'd':
if (column == 2) { column = 0; }
else { column++; }
break;
// if spacebar is pressed, enter move if valid, otherwise tell invalid and get more input
case ' ':
if (checkX(row, column, userMoves, serverMoves)) {
invalid = 0;
// no longer used function, thought maybe was the issue
//addX(row,column,userMoves,buffer);
//catch information in buffer to send to server
buffer[8] = (row + '0');
buffer[9] = (column + '0');
//cout << "buffer 0 and 1 are " << int(buffer[0]) << " " << int(buffer[1]) << endl;
// add newest move to the list of user moves
userMoves.push_back(make_pair(row,column));
// check if the game is over, send a game over message to server if so and exit/clean up pipes
if (checkValid(userMoves,serverMoves) == 0 || (userMoves.size() + serverMoves.size() == 9) ) {
youwin(screen);
buffer[8] = (3 + '0');
buffer[9] = (3 + '0');
result = fwrite(buffer.c_str(), 1, buffer.length(), pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
}
//mvwaddch(screen, 12, 1, 'k');
//wrefresh(screen);
//cout << endl << endl << endl << endl << endl << buffer << " " << buffer.length() << endl;
// write newest move to server, currently where hangs!!!!!!
result = fwrite(buffer.c_str(),1,buffer.length(),pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
//cout << endl << "written successfully" << endl;
//mvwaddch(screen,12,1,'l');
//wrefresh(screen);
// read in server counter move
result = fread(&catcher[0],1,BUFFERS,pread);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "read error, servermove" << endl; }
// catch newest computer move
charInt[0] = (catcher[8] - '0');
charInt[1] = (catcher[9] - '0');
// if the server says it won, clean up pipes and exit
if (charInt[0] == 3 && charInt[1] == 3) {
youlose(screen);
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
}
// check if the server made a valid move
if (checkX(charInt[0], charInt[1], userMoves, serverMoves)) { invalid = 1; }
//addX(charInt[0],charInt[1],serverMoves,catcher);
// add newest server move to list of server moves
serverMoves.push_back(make_pair(charInt[0],charInt[1]));
// if server has won or a draw, tell the server and clean up pipes/exit
if (checkValid(userMoves,serverMoves) == 0) {
youlose(screen);
buffer[8] = (3 + '0');
buffer[9] = (3 + '0');
result = fwrite(&buffer[0],1,BUFFERS,pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
}
}
// if the move was invalid say so
else { invalid = 1; }
break;
// if user wants to exit, tell the server and clean up/exit
case 'q':
buffer[8] = 3 + '0';
buffer[9] = 3 + '0';
result = fwrite(&buffer[0],sizeof(char),BUFFERS,pwrite);
if (result < BUFFERS) { cout << endl << endl << endl << endl << endl << "write error, usermove" << endl; }
fclose(pread);
fclose(pwrite);
unlink(userWrite.c_str());
unlink(serverWrite.c_str());
endwin();
return 0;
break;
default:
break;
}
}
return 0;
}
server main() :
const int GRID = 9;
const int MAX_G = 10;
const int MAX_L = 10;
const string PRIMARY="/home/mking/GPipe";
int main() {
// variables to hold personal pipe input
char userWrite[MAX_L];
char serverWrite[MAX_L];
// open global pipe and prepare for input
cout << PRIMARY << endl;
FILE * comms = fopen(PRIMARY.c_str(), "r");
cout << "comms open" << endl;
pid_t pid;
bool valid = 1;
int charInt[MAX_G];
char prev[] = "/temp/0000";
size_t result;
// run until forced to close
while(1) {
// get the personal pipe names
//cout << "about to read user" << endl;
result = fread(&userWrite[0], sizeof(char),MAX_L,comms);
if (result < MAX_L && result > 0) { cout << "read error, user" << endl; }
//cout << "read user" << endl;
result = fread(&serverWrite[0], sizeof(char), MAX_L,comms);
if (result < MAX_L && result > 0) { cout << "read error, server" << endl; }
//cout << "read server" << endl;
//cout << "User pipe is " << userWrite << endl;
//cout << "Server pipe is " << serverWrite << endl;
// if a new pipe was detected, fork and play against a client
if (strcmp(prev, userWrite) != 0) { pid = fork(); }
strcpy(prev, userWrite);
// if a chiled, play against a client
if (pid == 0) {
//close comms and open personal pipes
cout << "In child" << endl;
fclose(comms);
string user(userWrite);
string server(serverWrite);
// was having issues with fread earlier also, roundabout fix
user.erase(2,1);
server.erase(2,1);
// set up pipes
cout << "opened pipes " << user << " " << server << endl;
FILE * userFifo = fopen(user.c_str(), "r");
cout << "opened user pipe" << endl;
FILE * serverFifo = fopen(server.c_str(), "w");
cout << "opened server pipe" << endl;
// set up data for server to check moves
pair<int,int> move;
vector<pair<int,int> > userMoves;
vector<pair<int,int> > serverMoves;
char buffer[MAX_G] = {'/','t','e','m','p','/','0','0' };
char filler[MAX_G];
vector<bool> untaken (GRID, 1);
// while game not over
while (valid) {
// get a new move, HANGS HERE!!!!!
cout << "waiting for user move" << endl;
result = fread(&filler[0], sizeof(char), MAX_G, userFifo);
if (result < MAX_G) { cout << "read error, usermove" << endl; }
cout << "move read in" << endl;
// catch user move
charInt[0] = filler[6] - '0';
charInt[1] = filler[7] - '0';
cout << charInt[0] << " " << charInt[1] << endl;
// if user says game over, close pipes
if (charInt[0] == 3 && charInt[1] == 3) {
fclose(userFifo);
fclose(serverFifo);
exit(0);
}
// add user move to list of moves
userMoves.push_back(make_pair(charInt[0], charInt[1]));
// mark location of taken moves
untaken[(userMoves.back().first * 3 + userMoves.back().second)] = 0;
// see if game can be ended and add a server move
valid = checkX(userMoves,serverMoves, untaken);
untaken[(serverMoves.back().first * 3 + serverMoves.back().second)] = 0;
//prepare server move for writing
buffer[6] = serverMoves.back().first + '0';
buffer[7] = serverMoves.back().second + '0';
//buffer[0] = -1;
//buffer[1] = -1;
// write servermove to client
//cout << buffer[0] << " " << buffer[1] << endl;
result = fwrite(&buffer[0],sizeof(char),MAX_G,serverFifo);
if (result < MAX_G) { cout << "write error, servermove" << endl; }
}
// close pipes if game is over
fclose(userFifo);
fclose(serverFifo);
exit(0);
}
}
fclose(comms);
return 0;
}

C++ class and function output issue

I'm having problems with my program's output. It keeps spitting out 12345.
Here's the details:
It's split in three files: program8.cpp (the part that runs tests), myRandom.cpp (implementation of the class), and myRandom.h (specification of the class).
myRandom.h:
#ifndef MYRANDOM_H_
#define MYRANDOM_H_
class myRandom
{
public:
myRandom(); //Constructor
~myRandom(); //Destructor
void seed(unsigned long theSeed); //Mutator for current
unsigned long next(); //Mutator or Accessor for current
int randInt(int start, int end); //Scales result to a range
double randNormal(); //Future expansion
private:
unsigned long current; //Current random #
static const unsigned long a = 1103515245; //Multiplier for LGC
static const unsigned long c = 12345; //Increment for LGC
static const unsigned long m = 2147483648; //Modulus for LGC
};
#endif /* MYRANDOM_H_ */
myRandom.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
myRandom::myRandom() //Constructor
{
current = 0;
}
myRandom::~myRandom() //Destructor
{
}
void myRandom::seed(unsigned long theSeed) //Mutator for current
{
if (theSeed < 0 || theSeed > m-1)
{
// ERROR
return;
}
else
current = theSeed;
}
unsigned long myRandom::next() //Mutator or Accessor for current
{
if (current < 0)
{
cout << "Error: cannot set seed to a negative number" << endl;
return 0;
}
else
{
current = (m*current+c)%m; //Formula
return current;
}
}
int myRandom::randInt(int start, int end) //Scales result to a range
{
if (start >= end)
{
cout << "Error: cannot set start greater than or equal to end" << endl;
return 0;
}
else
{
return ((this->next() % (end - start)) + start);
}
}
double myRandom::randNormal() //Future expansion
{
cout << "Warning: randNormal not implemented" << endl;
return 0;
}
program8.cpp:
#include <iostream>
#include <cstdlib>
#include "myRandom.h"
using namespace std;
int main()
{
myRandom theRand;
unsigned long theSeed;
cout << "Verify that the sequence generated by next() is the same on each run" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.next() << endl;
}
cout << "Verify that you can set the seed to 0 and 1" << endl;
theSeed = 0;
cout << theRand.next() << endl;
theSeed = 1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to -1 generates an error" << endl;
theSeed = -1;
cout << theRand.next() << endl;
cout << "Verify that you can set the seed to m-2 and m-1" << endl;
theSeed = 2147483648-2;
cout << theRand.next() << endl;
theSeed = 2147483648-1;
cout << theRand.next() << endl;
cout << "Verify that attempting to set the seed to m generates and error" << endl;
theSeed = 2147483648;
cout << theRand.next() << endl;
cout << "Verify that next() produces a sequence predicted by hand/calc for the chosen seed" << endl;
cout << "Please enter a seed: ";
cin >> theSeed;
cout << theRand.next() << endl;
cout << "Verify that using start == end generates and error. Set both to 10." << endl;
theRand.randInt(10,10);
cout << theRand.next() << endl;
cout << "Verify that using start > end generates and error. Set start to 10 and end to 5." << endl;
theRand.randInt(10,5);
cout << theRand.next() << endl;
theRand.seed(theSeed);
cout << "Testing randInt for start=0 end=1,000" << endl;
for (int i = 0; i < 5; i++)
{
cout << theRand.randInt(0 , 1000) << endl;
}
return 0;
}
I think the problem lies in the next() function, since that's what gets called all those times in program8.cpp cout statements. I could understand getting 12345 once, but it should be updated once that function runs successive times. I apologize if it's a dumb question. Thank you for your time and patience.
Your problem isn't a code specific one - it is Math-related from here:
current = (m*current+c)%m;
This always returns the value of c if c < m, otherwise (or more generally) it returns c % m. Why? From this theorem:
(m*n + a)%m = a
Example:
m = 10
n = 3
a = 7
(10*3 + 7)%10 = 7
See this for more:
http://en.wikipedia.org/wiki/Modulo_operation

C++ Why is my loop breaking?

I'm following a tutorial for making a MUD (text-based RPG), and I am having issues with my main function. If you'll look at the code, you'll see that when the player moves it will check for a random encounter, and if monster != 0, it will go into the combat loop. When I execute this in the command prompt, it will allow me to attack the monster, but it never makes it to the monster->attack(mainPlayer) function. It just goes back to the screen that states whether I want to move, rest, view stats, or quit. Any help with this would be greatly appreciated!
#include "stdafx.h"
#include "Map.h"
#include "Player.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
using namespace std;
int main()
{
srand( time(0) );
Map gameMap;
Player mainPlayer;
mainPlayer.createClass();
// Begin adventure
bool done = false;
while( !done )
{
// Each loop cycle we output the player position and
// a selection menu.
gameMap.printPlayerPos();
int selection = 1;
cout << "1) Move 2) Rest 3) View Stats 4) Quit: ";
cin >> selection;
Monster* monster = 0;
switch( selection )
{
case 1:
// Move the player
gameMap.movePlayer();
// Check for a random encounter. This function
// returns a null pointer if no monsters are
// encountered.
monster = gameMap.checkRandomEncounter();
// 'monster' not null, run combat simulation.
if( monster != 0)
{
// Loop until 'break' statement.
while( true )
{
// Display hitpoints
mainPlayer.displayHitPoints();
monster->displayHitPoints();
cout << endl;
// Player's turn to attack first.
bool runAway = mainPlayer.attack(*monster);
if( runAway )
{
break;
}
if( monster->isDead() )
{
mainPlayer.victory(monster->getXPReward());
mainPlayer.levelUp();
break;
}
monster->attack(mainPlayer);
if( mainPlayer.isDead() )
{
mainPlayer.gameover();
done = true;
break;
}
}
// The pointer to a monster returned from
// checkRandomEncounter was allocated with
// 'new', so we must delete it to avoid
// memeory leaks.
delete monster;
monster = 0;
}
break;
case 2:
mainPlayer.rest();
break;
case 3:
mainPlayer.viewStats();
break;
case 4:
done = true;
break;
} // End switch statement
} // End While statement
} // End main function
Here is the Player::attack function:
bool Player::attack(Monster& monster)
{
int selection = 1;
std::cout << "1) Attack 2) Run: ";
std::cin >> selection;
std::cout << std::endl;
switch( selection )
{
case 1:
std::cout << "You attack the " << monster.getName()
<< " with a " << mWeapon.mName << std::endl;
if( Random(0, 20) < mAccuracy )
{
int damage = Random(mWeapon.mDamageRange);
int totalDamage = damage - monster.getArmor();
if( totalDamage <= 0)
{
std::cout << "Your attack failed to penetrate the "
<< monster.getName() << "'s armor." << std::endl;
}
else
{
std::cout << "You attack for " << totalDamage
<< " damage!" << std::endl;
// Subtract from monster's hitpoints.
monster.takeDamage(totalDamage);
}
}
else
{
std::cout << "You miss!" << std::endl;
}
std::cout << std::endl;
break;
case 2:
// 25% chance of being able to run.
int roll = Random(1, 4);
if( roll == 1 )
{
std::cout << "You run away!" << std::endl;
return true; //<-- Return out of the function.
}
else
{
std::cout << "You could not escape!" << std::endl;
break;
}
}
}
And here is the Monster::attack function:
void Monster::attack(Player& player)
{
cout << "A " <<mName << " attacks you "
<< "with a " << mWeapon.mName << std::endl;
if( Random(0,20) < mAccuracy )
{
int damage = Random(mWeapon.mDamageRange);
int totalDamage = damage - player.getArmor();
if( totalDamage <= 0 )
{
cout << "The " << mName << "'s attack failed to "
<< "penetrate your armor." << endl;
}
else
{
cout << "You are hit for " << totalDamage
<< " damage!" << endl;
player.takeDamage(totalDamage);
}
}
else
{
cout << "The " << mName << " missed!" << endl;
}
cout << endl;
}
Your Player::attack() method has only one return-statement: return true;. You forgot to add the final line return false; to your method.
This could have easily been prevented if you enable warnings (and pay attention to them!)
Your Player::attack doesn't return in all cases (specifically when it needs to return false). When the calling function tries to access the return value of Player::Attack it will get junk and so you enter the if(ranAway) block and break out of your while loop

final project, Dynamic Programming. Need second set of eyes

I feel really stupid coming to ask this question here today after bugging everyone yesteday on understanding the algorithm. But I am not looking at this thing straight anymore. Anyways, it is a knapsack probled, solved with memoization and dynamic progrmming. The problem is that the printout of my answers is not matching the requierements.
All I want is a second look at it and if someone can point me where I am wrong at.
Appreciated for all the help.
This is the ProfitHeader.h file
#ifndef PROFITHEADER_H_
#define PROFITHEADER_H_
#include <string>
#include <map>
#include <vector>
using namespace std;
namespace kproblem{
typedef int Money;
typedef int Labor;
struct Resources{
Money liquidity;
Labor officeWork;
Labor programmingWork;
Resources(Money li, Labor of, Labor pro) : liquidity(li), officeWork(of), programmingWork(pro){}
//operator -=
Resources & operator -=( const Resources &rhs ){
liquidity -=rhs.liquidity;
officeWork -=rhs.officeWork;
programmingWork -=rhs.programmingWork;
return *this;
}
//operator< Used to make sure that key elements Match. will not modify (this)
bool operator<(const Resources & rhs) const{
if(this->liquidity < rhs.liquidity)
return true;
else if(this->liquidity > rhs.liquidity)
return false;
else if(this->officeWork < rhs.officeWork)
return true;
else if(this->officeWork > rhs.officeWork)
return false;
//this is the iff conditional
else if(this->programmingWork < rhs.programmingWork)
return true;
else
return false;
}
};
//Global Operator-. This will not modify (this).
Resources operator-( const Resources & lhs, const Resources & rhs ){
return Resources(lhs.liquidity - rhs.liquidity,
lhs.officeWork - rhs.officeWork, lhs.programmingWork - rhs.programmingWork);
}
//This is the Project Struct. It should contain the resources and data from the file.
struct Project{
string name;
Resources resources;
Money profit;
Project(string n, Resources re, Money p) : name(n), resources(re), profit(p) {}
};
//Definition of the ValueMap
typedef map<pair<Resources, vector<Project>::size_type>, pair<Money, bool>> ValueMap;
}
#endif
This is my main.cpp
#include <iostream>
#include <fstream>
#include <sstream>
#include <exception>
#include "ProfitHeader.h"
using namespace std;
using namespace kproblem;
//The following was provided to us on the program
class IO_Exception : public runtime_error
{
public:
IO_Exception(const string & message) : runtime_error(message) { }
};
void readProjects(vector<Project> & projects, const string & fileName)
{
ifstream infile(fileName.c_str());
if (!infile)
throw IO_Exception("Could not open " + fileName);
string oneLine;
unsigned int lineNum = 0;
while (getline(infile, oneLine))
{
istringstream st(oneLine);
lineNum++;
string name;
Money liquidity;
Labor officeWork;
Labor programmingWork;
Money profit;
st >> name;
st >> liquidity;
st >> officeWork;
st >> programmingWork;
st >> profit;
if (st.fail())
{
cerr << "Skipping line number " << lineNum << ": "
<< oneLine << endl;
continue;
}
string junk;
if (st >> junk)
{
cerr << "Skipping line number " << lineNum << ": "
<< oneLine << endl;
continue;
}
projects.push_back(Project(name, Resources(liquidity, officeWork, programmingWork), profit));
}
if (!infile.eof())
throw IO_Exception("Error reading from " + fileName);
}
//Class Best Profit.
//This class will calculate the best possible profit we can get.
Money bestProfit(const vector<Project> & projects, Resources res, ValueMap & valMap,int n){
//initialize the best 2 possible solutions.
Money best1;
Money best2;
Money map; // the map where ou answers are stored
// First check if we are not at the end of the projects
if(n == 0){
return 0;
}
//now we are going to check the best project possible.
//Check the subinstance if it was solved.
if(valMap.find(make_pair(res, n-1)) != valMap.end()){
map = valMap.find(make_pair(res, n-1))->second.first;
return map;
}//check if the subinstance is solved. if it is return the value.
best1 = bestProfit(projects, res, valMap, n-1);//first best possible solution
//check the resources for the last project only. Fopr the second best possible solution.
if(res.liquidity >= projects.at(n-1).resources.liquidity
&& res.officeWork >= projects.at(n-1).resources.officeWork
&& res.programmingWork >= projects.at(n-1).resources.programmingWork){// feasability Check.
//all the above are requiered as it is necessary to check for all of them when doing the calculations.
best2 = bestProfit(projects, res - projects[n-1].resources, valMap, n-1) + projects[n-1].profit;
}
else{
best2 = 0;
}
//after the whole check compare the results and store the best possible result in the map.
if(best1 >= best2){
valMap.insert(make_pair(make_pair(res, n), make_pair(best1,false)));
return best1;
}
else{
valMap.insert(make_pair(make_pair(res, n), make_pair(best2,true)));
return best2;
}
}
//reportBestProfit. This will call Best profit and help us print the final results.
void reportBestProfit(vector<Project> projects, Resources resources){
ValueMap valueMap;
//Variables for the total resources used.
Money liq = 0;
Money ow = 0;
Money pw = 0;
int n = 1000; //number of projects, put here for fast testing
Money bestP = bestProfit(projects, resources, valueMap, n);
//Iterate the valuemap and print the best projects available to us.
cout << "Selected Projects -" << endl;
for(int i= 1; i <= 1000; i++){
//if(valueMap.find(make_pair(resources, i-1)) == valueMap.end()){
if(valueMap.find(make_pair(resources, i))->second.second == true){
//if(valueMap.find(make_pair(resources, i))->second.first != valueMap.find(make_pair(resources, i-1))->second.first){
//cout << valueMap.find(make_pair(resources, i))->second.first; //money
//cout <<" "<< valueMap.find(make_pair(resources, i))->second.second; //boolean
cout << " " << projects.at(i-1).name << " " << projects.at(i-1).resources.liquidity <<" ";//projects
cout << projects.at(i-1).resources.officeWork << " " << projects.at(i-1).resources.programmingWork;
cout << " " << projects.at(i-1).profit << endl;//profit
//}
}
}
cout << "Total Resources Used -" << endl;
//Print the resources consumed.
for(int i= 1; i <= 1000; i++){
if(valueMap.find(make_pair(resources, i))->second.second == true){
liq += projects.at(i-1).resources.liquidity;
ow += projects.at(i-1).resources.officeWork;
pw += projects.at(i-1).resources.programmingWork;
}
}
cout << " " << "Liquidity: " << liq <<endl;
cout << " " << "Office Work: " << ow <<endl;
cout << " " << "Programming Work: " << pw <<endl;
//Print the total Profit.
cout << "Profit: " << bestP << endl;
system("PAUSE");
}
int main()
{
vector<Project> projects;
try
{
readProjects(projects, "Proj5Data.txt");
}
catch (const IO_Exception & ex)
{
cerr << "IO error from: " << ex.what() << endl;
return 1;
}
//these values can be changed for different analysis on projects.
Money liquidity = 200;
Labor officeWork = 450;
Labor programmingWork = 1000;
cout << "Available resources - " << endl
<< " Liquidity: " << liquidity << endl
<< " Office Work: " << officeWork << endl
<< " Programming Work: " << programmingWork << endl;
reportBestProfit(projects, Resources(liquidity, officeWork, programmingWork));
return 0;
}
The project file that contains the projects can be downloaded temporarily here:
https://rapidshare.com/files/459861869/Proj5Data.txt
my guess is the problem is on the valmap find, but I have tried all kinds of combinations and it does not work at all.
Finally this is the final printout I should be getting from this:
But instead I am getting all these other results, including some of the ones I need:
Again thank you for the one that can slap me in the head and say, you FOO, you shouldn't be doing this anymore :).
removing this would get rid of the leading numbers on the second part of the output
cout << valueMap.find(make_pair(resources, i))->second.first; //money
cout <<" "<< valueMap.find(make_pair(resources, i))->second.second; //boolean
cout << " "
the values you print at this point haven't been filtered by and ordered by which is why i think your printing these values
but you don't have code to print "The total resources used -" part
OK, so yes I do have an answer. Is now complete (after edit)
void reportBestProfit(vector<Project> projects, Resources resources){
ValueMap valueMap;
//Variables for the total resources used.
Money liq = 0;
Money ow = 0;
Money pw = 0;
vector<Project> result;
int n = 1000; //number of projects, put here for fast testing
Money bestP = bestProfit(projects, resources, valueMap, n);
//Iterate the valuemap and print the best projects available to us.
cout << "Selected Projects -" << endl;
// this loop just iterates through the values, it does not check the initial resources.
for(int i= 999; i > 0; i--){
//if(valueMap.find(make_pair(resources, i-1)) == valueMap.end()){
//check first If I still have resources available
if(resources.liquidity >=0 && resources.officeWork >= 0 && resources.programmingWork >= 0){
if(valueMap.find(make_pair(resources, i))->second.second == true){
//when I find the first true, I need to substract the resources of it from the base resources,
//to ask the question again.
resources.liquidity -= projects.at(i-1).resources.liquidity;
resources.officeWork -= projects.at(i-1).resources.officeWork;
resources.programmingWork -= projects.at(i-1).resources.programmingWork;
//Push the results into a vector for the printout
result.push_back(Project(projects.at(i-1).name,
Resources(projects.at(i-1).resources.liquidity,
projects.at(i-1).resources.officeWork,
projects.at(i-1).resources.programmingWork),
projects.at(i-1).profit));
//Also in one shot add together the resources used
liq += projects.at(i-1).resources.liquidity;
ow += projects.at(i-1).resources.officeWork;
pw += projects.at(i-1).resources.programmingWork;
}
}
}
//Print the saved vector in reverse order
for(int size = result.size(); size != 0; size--){
cout << " " << result.at(size -1).name;
cout << " " << result.at(size -1).resources.liquidity;
cout << " " << result.at(size -1).resources.officeWork;
cout << " " << result.at(size -1).resources.programmingWork;
cout << " " << result.at(size -1).profit << endl;
}
cout << "Total Resources Used -" << endl;
////Print the resources consumed.
cout << " " << "Liquidity: " << liq <<endl;
cout << " " << "Office Work: " << ow <<endl;
cout << " " << "Programming Work: " << pw <<endl;
//Print the total Profit.
cout << "Profit: " << bestP << endl;
system("PAUSE");
}
Basically I was not substracting the resources, so I was always having over resources, but once I did that viola! it works. Thank you guys for looking at it, I guess I just needed inspiration this morning.