i need help aboutmaking matrix array

hi guys.

i need a array like 'int array[10][10];'

this array will contain 1 to 100 numbers. every number must just 1 time used (control will make with another function) and made with rand() function. i tried to use recursive function but i couldnt. can anybody help me?


recursion is usually just a confusing way to write a loop.

100 is small enough that while idiotic, you can brute force it..
roughly ...

int get_value()
{
static char used[101] = {0};
int r = 0;
while(used[r] == 0)
r = rand()%100+1;
used[r] = 1;
return r;
}

for(x = 0; x < 10; x++)
for(y = 0; y < 10; y++)
array[x][y] = get_value();

can you do it cleaner though? It will start to act up when there are less than 10 numbers left in the pool as it tries to randomly roll the last one a half billion times or something.
Last edited on
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
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <iterator>
#include <numeric>
#include <random>
#include <algorithm>
#include <iomanip>

int main()
{
    const std::size_t N = 10 ;
    int array[N][N] {} ;

    // http://en.cppreference.com/w/cpp/iterator/begin
    // http://en.cppreference.com/w/cpp/iterator/end
    // http://www.stroustrup.com/C++11FAQ.html#auto
    const auto begin = std::begin( array[0] ) ; // iterator (pointer) to first number
    const auto end = std::end( array[N-1] ) ; // iterator (pointer) to end of sequence

    // fill array with numbers 1 ... NxN
    // http://en.cppreference.com/w/cpp/algorithm/iota
    std::iota( begin, end, 1 ) ;

    // randomly shuffle the numbers in the array
    // http://en.cppreference.com/w/cpp/algorithm/random_shuffle
    // http://en.cppreference.com/w/cpp/numeric/random
    std::shuffle( begin, end, std::mt19937( std::random_device{}() ) ) ;

    // print the array
    // http://www.stroustrup.com/C++11FAQ.html#for
    for( const auto& row : array ) // for each row in the array
    {
        // print each integer in the row
        for( int v : row ) std::cout << std::setw(4) << v ;
        std::cout << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/4c9abac5fa9abbf4
Registered users can post here. Sign in or register to post.