Filling of Randomly Generated Unique Values in 1D Array in C++.
//Generate Unique Random Values and Store in Array.
#include<iostream>
#include<iomanip>
#include<time.h>
#include<stdlib.h>
using namespace std;
int generateRandom(int a[], int n)
{
int min, max, rng, i, j, k, tmp, flag;
cout<<"Enter Value range to be stored in array\n";
cout<<"Enter Minimum Number: "; cin>>min;
cout<<"Enter Maximum Number: "; cin>>max;
rng=max-min+1;
if(rng<n)
{
cout<<"Your Array size is:"<<n<<" and your number range is: "<<rng
<<"\nFilling of Unique values in array is not possible...\n";
return 0;
}
srand((unsigned)time(NULL));
for(i=0,j=0;j<n;i++)
{
tmp=rand()%rng+min;
if(i==0)
a[j++]=tmp;
flag=0;
for(k=0;k<j;k++)
{
if(a[k]==tmp)
flag++;
}
if(flag==0)
a[j++]=tmp;
}
//Printing of array
cout<<endl<<endl;
for(i=0;i<n;i++)
{
cout<<setw(4)<<a[i];
}
cout<<endl;
return 0;
}
int main()
{
int n;
cout<<"Enter Size of Array: ";
cin>>n;
int arr[n];
generateRandom(arr,n);
return 0;
}
Watch Video for Explanation
No comments
Post your comments