Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

3. Write a program to generate m random integers from an array of size n, such t

ID: 3735619 • Letter: 3

Question

3. Write a program to generate m random integers from an array of size n, such that the prob- ability of selecting even indexed elements is twice that of odd indexed 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 func- tion. Utilize the function rand to generate a pseudo random number and the function srand ) to seed the random number generator. Start with the code RandomArrayGen- erate.c provided on the Blackboard. An example on generating random numbers in a given range can be found at the link http ://www.cplusplus.com/reference/cstdlib/rand,

Explanation / Answer

#include<stdio.h>
#include <stdlib.h>  
#include <time.h>

int main()
{

int randomgeneratorArray[1000];
int n = 100;
int m = 300;
int i=0;
FILE *fp;

fp = fopen("ArrayInp.dat", "r+") ;

printf("numbers in random number list ");
while(fscanf(fp,"%d",&randomgeneratorArray[i]) == 1)
{
       printf("%d ",randomgeneratorArray[i]);
       i++;
}

n = i;

printf(" random number generated m = %d ",m);

srand (time(NULL));

for(int i=0;i<m;i++)
{
   int number = 0;

   int p = rand() % 3 + 1;

   int isodd = 0;

   if(p <=2) isodd = 0;
   else isodd = 1;

   int index = rand() % (n/2) ;

   if(isodd == 1)
      {
          number = randomgeneratorArray[2*index + 1];
      }
   else number = randomgeneratorArray[2*index];

   printf("%d ",number);


}


return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote