0

Here's the part of the program I'm having problems with:

// precondition: board is initialized
// postcondition: board is shuffled by randomly swapping 20 values
void shuffle(int board[][NCOLS]) {
    int num = rand();
    num = num %6 + 1;
    for (int i = 0; i < 20; i++) {

    }
}

Pretty sure I have it wrong already, I think I may need the rand function but I'm not sure how the for loop would work.

Basically there are 6 pictures and they're in 4 columns, it's a memory game and as of the moment they stay in the same place. I need to make it so that they are random and flipped on the side where you can't see them but I can't figure it out.

I have no idea how to randomize columns especially when they're under the name of simply board and NCOLS.

2

1 Answer 1

2

I can see why this is hard - random_shuffle prefers 1D arrays, and you have a 2D array. Luckily, since arrays are contiguous, that means a 2D array can also be accessed as a 1D array - it's just NCOLS x NROWS elements in memory:

auto begin = &(board[0][0]);
auto end   = begin + NCOLS*NROWS;
Sign up to request clarification or add additional context in comments.

4 Comments

Where would I put that though MSalters? I'm sorry, I'm a bit new to programming, I'm taking just an introductory course to see how it is. To initalize it i would just do shuffle(board); as well right? but do i put that in the for loop? it doesn't seem to do anything
Well, random_suffle already loops for you. It just needs to know which elements it needs to shuffle, so the code above goes right before the call to random_shuffle. Look at Igor Tandetnik's comment, he already linked to the appropriate documentation.
How do I use random_shuffle in this situation? So far what i made doesn't work and looks like this: random_shuffle(board.begin(), board.end()); which only give the error that board needs a class type
@Nick: That error is precisely why I provided you with the two statements above. Since you're using a primitive type (not a class type), you don't have the convenient object.begin() syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.