+ 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)..
10 Respostas
+ 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. =^=
+ 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.
+ 6
Code playground shows 'time limit exceeded' for my code above but it works on desktop compiler. Nvm, I'll think of another way.
+ 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;
}
+ 6
So erm, are things working now lol. I've lost track.
+ 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
+ 1
nice thx.. how can u do that guys.. awesome
0
no output from that code
0
//trying too
0
cool, but i dont know how line 16 work.. i think i should learn more about swap. thx a lot bro..