C10 Answer


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

/* Puzzle C10 -- fill an array with an ascending sequence of random doubles,
   with an average step size of avg, and a max deviation of dev */

double randDoubleRange( double min, double max );
int randInt( int min, int max );

/* Find a value x which will be added to an array
|  element to get the next element. x is contained
|  in the open interval:
|  (avg-dev)< x < (avg+dev)
|
|  That this is an open inteveral on both sides
|  causes some problems, since randDoubleRange(min, max)
|  might return exactly min.
*/
double stepSize (double avg, double dev )
{
  double diff;

  /* get a value 0.0 <= diff < dev */
  diff = randDoubleRange( 0.0, dev );

  /* flip a coin to make it positive or negative */
  if ( randInt(0,1) == 0 )
    diff = -diff;

  return avg+diff;
}

void fillDoubleArrayRandomAscending( double arr[],
          int size, double avg, double dev )
{
  int j;
  arr[0] = stepSize( avg, dev );

  for ( j=1; j<size; j++ )
    arr[j] = arr[j-1] + stepSize( avg, dev );
}

double randDoubleRange( double min, double max )
{
  return (rand()*(max-min))/(RAND_MAX+1) + min;
}

int randInt( int min, int max )
{
  return (rand()*(max-min+1))/(RAND_MAX+1) + min ;
}

void printArrayDouble( double arr[], int size )
{
  const int N = 5;
  int j;

  for ( j=0; j<size; j++ )
  {
    if ( j%N == N-1 )
      printf("%8.4lf\n", arr[j] );
    else
      printf("%8.4lf ", arr[j] );
  }
}

int main(int argc, char *argv[])
{
  const int SIZE = 50;
  double x[ SIZE ];
  
  srand( time(NULL) );
  fillDoubleArrayRandomAscending( x, SIZE, 1.0, 1.5 );
  printArrayDouble( x, SIZE );
    
  printf("\n");
  system("PAUSE");	
  return 0;
}