My 7 Bag Shuffle

 avatar
unknown
c_cpp
2 months ago
1.0 kB
3
Indexable
// Function to shuffle the bag of Tetrominoes
void shuffle_bag(Tetromino bag[], int n)
{
    // Temporary array to hold one set of Tetrominoes
    Tetromino temp_bag[NUM_TETROMINOES];
   
    // Seed the random number generator
    srand(time(0));

    // Fill the bag n times, where n is the number of pieces you need
    for (int set = 0; set < n / NUM_TETROMINOES; ++set) {
        // Fill temp_bag with one of each Tetromino
        for (int i = 0; i < NUM_TETROMINOES; ++i) {
            temp_bag[i] = bag[i];
        }

        // Shuffle temp_bag using the Fisher-Yates algorithm
        for (int i = NUM_TETROMINOES - 1; i > 0; --i) {
            int j = rand() % (i + 1);
            Tetromino temp = temp_bag[i];
            temp_bag[i] = temp_bag[j];
            temp_bag[j] = temp;
        }

        // Place shuffled set into the main bag array
        for (int i = 0; i < NUM_TETROMINOES; ++i) {
            bag[set * NUM_TETROMINOES + i] = temp_bag[i];
        }
    }
}
Leave a Comment