Q Write a program in C to generate m random integers from an
Q) Write a program in C to generate m random integers from an array of size n, such that the probability of selecting even elements is twice that of odd elements. The same element may be selected multiple times. As an example, let n = 100 and m = 30. Read in the array elements from the provided data file ArrayInp.dat, using the fscanf() function. Utilize the function rand() to generate a pseudo random number and the function srand() to seed the random number generator. Fill in the above program please.
Where ArrayInp.dat is just random numbers
Solution
I am assuming even element means element at the even position and odd element means element at an odd position.
we will take %3 if and is even that is 0 or 2 then even element else answer is an odd element.and inside the loop, we will use rand again to get the position of an element by taking modulo by n.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, n,m;
time_t t;
FILE *fp;
fp = fopen(\"ArrayInp.dat\", \"r\");
srand((unsigned) time(&t));
fscanf(fp, \"%s\",n );
fscanf(fp, \"%s\",m);
int ans[m];
int arr[n];
fgets(arr, n, (FILE*)fp);
for( i = 0 ; i < m ; i++ )
{
int x=rand()%3;
if(x==0||x==2){
x=rand()%n;
if(x%2==0){
ans[i]=arr[x];
}
else{
ans[i]=arr[x-1];
}
}
else{
x=rand()%n;
if(x%2==1){
ans[i]=arr[x];
}
else{
ans[i]=arr[1];
}
}
}
fclose(fp);
return(0);
}

