0

Random Values

how to print the only same random value in array? #include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand(time(0)); int arr[8]; for(int i=0;i<8;i++){ int random =rand()%10; arr[i]=random ; cout << arr[i]; } return 0; } ex : if array 21417823 the output : 2,1

22nd Jan 2017, 1:05 PM
Sonny Michael
Sonny Michael - avatar
8 Réponses
+ 2
If their are few values (like for your array (8)) compared to the scale (for example from 0 to 100 000), then this one is better : int main(){ int arr[8]; int sum, j; srand(time(0)); for(int i=0;i<8;++i){ arr[i]=rand()%100000; } for(int i=0;i<8;++i){ sum=0; j=0; while(j<i && sum==0){ if(arr[j]==arr[i]){ ++sum; } ++j; } if(sum==0){ for(j=i;j<8;++j){ if(are[j]==arr[i]){ ++sum; } } if(sum>1){ cout<<arr[i]<<endl; } } } return 0; }
22nd Jan 2017, 2:26 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
If the values are on a small scale (like here, from 0 to 9), I think the best way would be this one : #include <vector> int main(){ int arr[8]; vector<int> v(10,0); srand(time(0)); for(int i=0;i<8;++i){ arr[i]=rand()%10; } for(int i=0;i<8;++i){ v[arr[i]]++; } for(int i=0;i<8;++i){ if(v[i]>1){ cout<<i<<endl; } } return 0; } You can fuse the two first for loops.
22nd Jan 2017, 2:17 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 1
vector (example : vector<int> v) as properties in common with array (example : int arr[8]) but you do not define a size for the vector, it will manage itself (not without a cost of memory and time of course, but on small samples like yours, you should not see the difference). You can add to vector without worrying of its max size (but as I said, the bigger it become, the more expensive it will be in memory and in time)
23rd Jan 2017, 7:25 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
can you give some examples of the result you want please?
22nd Jan 2017, 1:23 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
ex : if the result of random array {2,1,4,1,7,8,2,3} the output that i want is 2 and 1 bexause the values more than 1 so print it.
22nd Jan 2017, 1:56 PM
Sonny Michael
Sonny Michael - avatar
0
I.am sorry, what actually the function of vector ?
22nd Jan 2017, 11:55 PM
Sonny Michael
Sonny Michael - avatar
0
Vector is like an array, you can replace it
23rd Jan 2017, 6:48 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
0
still dont know yet, but btw thx, i will learn more about vector
23rd Jan 2017, 6:53 AM
Sonny Michael
Sonny Michael - avatar