przemieszanie tablicy

0

witam,mam taki program:

#include <iostream>
#include <algorithm>
#include <ctime>
#include <vector>

using namespace std;

int main()
{
    int n,x;
    cout<<"Podaj n: ";
    cin>>n;
    
    vector< vector<int> >tab(n,vector<int>(n));
    
    x=1;
    for(int i=0;i<n;i++)
    {
      for(int j=0;j<n;j++)
      {
              tab[i][j]=x;
              x++;
              }
              }


int s = sizeof (tab)/ sizeof (tab[0][0]);   

     srand(time(NULL));
     random_shuffle( &tab[0][0], &tab[0][0] + s);
  
    for(int a=0; a<n; a++)
    {
        for(int b=0; b<n; b++)
        {
           cout.width(2);
            cout << tab[a][b]<<" ";
        }
    cout << endl;
    }   
     
         cout<<endl<<endl;
        system("pause");
        return 0;
}

Chciałbym,żeby program przemieszał mi tablice składającą się z elementów od 1...n^2.Program miesza ale tylko pierwszy wiersz.Jak to powinno być zrobione?

0

Wzorując się na opisie random_shuffle:

void randomShuffleMatrix(vector< vector<int> > &matrix) {
     for (int i=0, n=matrix.size(); i<n; ++i) {
          for (int j=0, m=matrix[i].size(); j<m; ++j) {
              k = rand()%n;
              std::swap(matrix[i][j], matrix[k][rand()%matrix[k].size()]);
          }
     }
}
0

Nie testowane:

vector< vector<int> >::iterator it;
for (it=tab.begin(); it!=tab.end(); ++it)
  random_shuffle ( (*it).begin(),  (*it).end() );

1 użytkowników online, w tym zalogowanych: 0, gości: 1