lundi 25 janvier 2016

Proper use of rand()?

So the idea with this is that it takes in the 9x9 array that's in main, and swaps around rows. It can only swap rows 1-3 with 1-3, 4-6 with 4-6 and 7-9 with 7-9. For some reason every once in awhile it will swap one from 4-6 with one from 7-9, and also sometimes it will give me absolute garbage for one of the rows 7-9. I've spent the better part of 2 hours trying to figure out the proper way to use rand() in this context and I am sure I am not doing it correctly. Any ideas?

#include <iostream>
#include <time.h>
#include <stdlib.h>

using namespace std;

void printSudoku(int square[9][9]) // Prints out the 9x9 array
{
    for(int i = 0; i < 9; i++)
    {
        for(int j = 0; j < 9; j++)
        {
            cout << square[i][j];
        }
        cout << endl;
    }
}

void swapRows(int square[9][9]) // Randomly generates numbers, within bounds, and swaps those rows with each other
{
    int temp[1][9];
    srand(time(NULL));
    int n = (rand() % 2) + 0;
    int m = (rand() % 2) + 0;
    for(int i = 0; i < 9; i++)
    {
        temp[0][i] = square[n][i];
    }
    for(int j = 0; j < 9; j++)
    {
        square[n][j] = square[m][j];
    }
    for(int k = 0; k < 9; k++)
    {
        square[m][k] = temp[0][k];
    }
    int a = (rand() % 5) + 3;
    int b = (rand() % 5) + 3;
    for(int i = 0; i < 9; i++)
    {
        temp[0][i] = square[a][i];
    }
    for(int j = 0; j < 9; j++)
    {
        square[a][j] = square[b][j];
    }
    for(int k = 0; k < 9; k++)
    {
        square[b][k] = temp[0][k];
    }
    int c = (rand() % 8) + 6;
    int d = (rand() % 8) + 6;
    for(int i = 0; i < 9; i++)
    {
        temp[0][i] = square[c][i];
    }
    for(int j = 0; j < 9; j++)
    {
        square[c][j] = square[d][j];
    }
    for(int k = 0; k < 9; k++)
    {
        square[d][k] = temp[0][k];
    }
}


int main() {
int square[9][9] = {1,2,3,4,5,6,7,8,9,
                    4,5,6,7,8,9,1,2,3,
                    7,8,9,1,2,3,4,5,6,
                    2,3,4,5,6,7,8,9,1,
                    5,6,7,8,9,1,2,3,4,
                    8,9,1,2,3,4,5,6,7,
                    3,4,5,6,7,8,9,1,2,
                    6,7,8,9,1,2,3,4,5,
                    9,1,2,3,4,5,6,7,8,};
printSudoku(square);
swapRows(square);
cout << endl;
printSudoku(square);
    return 0;
}




Aucun commentaire:

Enregistrer un commentaire