i'm buisy learning myself to program and i'm trying to copy a game that i find fun to play to c++ (basicly just for the sake of learning. So if i formulated the question wrong please forgive me.)
Now i have an issue with randomising a 2 dimentional array. The thing is that i manage it partially to get it to work but i just fail to reason how i can make it fully work.
The code:
// Random generate and return nr 2 or 4 on calling this function.
int startValue1(){
srand(time(NULL));
int arrayStart[2] = {2, 4};
int randIndex = rand() % 2;
return arrayStart[randIndex];
}
// Random generate and return nr 4 or 2 on calling this function.
int startValue2(){
srand(time(NULL));
int arrayStart[2] = {4, 2};
int randIndex = rand() % 2;
return arrayStart[randIndex];
}
int tester(){
//generate 2 start values and assign to variables
int a = startValue1();
int b = startValue2();
//initialize 2 dimentional array and add the 2 starting numbers.
int board[4][4] = {{a,0,0,0},
{0,0,0,0},
{0,0,0,0},
{0,0,0,b}
};
// print out the board in console to check/test the function(S).
for(int row = 0; row<4; row++){
for (int column = 0; column<4; column++){
cout << board[row][column] << " ";
}
cout << endl << endl;
}
cout << endl;
//Randomize the elements in the 2 dimentional array.
random_shuffle(board, board +4) ;
//print out the array to console after the board is randomised (for testing/checking only)
for(int row = 0; row<4; row++){
for (int column = 0; column<4; column++){
cout << board[row][column] << " ";
}
cout << endl << endl;
}
}
The output of this looks something like this :
0 0 0 0
0 0 0 0
4 0 0 0
0 0 0 2
The problem is that the elements only arrange verticaly and never horizontally as if the random_shuffle function only works on one dimention. I did read up on that function but i just fail to see/reason how i can make it work on a 2 dimentional array. Hopefully someone can give me some pointers or directions to the info on how to solve this.
Personally i thought that it would be best if i just now somehow arrange the elements horizontally and continue from there. But if there is a better solution i'm al open for it ofcourse.
(In case for anyone who wonders: i'm trying to remake the webgame 2048 in c++ and i plan to use this code to initialize the board and make it ready to play. Most likely it's not the best approach to solve this but i'm trying to tackle one problem at the time and learn from it and just keep redoing the code till it works.)