I was trying to create a memory type of game here with 8 by 8 totaling 64. What I'm trying to do here is to have 2 sets of pairs in the board from 1 - 32. I used the rand to generate random integer for every column and row however I do notice that some numbers appear more than twice and some only once or none. What can I do to limit these numbers to make them appear exactly two times?
If you want to populate the array with number pairs, you will need a way to track which numbers have been used.
One option is to create a list of ints that holds two of each number from 1 to 32. For example, using a vector:
1 2 3 4 5 6
vector<int> tiles;
for (int i = 0; i < 32; ++i)
{
tiles.push_back(i+1);
tiles.push_back(i+1);
}
Once you have your list, you can use rand() to choose an index from 0 to tiles.size(), insert the value stored at the index into your board, then erase that element from tiles so you don't repeat it later. I used a vector instead of an array because it's easier to remove elements from the middle.
No doubt there are other ways to achieve your goal. I suspect in any solution, you'll need to track what integers have been added -or- what integers still need to be added.
To do that you have two options:
- You can keep track of which values are already in the board.
- You can limit the values that the computer can choose from to a set of values and make sure that set contains exactly two values of each to start with.
Personally I would go for the second option. That could look something like this:
#include <iostream>
#include <vector> // required to work with vectors
#include <algorithm> // required to randomize a vector
void memorygame(int boardsize);
int main()
{
memorygame(8);
system ("pause");
return 0;
}
void memorygame(int boardsize)
{
std::vector<int> cards;
for (int i=0; i<(boardsize*boardsize)/2; i++)
{
cards.push_back(i+1);
cards.push_back(i+1);
}
// You now have a vector with 64 values (1 to 32 all twice).
// using built-in random generator to shuffle all the cards:
std::random_shuffle ( cards.begin(), cards.end() );
// You now have a randomized vector with 64 values, (1 to 32 all twice).
// Lets put them in the board.
int board[boardsize][boardsize];
for (int i = 0; i < boardsize; i++)
{
std::cout << std::endl << std::endl;
for (int j = 0; j < boardsize; j++)
{
board[i][j] = cards.back(); // places the last value from the vector in your grid.
cards.pop_back(); // removes the last value from the vector
std::cout << board[i][j] << "\t";
}
}
std::cout << std::endl;
}