Designing Game of Life using classes C++ [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
for my final project in my intro C++ class we have to design a version of Game of Life using classes and file I/O. I have been given some beginning functions/instructions but can't even begin to understand where to start or if I am missing other functions to get started. I've included the instructions given and what I have so far. I don't necessarily need the whole thing laid out for me, but if I could just have a little help on how to get started, that would be great.
Instructions:Since the project is in chapter 7, the book’s version doesn’t work with classes and it doesn’t have any file IO. Let’s
address the file IO first. On the project download page in addition to the usual items there will be two data files
containing very simple life community specifications. The files have the following format: first item in the file is the
number of rows the community requires, second item in the file is the number of columns the community requires, third
item is the LIFE community which is stored as ‘.’ (dead) or ‘O’ (alive) characters in the array shape specified by the
preceding two values.
In order for your project to work with these inputs you will need to specify a two dimensional array. The book specifies a
22 by 80 array. The GTA project uses a 50 by 100 (row by col) array. So long as your array is larger than the size specified
by the input, your code will work with the input. After creating the array, the code reads in the data from the input and
fills out your LIFE community array with a small twist. The book suggests filling in the grid directly with asterisks for live
cells and blanks for dead cells. We will use class objects instead.
The normal implementation of LIFE uses two identical arrays. One stores the now generation and one is used to store
the next generation. (see the book pgs 446 & 447) We will be using one array which contains LIFE cell objects made from
the simplest useful class we could think of. Our class objects will contain two Boolean data items that store the cell’s life
condition and one function which will age the cell.
Your LIFE community’s size should be square and an edge length is define globally as const int edge=#. Your class is
named cell and contains the public boolean variables aod_d0, aod_d1 and the void function age(). Create a general
function that counts the number of living neighbors of a cell and declare its type with the following declaration: int
nbors_sum(cell[edge][edge], int, int, int, int);. Your LIFE community ages a day at a time so create a general function that
reads cells at d0 and determines whether that cell is alive or dead (aod) at d1. It’s declaration is: void oneday(cell[edge]
[edge], int, int);. The oneday function will call the nbors_sum function. The GTA version has a fair amount of code in
main() including file input and the while(true) display loop.
Code:
#include <iostream>
#include <fstream>
using namespace std;
const int edge=20;
class cell{
public:
bool aod_d0, aod_d1;
int nbors_sum(cell[edge][edge],int,int,int,int);
void oneday(cell[edge][edge],int,int);
int main()
{
ifstream in;
in.open("glidergun.txt");
if(in.fail())
{
cout <<"Input file failed to open.\n";
return 1;
}
oneday()
in.close();
return 0;
}
void age();
int nbors_sum(cell[edge][edge],int,int,int,int);
void oneday(cell[edge][edge],int,int){
}

It's not so hard - that's a pretty common excercise, so there's a lot of material on the Web. Just check Wikipedia, for example, to get an idea and see some animations of this "Game" in motion:
https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life
As a starting point, I would suggest that you do the following:
Make your program read in a file and store the data within a 2D
array, as suggested by the excercise
Make your program print the
resulting 2D array to the console (standard output)
If you manage to get those two steps done, by the point you proceed you will already have a better understanding of what this is all about.
My general suggestion would be that you, if you face a problem like that where you don't know what to do, just start by doing the very obvious things that need to be done anyway (such as the reading the file, in this case). By doing that, you will get familiar with the rest on the way.

Related

How to write output of two different functions at the same times on separate lines in console? (C++, Windows 10)

I have the write() function which takes a string and an int for time as parameters. It takes the given string and writes the same string, letter by letter, with a set time delay.
For example, write("Cat is moving", 50) would output each letter one after the other with a 50 millisecond delay.
Right now I am wondering how I could make it so the console can output 2 different write() functions on the screen at the same time, on two separate lines of the console, without overlapping each other.
I tried doing something with multi-threading but it didn't work and I believe there has to be a simpler way.
This program is intended for Windows only.
I did implement a change cursor position function already, so that shouldn't be a problem.
This is the function:
void write(string word, int time)
{
for (int i = 0; i < word.length(); i++)
{
cout << word.at(i);
Sleep(time);
}
}
You are basically asking for a way for your program to be logically running several instances of the same function at the same time (without using recursion).
Although this can be accomplished by using multithreading, I don't recommend doing this, because in your case, this will probably introduce more problems than it will solve.
An alternative to multithreading may be to use coroutines, which were introduced in C++20. If you make write a coroutine instead of a function, then you may be able to solve the problem by having several of these coroutines logically running at the same time (they will probably not actually be running at the same time, because they will be suspended most of the time).
Unfortunately, I have no practical experience with coroutines, so I am unable to provide the details of a solution which would use coroutines. All I can say is that they are probably worth looking into for you, because as far as I can tell, they coincide with your way of thinking and with your way of wanting to solve the problem.
A more traditional way of solving the problem in C++ would be the following:
In the main loop of your program, you could call a function write_next_characters (which you write yourself) every 50 milliseconds, which writes the next characters of all words that are currently to be written.
In order for this function to work, your program will have to keep track of
a list of all words that are currently to be written,
the screen coordinates to which each word is to be written, and
how many characters of each word have already been written.
The function write_next_characters should receive a pointer to this information whenever it is called by the function main. It can then jump to the appropriate screen coordinates and print the next letter of each word. It will also have to update the state information mentioned above.
I would suggest that you define the following struct which contains the state information mentioned above for every word:
struct word_state
{
//the word that is to be written
std::string word;
//the screen coordinates to which the word is to be written
int x;
int y;
//how many characters have already been written
int written;
};
For every word that you are currently writing, you will have to create one object of type word_state. You can use a container of type std::list<word_state> to keep them in a linked list. I believe that using a linked list is appropriate, so that you can easily remove words from the list after the last character of that word has finished printing.

write and load decision tree to file C++ [duplicate]

This question already has answers here:
How to Serialize Binary Tree
(11 answers)
Closed 6 years ago.
I have a decision tree node class defined in following way:
class dt_node
{
public:
dt_node* child[2]; //two child nodes
int feature;
double value; // feature and value this node splits on
bool leaf;
double pred; // what this node predicts if leaf node
}
Is there a way I can write this to a file and reconstruct the tree from the file if needed?
You can do it anyhow you want...
And the real answer: it really is up to you only. If I were you, and had to save this kind of object in a .txt file, I would just make up some way to save this structure, for example as 0*0*0.0*0*0.0. With the first 0 representing the number of child nodes, second 0 representing the feature value and so on, while * character being a separator between values. Spaces could work better, but I just don't like them as separators in my files... Text file would then have some other character (for example, an |) between each separated object. Example would look like 3*22*31.11*1*1.0|2*2*1.0*0*33.3.
Obviously I could've misinterpreted your qestion. If you ask is there a way of saving this particular code and execute it via opening the file in a program without the dt_node class, I, unfortunately, feel like my knowledge is not sufficent enough to answer.
Hope it helps anyhow.
If you would like to write the format yourself, I'll just write every other node's parameters in the file (two doubles, bool and one int) along with it's level starting from the root node and then recurrently proceeding through the tree. As I can see, the bool you have in it controls whether the node have or have not any children, this will help in the reading file process.
File reading will be a bit mode complex than file writing. For each node you read, recurrently, again, read next nodes until any node's level will be equal or lesser than the current node's. It sounds complex, but it really isn't.
Of course you shouldn't write the note* pointers to the file, as they contain useless information, as upon reading the file you will have to recreate the full tree again.
Adding boost to your project can be a little bit of a pain, but there's quite a few libraries there including maths and graphics, so it may well be worth the effort.
The Boost serialisation docs are here with a tutorial here
The serialisation library allows you to add even just 1 function to your class which then defines how to save and load the state of that class. How that data is actually saved is then done by the boost library, for example you can have it save with binary, xml & text.
The only thing that you need to watch out for is that the binary serialisation is not machine transferable.

C++ Multi-Dimensional Array saving/loading to file error [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I've been working on this C++ project for roughly 2 weeks now and I'm stumped on a couple things regarding 2D Arrays. To start off here is the code I wrote as of now:
http://pastebin.com/vCsz947Q
I decided to provide this as a pastebin link due to the fact that it's rather large (it uses 8 functions) and I thought it would save space in this post. I'm new to this site so I apologize if there's a better way that I'm not aware of.
The Problem:
When I go to save my "char seating" array to a .dat file using the "save seats" function that I created, I get a file that gives me the following garbage character " Ì " instead of the intended ' # ' (for open seats) or ' * ' (if a seat is bought).
My functions will save the intended amount of rows (15) and columns (30) despite this though. Also an asterisk will be placed when I go to "purchase a seat" in this program in the file. Additionally my program loads the files as intended, except for the fact that... Well... There's garbage data stored in the seat array.
I feel like this relates to another problem I'm having where if I go to the "purchase seats" function and I say to purchase a seat, it should replace a # with a *, but it doesn't, yet in the saved file it will show an asterisk in the intended spot... Which is very strange.
I have absolutely no idea why this occurs, and what's frustrating is this one thing that's preventing me from finishing this program. I want to believe that my original array in int main that's being called by other functions isn't being updated properly, but I don't know, which is why I came here to seek assistance.
Thank you for your assistance whoever can help.
Well for a start you have some undefined behaviour here inside your displaySeatingChart (char displaySeats[ ][30], float displayPrices[ ]) function with the following:
const int rowDisplay = 15;
const int colDisplay = 30;
as later within one of your loops you have
cout << displaySeats[rowDisplay][colDisplay];
which is clearly reading beyond the array bounds since in main() you define
const int rowMain = 15;
const int colMain = 30;
char seating[rowMain][colMain];
float seatPrices[15];
and pass both seating and seatPrices to the displaySeats function. There may well be other problems with your code but this at least is a clear example of undefined behaviour. Consider stepping through the code with a debugger to get a clearer idea of the source of the issue.
On another note given that you are working with C++ consider working with std::vector instead of arrays. This will give you more scope to ascertain the dimensions of the items that arrays that you are working with from within your utility functions and result in less potential for errors in array access.

Copy Certain Portion of One Array to Another

I'm still quite new to programming -- about two months in -- so if this is a really basic question, then I apologize. Going along with that, my terminology might be completely off. If it is, I'd greatly appreciate any help you might be able to offer with telling me the proper terms. I searched around the forums here for a bit, but couldn't find anything that answered my question. If you're aware of a topic that does, then please just link it below.
Onto the question.
Let's say that I have an external text file with a bunch of information in it. The information is divided into items, each item delineated from the next by '::'. Each item is divided into four fields, each field delineated from the next by '\'.
What I want to do is take one item's information out of the text file and place it into an array called info. I want to then take info and pass it to another function. This function will create four new arrays and then portion out field 1 to array 1, field 2 to array 2, etc.
Basically, how do I take an array, take a portion of that array and give it to another variable, then copy another portion of that array and give it to another array.
Example:
The External Text File looks like the following:
26::Female::Kentucky::Trauma\\34::Male::Michigan::Elective\\85::Male::Unknown::Trauma\\18:Female::Washington::Emergent
Using fstream, I then take "26::Female:Kentucky::Trauma" and put it into an array called 'info', which is then passed to a function called Sort(char info[]).
How do I get Sort(char info[]) to take an array with "26::Female::Kentucky::Trauma" and turn it into four arrays such as:
Age: 26
Sex: Female
Location: Kentucky
Reason for Admission: Trauma
EDIT
Array 1 looks like:
26::Female::Kentucky::Trauma
I then create four char arrays called, Age, Sex, Location, Reason. How do I get 26 into the Age array, Female into the Sex array, Kentucky into the Location array, and Trauma, into the Reason array?
I know that I could do this at the stage where I'm reading in from an external file, but it seems easier to do it this way for my purposes.
Thank you for your time.
Look at the documentation for the string class. The functions find_first_of and substr will be useful. Split the string when it finds :: or //. For example, 26::Female::Kentucky::Trauma would be split into 26 and Female::Kentucky::Trauma. This sounds like it may be an assignment, so I will not give a complete solution, but this should be enough to get you going.

C/C++ code for rearranging .txt file [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Hi i have to make a function in C++ that gets one file as an input and as an output it has another file, that is rearranged in a specific way. In the file there are names of people,names of subject they are teaching, commented lines starting with '#' and also duplicated white spaces. The input file looks like this (before ':' are the names, after it are the subjects):
john : PA1 , PA2,OSY
#this is commented line
peter: PA1, PA2
And the output in the second file should look like this:
OSY: john
PA1: john, peter
PA2: john, peter
As you can see, the function should put one subject on each line (in alphabetical order) and then there should be ':' and after that the names of the people teaching it (also in aplhabetical order). Also all commented lines should be deleted and the same with duplicated white spaces.
I know how to delete duplicated white spaces and commented lines, but I have problem with rearranding the people and subjects. Is there any possible way to do this function without using classes?
I would be very thankful for any help or advices.
bool transform ( const char * inFile,
const char * outFile )
{
// todo
}
There are various different problems to solve. You must first identify those individual problems, then solve them one by one, and then put the pieces together. Many years ago, when I was a student at university, this approach was taught to me as "divide & conquer".
Here are the individual problems I can identify in your question:
Read a text file's contents into memory, so that you deal with strings and each line is a string.
Parse a string. Split it into substrings, so that you deal with a collection of strings (tokens). Know when a string starts with a particular character.
Create a data structure in which a sorted, unique string key relates to a list of (likewise ordered and unique) strings.
Write a series of strings to a text file.
Each of the sub-problems may well be individual separate questions on Stack Overflow. I'll give you hints for every one of them, so that you can google them or browse the archive for related questions:
Reading a text file line by line in order to end up with a series of std::string objects is best done with std::ifstream and std::getline.
Getting the first character of a std::string is easy: my_string[0], first checking if !my_string.empty(). Splitting it is more difficult. I would personally use the occasion and get started with the Boost libraries. See the Boost Tokenizer example.
The data structure you need is already there - C++ itself provides it as part of the language. The first thing which comes to mind is std::map<std::string, std::set<std::string> >.
Writing is simpler: use std::ofstream and write line by line with operator<<.
std::map and std::set are your best friends here.