Why am I getting this output? - c++

Alright so I writing Conways Game of Life in C++, and so far I have only created the rule that allows users to create cells if it has 3 neighbors.
Here is the current code: http://tinypaste.com/f59b4463
When I launched the program I entered in the coordinates so that I would have the gameboard depicted in the photo below, and the output wasn't what I expected, it should have made it so that the cell 2,1 would be alive, but in the output it remained dead. I am not sure why it is not working. Any help?
Input & Output: http://i.imgur.com/1Mvhi.png

Several things to address, and while this is not an answer, it's too big for a comment. Please fix these then I will get back to you...
In gameboard() please arrange the code so that it consists of two for loops instead of all the couts. Example:
int i, j;
for (i = j = 0; i < 10; i++) {
for (; j < 10; j++) {
cout << world[i][j];
}
}
it's much more concise.
Second, in cells(), in the second for loop, you can use another nested for loop.
Third, I would avoid naming normal variables in ALL CAPS since that is generally reserved for preprocessor #defines.
K, enjoy cleaning up :)

Alright. It's an algorithmic issue. When you call calculate, it creates extra cells because it's not exactly one generation. It's a mix of two and three - it acts on cells you just created. Get what I'm saying? I explained this on GMail.

Related

Comparing indexes in arrays/vectors

I just completed a project through Codecademy, and I couldn't for the life of me figure it out. I went and looked at the example solution and it contained code that I didn't even know you could do and I cannot figure out how it works.
There is a nested for loop, and the user takes advantage of adding the indexes together?? Or is comparing them?? I've just never seen it done, to be quite honest and I have looked for an explanation of what exactly is happening and I can't find one.
`
for (int i = 0; i < text.size(); ++i) {
int match = 0;
for (int j = 0; j < word.size(); ++j) {
if (text[i+j] == word[j]) {
++match;
}
}
`
The project was a C++ program where you had to bleep a word out of any phrase that was input into the program. I just don't understand what "text[i+j]" accomplishes? How do you add two indexes together in a for loop?? Does it add?? Does it compare?? But comparison doesn't make much sense to me either??
Here is a link to the github repository as well, so you can see the entire program: https://github.com/Codecademy/learn-cpp/tree/master/8-references-and-pointers/bleep
Since you're learning, the easiest way to figure this out is to write out exactly what is happening. Take text=="Hello, World and word=="World", and work out on paper how this code runs. For what values of i and j will match be incremented?

How would I overwrite a printed 2D array to simulate 'updates'

So given a 2D array called 'world' and the code below to output the array to the console. I want to constantly update the outputted array using a while loop to simulate movement and other actions via changes in the array values without it messily reprinting the entire thing for every update.
I would imagine the best way to do this would be to try and reset the output stream to the first line and overwrite the previous printed array each update but I am unsure on how to do this.
char world[20][20];
for (unsigned int row = 0; row < std::size(world); row++)
{
for (unsigned int col = 0; col < std::size(world); col++)
{
std::cout << world[row][col];
}
std::cout << std::endl;
}
There is a simple way to do this on one line, using \r with printf, as discussed here. However, I'm not certain this is easy if one wishes to reprint multiple lines, as you do.
A better suggestion would be to make use of something like ncurses, which seems to be designed for your purposes, and was probably used to make other programs you've seen operate this way.

C++: Iterate using enum type

I have these codes:
for (i = 0; i <= WND_WRL; i++) {
syslog(LOG_ERR, "TESTE i=%d WND_WRL=%d", i,WND_WRL);
}
for (i = 0; i <= WND_WRL; i++) {
syslog(LOG_ERR, "OnScrDsp for i=%d WND_WRL=%d", i,WND_WRL);
m_pWnd[i] = gtk_window_new(GTK_WINDOW_POPUP);
assert(m_pWnd[i]);
}
The first for is only to explain my problem. The second is really my problem.
The source of second code can be found here:
https://github.com/HuayraLinux/intel-classmate-function-keys/blob/master/OnScrDsp.cpp
The problem:
WND_WRL variable came from
typedef enum {
WND_BRG,
WND_DSP,
WND_WRL,
} WND_ID;
struct.
In first code I can see i iterate until 2 (0,1,2) and WND_WRL will be always 2. The problem is in second code: even WND_WRL ever print 2 value, that for will iterate i until receive SIGV signal (11) and break my application (here it stop with i=384). I can understand why 384, I am not concerned about that.
What I do not understand is why the same condition provide different ways. If I change WND_WRL to number 2, I get correct code and correct app execution.
My first idea is the block of the second for maybe change WND_WRL value, but isn't happened.
I can understand if may be this code is writing in wrong memory position, but I always see WND_WRL with 2 value.
SOLUTION :
Change expression "i <=WND_WRL" to "i < WND_WRL" because m_pWnd size. It explain SIGV, but not explain why for continue until receive SIGV even if 2<=2 condition matches. Overriding memory we know can destroy a lot of things, but constants and code are read-only stack memory region, so access m_pWnd[3] and others i++ not explain why for does not stop.
Variable m_pWnd is defined in your source code as an array of pointers, with a size of 2, so valid index is 0 or 1.
GtkWidget *m_pWnd[WND_WRL];
But your loop goes i <= WND_WRL, so i=2 case will crash
m_pWnd[i] = gtk_window_new(GTK_WINDOW_POPUP);

C++ character variable value of '\x1'

I'm failing to understand why would the loop exit at the value of character variable i = '\x1'
#include <iostream>
using namespace std;
int main()
{
char i;
for (i = 1; i < 10, i++;)
{
cout << i << endl;
}
return 0;
}
Can somebody please explain this behavior ?
This is wrong
for (i = 1; i < 10, i++;)
/* ^ should be ; */
You only declared 3 regions for the loop, but put your increment statement in the middle area, and left your increment area empty. I have no idea which statement in the middle area your compiler will choose to execute. Best not to try to be cute and deceive your compiler. Let alone some colleague who will read your code years from now and go WTF???
A for loop has 3 distinct areas delimited by semi-colons:
The initialization area. You can declare as many variables in here as you want. These can be delimited by commas.
The test area. This is where an expression goes to test if the loop should continue.
The post loop area. This region of code gets executed after every loop.
Try to keep it simple. If it is going to be more complicated then use a while loop.
The reason that i ends up being 1 is that when i++ is zero, which terminates the loop, then i will become 1 (That is what the form of the ++ operator you used does). As the other answered have pointed out, once you fix your code by moving i++ out of the condition by replacing the comma with a semicolon, then i will make it all the way to 10 as desired.
for (i = 1; i < 10; i++)
You wrote for statement wrong.

Optimize my code? C++ Compare arrays & calculate prize

I'm doing this slot machine game where a 3x3 2D-array is being generated with random letters.
I have successfully made the game work as I want but I wonder if you have any tips on how I can optimize or improve my code.
What I've gotten my code to do:
Generate an 2D-array (3x3) and randomly assign chars out of 3
letters.
An "if" that will compare and see what elements in the array belong
to each other (same char next to eachother for getting
columns/rows/diagonals).
An "if else" that will take total amount of columns/rows/diagonals
and make a prize out of it, depending on total amounts of row in the
slot machine and the bet.
So I'm now wondering if you have any suggestions on how I can improve the "if" code where the program checks if there are any rows/columns/diagonals? The game works as it should but I just wonder if there's any way of optimizing it - Perhaps with a "for-loop"?
I also wonder if you have any tips on the "prize" code where the code calculates total amout of rows/columns/diagonals and multiplies that with the bet.
I mean, there must be a way to optimize this. If I was to do a 100x100 array, the code where the elements are compared would be awfully long :)
I'm new to C++ (this is a course) so I'm looking forward to optimize this.
PS! I'm not asking for a solution but rather suggestions/tips of methods I can use to optimize it.
This is a homework so no solutions please, only suggestions/tips!
My code for the array comparison and prize calculation:
To optimize, running a profiler would give you a lot of information. If you're talking about general guidelines to optimizing your application, here are some:
1 - use threads to process in parallel
2 - reduce cache miss by keeping the data properly aligned depending on the processing done on it. For instance, if you need to use the speed to process the position, keeping them both near each other in memory will reduce cache-misses.
ie:
struct Particle
{
float position;
float speed;
};
Particle particles[NUM_PARTICLES];
vs
float positions[NUM_PARTICLES];
float speeds[NUM_PARTICLES];
3- Don't process what you don't need to process or user can't see. For instance, some stuff may not affect the current states - no need to process it (in graphics, we use scene management like octtrees but the same applies to all - if you don't need it, don't process it).
4- Reduce the amount of floating point operations.
See this post as well - it provices with some good C++ references for optimizations: C++ Optimization Techniques.
About optimizing:
Don't optimize prematurely - it won't help anything. I'm too lazy to write about that, but search internet, read "Code Complete" and "C++ Coding Standards: 101 Rules, Guidelines, and Best Practices" books.
Don't waste - if optimization won't take more time and is at same readability level, than you can use it.
Optimize AFTER a speed problem arise.
About your problem:
You are absolutely right that there should be better ways to write a code. What you wrote is what workers do, but you need to be smart programmer to make it more easy.
But what you need is more knowledge about language.
Yes, there is a looping possibility for C++. For example following code checks whether a line contains same values:
const int rowCount = 3; // Number of rows
const int colCount = 3; // Number of columns
// Variable for counting same rows
int sameRowsCount = 0;
// Following line is loop: first it sets variable row to 0
// and for each pass it increments it until rowCount is reached
for(int row = 0; row < rowCount; ++row)
{
// This variable stores whether the row contains same values.
// At beginning we assume that it does.
bool isSame = true;
// Now we will check each column in current row. Note that
// we begin with 1 and not 0 - at 0 position is value which
// we check against all others.
for(int col = 1; (col < colCount) && isSame; ++col)
{
if(matrix[0] != matrix[col])
{
// We found different values
isSame = false;
}
}
// If row contains same values, isSame remained true and
// we increment same-rows counter.
if(isSame)
{
++sameRowsCount;
}
}
cout << "Number of same rows: " << sameRowsCount << "." << endl;
Depends on the array size(s) as you mentioned. With small arrays the if statements may be more efficient than using a loop (or two nested) to iterate over all the elements (this is also called 'loop unrolling' and is considered a performance improvement).
To 'optimize' (I'd better say generalize) your code for any array sizes you should use for loops of course to iterate over the x/y indices.
Completed code:
//Check all horiztonal and vertical locations
for(int i = 0; i <= 2; i++)
{
if(matris[i][0] == matris[i][1] && matris[i][1] == matris[i][2])
rows++;
if(matris[0][i] == matris[1][i] && matris[1][i] == matris[2][i])
rows++;
}
//Now check diagonals
if(matris[0][0] == matris[1][1] && matris[1][1] == matris[2][2])
if(matris[0][2] == matris[1][1] && matris[1][1] == matris[2][0])
//Calculate prize
prize = g_satsning*(1 << rows);
In terms of speed, what you have is not going to be inefficient. If you are looking to generalize the code and make it scalable (e.g. if you wanted to add 2 more rows/columns), there are several things you could do (e.g. looping and a more mathematical form of prize calculation).
The looping has already been discussed, but the prize calculation could be simplified a bit using something like the following:
if (rows > 0 && rows < SOMEMAXIMUMVALUE)
{
prize = g_satsning * (1 << rows);
}
else
{
prize = 0;
}
Since your multiplier is an exponent of 2, the math is fairly straight forward. SOMEMAXIMUMVALUE should be declared to be the maximum number of matching rows you expect. For a 3x3 setup, there would be 8 potential matches (3 rows, 3 columns, 2 diagonals), so SOMEMAXIMUMVALUE should be set to 8.