+ 1

Random array in cpp

how to print values of random array where there's not print same value. ex : arr[]{a,b,c} -> make random func -> print out c,a,b(random)..

16th Jan 2017, 6:23 AM
Sonny Michael
Sonny Michael - avatar
10 Antworten
+ 7
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand(time(0)); char array[5] = {0, 1, 2, 3, 4}; for (int i = 0; i < 5; i++) { cout << array[rand() % 5] << " "; } return 0; } The above code may, however, print array of duplicate indexes. To overcome this issue, a slight tweak is required but I am lazy. =^=
16th Jan 2017, 9:12 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
Oh. I reread the question. Guess it means that I have to stop being lazy. // Functional code updated #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand(time(0)); int array[5] = {0, 1, 2, 3, 4}; int array2[5]; int i = 0; int j; int checker; bool ident; while (i < 5) { ident = false; checker = rand()%5; j = 0; while (j < 5) { if (checker == array2[j]) { ident = true; } } if (ident) { continue; } array2[i] = checker; i++; } for (int k = 0; k < 5; k++) { cout << array[array2[k]] << " "; } return 0; } // this way, the elements of array[] will not repeat.
16th Jan 2017, 10:58 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
Code playground shows 'time limit exceeded' for my code above but it works on desktop compiler. Nvm, I'll think of another way.
16th Jan 2017, 11:36 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
OK, this is a *much much moar* garbage-less alternate. However, your original array gets modified. Ntls, this can be easily overcame if needed. #include <iostream> #include <cstdlib> #include <ctime> #include <algorithm> using namespace std; int main() { srand(time(0)); int array[5] = {1,2,3,4,5}; for (int i = 0; i < 5; i++) { swap(array[rand() % 5], array[i]); } for (int j = 0; j < 5; j++) { cout << array[j] << " "; } return 0; }
16th Jan 2017, 11:43 AM
Hatsy Rei
Hatsy Rei - avatar
+ 6
So erm, are things working now lol. I've lost track.
16th Jan 2017, 11:44 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
i've wrte that code before, my question is how to print out diferent rndom array. that code still probably print out same value
16th Jan 2017, 10:41 AM
Sonny Michael
Sonny Michael - avatar
+ 1
nice thx.. how can u do that guys.. awesome
16th Jan 2017, 11:39 AM
Sonny Michael
Sonny Michael - avatar
0
no output from that code
16th Jan 2017, 11:17 AM
Sonny Michael
Sonny Michael - avatar
0
//trying too
16th Jan 2017, 11:19 AM
Sonny Michael
Sonny Michael - avatar
0
cool, but i dont know how line 16 work.. i think i should learn more about swap. thx a lot bro..
16th Jan 2017, 11:55 AM
Sonny Michael
Sonny Michael - avatar