Randomizing and Avoiding Overlap 2D Arrays

I have an 2D array that contains set values. I want to create two functions to randomize the values and avoid overlapping them. How would I go about it?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
char Gird[5][5] =
    {
      { -1, -1, -1, -1, 'G'},
      { -1, -1, -1, 'P', -1},
      { -1, 'W', -1, -1, -1},
      { -1, -1, 'P', -1, -1},
      { -1, -1, -1, -1, -1}
    };

//This is so wrong. 
int Random () {
    srand(time(NULL));
    WumpusWorld[5][5] = rand() % WumpusWorld[5][5];
    return WumpusWorld[5][5];
}


Please help and thank you.
Are you reassigning the values, or simply moving them around?
Just moving them around.
If you're just moving them around, you could just as easily create a buffer array that matches the dimensions of Gird (Grid?).

1
2
3
4
5
6
7
8
9
int i, j;
char Buf[5][5];
for(i=0;i<5;i++) {
   for(j=0;j<5;j++) {
      Buf[i][j] = Gird[i][j];
   }
}

//Code to move stuff goes here 


If you want to randomly move things, then you would have to limit your random numbers to the amount of directions your elements can move

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const int up = 0, down = 1, left = 2, right = 3;
int direction;
direction = rand() % 5;
switch(direction) {
   case 0:
      cout << "up!";
      break;
   case 1:
      cout << "down!";
      break;
   case 2:
      cout << "left!";
      break;
   case 3:
      cout << "right!";
      break;
}


I'll leave the code for actually moving them to you, but you have the tools to start! :)
Thank You very much. I'm trying to program the game Wumpus World. 2D Array and Functions, lots of fun. :(
Lol, well if you need more help let me know.
C++ has the handy functions random_shuffle() and shuffle(), which can help you randomize that array:

Also, note that -1 is not a particularly good value to assign a char, here's an example using '\0' instead:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <algorithm>
#include <ctime>
#include <cstdlib>
int main()
{
    std::srand((unsigned)std::time(NULL));

    char Grid[5][5] = {'G', 'P', 'W', 'P'};
    std::random_shuffle(&Grid[0][0], &Grid[0][0] + 5*5);

    for(int r = 0; r < 5; ++r)
    {
        for(int c = 0; c < 5; ++c)
            std::cout << (Grid[r][c] ? Grid[r][c] : '_') << ' ';
        std::cout << '\n';
    }
}

online demo: http://ideone.com/T4vV8Y
Last edited on
Topic archived. No new replies allowed.