random number

How to store 0 to 25 number randomly in 5x5 array.Can u teach me how to do it


Last edited on
How to get random numbers between 0 - 25 and store them in an array:
1
2
3
4
int myArray[10];

for (int i = 0; i < 10; ++i)
    myArray = rand() % 26;


How to get the numbers 0-25 shuffled randomly:
1
2
3
4
5
6
int myArray[26];

for (int i = 0; i < 26; ++i)
    myArray[i] = i;

std::random_shuffle( myArray, myArray + 26 );




rand() comes from <cstdlib>
std::random_shuffle() comes from <algorithm>
Last edited on
How to get it for 5x5 array...
well you could just copy it over...

1
2
3
4
int fiveByfive[25][25];
for (int i = 0; i <5; ++i)
  for (int j = 0; j < 5; ++j)
    fiveByfive[i][j] = myArray[i * 5 + j ];


standard utilities are not really meant for multi-dimensional arrays because they are not the most efficient means of doing... anything.
Last edited on
closed account (D80DSL3A)
nvm. OP has abandoned the thread.
Last edited on
I advice against that as it's hackish. ;-P
closed account (D80DSL3A)
@Josue. Care to suggest a better method?
What do you find to be 'hackish' about it? Just curious.
Last edited on
You're writing random numbers into the array; there's no need to shuffle them. However, if you insist on shuffling them, here's what I believe to be the best way to achieve this:

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
#include <iomanip>
#include <cstdlib>

int main()
{
    /***********************************
     * Write into and print the array. *
     ***********************************/

    const int size = 5, range = 25;

    int array[size][size];

    srand(time(NULL));

    for (int i = 0; i < size; ++i)
    {
        for (int j = 0; j < size; ++j)
        {
            array[i][j] = rand() % (range + 1);
        }
    }

    for (int i = 0; i < size; ++i)
    {
        for (int j = 0; j < size; ++j)
        {
            std::cout << std::setw(2) << array[i][j] << ' ';
        }

        std::cout << std::endl;
    }

    std::cout << std::endl;

    /********************************
     * Shuffle and print the array. *
     ********************************/

    for (int i = 0; i < size; ++i)
    {
        for (int j = 0; j < size; ++j)
        {
            int it = rand() % size, jt = rand() % size;
            int temp = array[it][jt];
            array[it][jt] = array[i][j];
            array[i][j] = temp;
        }
    }

    for (int i = 0; i < size; ++i)
    {
        for (int j = 0; j < size; ++j)
        {
            std::cout << std::setw(2) << array[i][j] << ' ';
        }

        std::cout << std::endl;
    }

    return 0;
}
Topic archived. No new replies allowed.