Need help printing a 2D array Please help.

I was given a skeleton code to follow by implementing functions. LOTS of them! To create an interactive 8–puzzle game that will generate, valid, solvable puzzles. The objective of the game is to sort the numbers by moving them around until they are sorted.
For example,
123
45
786
can become
123
456
78
in one move, which would then be the correct sorted list.

Write your question here.

My question is how can i get the at least the 2d array to print and then from there I think I should be able to figure out the rest? Fingers crossed!! Please help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  //Your Code Here: I have intentionally removed most of the parameters to the  function prototypes and function definitions.
//You must figure out what function needs what and add it back in.
//Similarly in the main function I have removed most of the actual parameters passed to the functions so add those back in.
//You are not allowed to declare any additional variables inside the main function. If you declare any you will lose 50% of the grade.
//Several Parts of the code are temporarily commented out. Uncomment them as you add back the correct code. You will notice compilation errors
//As you uncomment the code. This is normal as code is missing, once you add it in all will be fine.


//Function Prototypes:
void initRand();
void initGrid();
bool argCheck(int argc, int);
int randomchoice();
void randomizeGrid(int iterations);
int getDifficulty(int argc, char *argv[]);
int getRoundCnt();
void clearScreen();
void printGrid();
bool checkWin();
bool checkMaxRounds(int, int);
void getOptions();
void printAvailableOptions(bool[]);
int readchoice(bool[]);
void swap(int&, int&);
void printRound(int);
void makemove(int, int[][3], int[], int, int);
void print(string const msg, int optnum = -1);

//I've commented out some code so it compiles slowly uncomment the code as you complete it.

//Main
int main(int argc, char *argv[]){ //DO NOT  DECLARE ANY ADDITIONAL VARIABLES!
//This is where I'm at.
const int GRIDX = 3;
    const int GRIDY = 3;
    const int COORDINATE = 2;
    int grid[GRIDY][GRIDX];
    int blank[COORDINATE] = {2, 2};
    initGrid();
    cout << grid << endl;


    return 0;
}

//Functions   
void initGrid(){
    int grid[3][3] = {{1,2,3},{4,5},{6,7,8}};
}


Last edited on
I'm not sure what exactly you want, but maybe something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Global constant
const int GRIDSIZE = 3;

// Initialize grid to solved position.
void initGrid(int grid[][GRIDSIZE]) {
    for (int r = 0; r < GRIDSIZE; ++r)
        for (int c = 0; c < GRIDSIZE; ++c)
            grid[r][c] = r * GRIDSIZE + c + 1;
    grid[GRIDSIZE-1][GRIDSIZE-1] = 0;
}

void printGrid(const int grid[][GRIDSIZE]) {
    for (int r = 0; r < GRIDSIZE; ++r) {
        for (int c = 0; c < GRIDSIZE; ++c)
            std::cout << grid[r][c] << ' ';
        std::cout << '\n';
    }
}


I think the initGrid function is supposed to create a solved grid and the randomizeGrid function is supposed to randomize it.
Last edited on
@tpb Thank you very much for taking the time. IS GREATLY APPRECIATED!!!

Yes, your assumption is correct. I'm just finding hard to implement another function without first being able to display the 2d array with some anything in it. for example:
./a.out
123
456
78
After i manage to come up with this I think it should be more approachable to solve for the other functions one at a time. Like randomize the numbers using srand(time(NULL)) etc.. But I'm not there yet, for reason Im having a lot of trouble seeing the path to get the array to display.

Bellow is the entire skeleton i'm obligated to work with so you can have a better understanding of where i'm trying to go with printing the array first.
#include<iostream> //cin / cout
#include<time.h> //for seeding rand
#include<string> //In case we use strings
#include<stdio.h> //For getchar
#include<stdlib.h> //For Ssrand
#include<ios> //For <streamsize>
#include<limits> //For numeric_limits

using namespace std; //So that we don't have to do std::cout instead of cout

//Defines
#define EMPTY -1 //To show where blank is
#define UP 0 //For directions allowed
#define DOWN 1
#define LEFT 2
#define RIGHT 3
#define Y 1 //For Coordinates
#define X 0

//NO GLOBAL VARIABLES OR GLOBAL CONSTANTS ALLOWED. IF YOU USE ONE YOU WILL LOSE 50% OF THE GRADE

//Your Code Here: I have intentionally removed most of the parameters to the function prototypes and function definitions.
//You must figure out what function needs what and add it back in.
//Similarly in the main function I have removed most of the actual parameters passed to the functions so add those back in.
//You are not allowed to declare any additional variables inside the main function. If you declare any you will lose 50% of the grade.
//Several Parts of the code are temporarily commented out. Uncomment them as you add back the correct code. You will notice compilation errors
//As you uncomment the code. This is normal as code is missing, once you add it in all will be fine.


//Function Prototypes:
void initRand();
void initGrid();
bool argCheck(int argc, int);
int randomchoice();
void randomizeGrid(int iterations);
int getDifficulty(int argc, char *argv[]);
int getRoundCnt();
void clearScreen();
void printGrid();
bool checkWin();
bool checkMaxRounds(int, int);
void getOptions();
void printAvailableOptions(bool[]);
int readchoice(bool[]);
void swap(int&, int&);
void printRound(int);
void makemove(int, int[][3], int[], int, int);
void print(string const msg, int optnum = -1);

//I've commented out some code so it compiles slowly uncomment the code as you complete it.

//Main
int main(int argc, char *argv[]){ //DO NOT DECLARE ANY ADDITIONAL VARIABLES!
const int GRIDX = 3; //Dimensions of Puzzle
const int GRIDY = 3;
const int COORDINATE = 2;
int grid[GRIDY][GRIDX]; //Grid Size
int blank[COORDINATE] = {2,2};
initRand(); //Initialize srand
initGrid(/*Your Code Here*/); //Initialize Grid to 123,456, 78_
argCheck(argc, 3); //Check that we have 3 arguments
randomizeGrid(/*Your Code Here*/getDifficulty(argc, argv)); //Mix it up randomly n number of times (3rd argument)
/* //Uncomment this as you complete the assignment.
for(int round = 0; round<getRoundCnt(argc, argv); round++){ //Loop a max number of rounds passed in 2nd argument
clearScreen(); //Clear the screen to re-draw each time
printGrid(grid, GRIDY, GRIDX); //print the status of puzzle
if(checkWin(grid, GRIDY, GRIDX) /* Check if we reached limit */
/* || checkMaxRounds(round, getRoundCnt(argc, argv))) break; //or if we have solved Puzzle. In either case. Finish.
//Attempt to Solve:
bool direction[4] = {0,0,0,0}; //stores which moves are allowed
getOptions(direction, blank, GRIDY, GRIDX); //Find out which moves are allowed
printAvailableOptions(direction); //Print out our available moves
printRound(round); //Prints Current Round
makemove(readchoice(direction), grid, blank, GRIDY, GRIDX); //Read user input and make the move
}
*/
print("Game Over!\n"); //Simple Print that prints game over.
return 0;
}

//Don't forget to document your functions according to guidelines!
//Functions:
void initRand(){
srand(time(NULL)); //Comment out to always have the same random digits for debugging
}

void initGrid(){
//Your Code Here
}

bool argCheck(int argc, int expected){
if(argc != expected){
print("Usage: Executable Rounds Difficulty\nExample: ./a.out 30 10\n");
exit(EXIT_FAILURE);
return 1;
}
}

int randomchoice(){
//Your Code Here
}

void randomizeGrid(int iterations){
//Your Code Here
//You Must call the following functions here:
//getOptions(direction, blank, GRIDY, GRIDX);
//makemove(randomchoice(direction), grid, blank, GRIDY, GRIDX);
//}
}

int getDifficulty(int argc, char *argv[]){
return strtol(argv[2], NULL, 10); //Number of Rounds to Play
}

int getRoundCnt(){
//Your Code Here
}

void clearScreen(){
cout << "\033c" << flush;
cout << "The Magic Square!"<< endl;
}

void printGrid(){
//Print Grid as a nice box
//Your Code Here
}

bool checkWin(){
//win?
bool win = true;
//Your Code Here
if(win){
cout << " Congratulations! You Win!" << endl;
cout << flush;
return true;
}
else
return false;
}

bool checkMaxRounds(int round, int roundcount){
if(round >= roundcount-1){
cout << " Round Limit Reached. You lose, General Kenobi!" << endl;
cout << flush;
return true;
}
else return false;
}

void getOptions(){
//direction[UP] = blank[Y] < GRIDY-1;
//Your Code Here
}

void printAvailableOptions(bool direction[]){
//Your Code Here
// print(string(" ")+"Available Options: ", optionTotal);
if(direction[UP]) print("Down ") ;
//Your Code Here
}

int readchoice(bool direction[]){
//Only Accept Valid Choices. Ignore Invalid Choices.
/*
int choice;
do{
if (getchar() == '\033') { // if the first value is esc
getchar(); // skip the [
switch(getchar()) { // the real value
case 'B':
choice = UP;
break;
case 'A':
choice = DOWN;
break;
case 'C':
//Your Code Here
break;
case 'D':
//Your Code Here
break;
}
}
}while(!direction[choice]);
cin.ignore(numeric_limits<streamsize>::max(),'\n');//Will Discard useless input
return choice;
*/
}

void swap(int &a, int &b){
//Your Code Here
}

void printRound(int round){
print("Round: ");
print("\n", round);
}

//Your move General Kenobi!
void makemove(int choice, int grid[][3], int blank[], int GRIDY, int GRIDX){
int cX= blank[X];
int cY= blank[Y];
int nX= blank[X];
int nY= blank[Y];

switch(choice){
case UP: cout << "CHANGING DOWN "; // because 0,0 is top left
nX = blank[X];
nY = blank[Y] + 1;
break;
//Your Code Here
}
//Your Code Here
//Call swap function here

blank[X] = nX;
blank[Y] = nY;
}

void print(string const msg, int optnum){
if(optnum == -1)
cout << msg << flush;
else
cout << optnum << msg << flush;
}
Last edited on
> I was given a skeleton code to follow by implementing functions. LOTS of them!
Have you ever written a complete program by yourself, or has your "tutor" always given you these "colour by numbers" assignments?

Sure, it's easy work for the tutor to mark, but it's not helping you stand on your own feet at all.

Your "how to print a 2D array" question leaves a worryingly large gap between what you have been given and the amount of code needed to complete this assignment.

Also, if you're meant to be learning C++ then your tutor is making a very bad job of it. It's just C with a bit of C++ I/O and strings thrown in.
thank you for the response Salem. Yes, I'm currently enrolled in a C++ course don't have much to say about my Professor's C++ abilities since I'm trying to learn right now other than he seems to be a very nice guy. I have written code before in previous assignments but haven't got a chance to really practice 2D arrays and functions. They are all new subjects in the course and he tends to give us some hard assignments to my perception for some reason or may be I'm just not that good at writing code as I thought i could become.
I would recommend to practice 2D arrays first in a separate project.
Start with the usual stuff. Filling it with values, printing, maybe getting sum of rows/cols and finally sorting. I hope you have a good textbook, otherwise you have to rely on google.
Good Morning, this is where I'm at right now. Been hitting a wall for the last couple of hours. So I started by displaying the 2D array with a blank space which I made possible with the help of tpb earlier. Then I moved to trying to get to move the numbers around but somehow after trying to implement some of the functions. I'm leaving everything that has to do with the random number generation part for last since I feel it will be even easier to get lost if enabling that part of the code. What do you guys think I should change in order to keep making progress? Thank for your help and time to everyone.

#include<iostream>
#include<time.h> //for seeding rand
#include<string> //In case we use strings
#include<stdio.h> //For getchar
#include<stdlib.h> //For Ssrand
#include<ios> //For <streamsize>
#include<limits> //For numeric_limits

using namespace std; //To skip writting std::cout instead of cout

#define EMPTY -1 //To show where blank is
#define UP 0 //For directions allowed
#define DOWN 1
#define LEFT 2
#define RIGHT 3
#define Y 1 //For Coordinates
#define X 0

// Function Prototypes
void initRand();
void initGrid();
void printGrid();
int getDifficulty(int argc, char *argv[]);
bool argCheck(int argc, int expected);
void getOptions();
void swap(int &a, int &b);
int readchoice(bool direction[]);
void makemove(int choice, int grid[][3], int blank[], int GRIDY, int GRIDX);
void printAvailableOptions(bool direction[]);

// MAIN
int main(int argc, char *argv[]){
const int GRIDX = 3; //Dimensions of Puzzle
const int GRIDY = 3;
const int COORDINATE = 2;
int grid[GRIDY][GRIDX]; //Grid Size
int blank[COORDINATE] = {2,2};
initRand(); //Initialize srand
initGrid(); //Initialized grid to 123,456, 78_
printGrid();
argCheck(argc, 3); //Checks that we have 3 arguments


return 0;
}
// FUNCTIONS
//done
void initRand(){

// srand (time(NULL)); Commented out for debugging porpuses

}
//done
void initGrid(){

int grid[3][3];

for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
grid[i][j] = i * 3 + j + 1;
grid[3-1][3-1] = 0;

}
//done
void printGrid(){
int grid[3][3];
for (int i = 0; i < 3; ++i){
for (int j = 0; j < 3; ++j){
if (grid[i][j] != 0)
cout << grid[i][j];
else
cout << " ";

}
cout << endl;
}
}
//needs revision
void printAvailableOptions(bool direction[4]){
//Your Code Here
// print(string(" ")+"Available Options: ", optionTotal);
if(direction[UP])
cout << "Down ";
else if (direction[DOWN])
cout <<"Up";
else if (direction[RIGHT])
cout << "Left";
else if (direction[LEFT])
cout << "Right";

}
//needs revision
int readchoice(bool direction[]){
//Only Accept Valid Choices. Ignore Invalid Choices.

int choice;
do{
if (getchar() == '\033') { // if the first value is esc
getchar(); // skip the [
switch(getchar()) { // the real value
case 'B':
choice = UP;
break;
case 'A':
choice = DOWN;
break;
case 'C':
choice = LEFT;
break;
case 'D':
choice = RIGHT;
break;
}
}
}while(!direction[choice]);
cin.ignore(numeric_limits<streamsize>::max(),'\n');//Will Discard useless input
return choice;

}
//done
bool argCheck(int argc, int expected){

if(argc != expected){
cout << "Usage: Executable Rounds Difficulty\nExample: ./a.out 30 10\n";
exit(EXIT_FAILURE);
return 1;
}

}
// done
int getDifficulty(int argc, char *argv[]){

return strtol(argv[2], NULL, 10);

}
//needs revision
void getOptions(bool direction[]){
int blank[4];
int GRIDX;
int GRIDY;

direction[UP] = blank[Y] < 0;
direction[DOWN] = blank[Y] < 1;
direction[LEFT] = blank[X] < 2;
direction[RIGHT] = blank[X] < 3;
}
//done
void swap(int &a, int &b){
int tmp;

tmp = a;
a = b;
b = tmp;

}
//needs revision
void makemove(int choice, int grid[][3], int blank[4], int GRIDY, int GRIDX){
int cX= blank[X];
int cY= blank[Y];
int nX= blank[X];
int nY= blank[Y];

switch(choice){
case UP: cout << "CHANGING DOWN "; // because 0,0 is top left
nX = blank[X] + 0;
nY = blank[Y] + 1;
break;
case DOWN:
nX = blank[X] + 0;
nY = blank[Y] - 1;
break;
case LEFT:
nX = blank[X] - 1;
nY = blank[Y] + 0;
break;
case RIGHT:
nX = blank[X] + 1;
nY = blank[Y] + 0;

}
//Your Code here
swap(GRIDX, nX);
swap(GRIDY, nY);

blank[X] = nX;
blank[Y] = nY;
}
//done
void print(string const msg, int optnum){
if(optnum == -1)
cout << msg << flush;
else
cout << optnum << msg << flush;
}
Last edited on
Topic archived. No new replies allowed.