Filling a matrix

I have a n×n matrix;
All elements of this matrix is 0;
I want to fill this matrix with n numbers of 1;
One state for n=4 is below:
0 1 0 0
1 0 0 0
0 0 0 1
0 0 1 0
How can I have all states such that in any rows
or columns just one number of 1 would have existed.
I work with visual basic 2o17 and want to do this with one library(iostream).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <chrono>
#include <random>
using namespace std;

int main()
{
   int N = 4;

   vector<vector<int>> matrix( N, vector<int>( N, 0 ) );                       // Initialise matrix to 0

   vector<int> choice( N );
   for ( int i = 0; i < N; i++ ) choice[i] = i;                                // choice[i] will hold the non-zero column in the ith row
   unsigned seed = chrono::system_clock::now().time_since_epoch().count();
   shuffle( choice.begin(), choice.end(), default_random_engine( seed ) );     // Give it a shuffle

   for ( int i = 0; i < N; i++ ) matrix[i][choice[i]] = 1;                     // Put the 1s in the matrix

   for ( int i = 0; i < N; i++ )
   {
      for ( int j = 0; j < N; j++ ) cout << setw(2) << matrix[i][j];
      cout << '\n';
   }
}


 0 0 1 0
 0 1 0 0
 0 0 0 1
 1 0 0 0
Last edited on
Thank, it,s so good;
But it has repeating operation;
I want to have number of this operation.
But it has repeating operation;
I want to have number of this operation.


I'm not sure that I understand what you are asking, Morapoly.

If you want all 4! = 24 possibilities then use next_permutation on choice, instead of shuffling it. The number of possibilities will go up very rapidly with the size of the matrix, though.
Last edited on
Topic archived. No new replies allowed.