PDA

View Full Version : Random در آرایه



دیابلو
یک شنبه 16 آذر 1393, 19:26 عصر
سلام کسی می دونه Random در آرایه چه طوری تعریف می شه ؟ منظورم اینه وقتی می خوایم در یک آرایه دو بعدی خونه ها به صورت تصادفی انتخاب بشه چه کار باید کرد؟

ashkufaraz
یک شنبه 16 آذر 1393, 20:07 عصر
از این استفاده کن

randomElement = arr[rand() % ARRAY_SIZE];

rahnema1
یک شنبه 16 آذر 1393, 21:29 عصر
سلام
از shuffle میشه استفاده کرد

#include <vector>
#include <chrono>
#include <algorithm>
#include <iostream>
int main()
{
const int n1 = 5;
const int n2 = 6;
int arr[n1][n2]= {{ 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}};

std::default_random_engine generator( std::chrono::system_clock::now( ).time_since_epoch( ).count());
std::vector<std::pair<int, int> > indexes;
for(int i = 0; i < n1; i++)
for(int j = 0; j < n2; j++)
indexes.push_back({i, j});
std::shuffle (indexes.begin(), indexes.end(), generator);

for (auto && i: indexes)
std::cout << arr[i.first][i.second] << std::endl;
}