Answer DA9

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

/* Puzzle D09 -- fill an array with an ascending sequence of random integers  */
int randInt( int min, int max );

void fillArrayRandomAscending( int size, int arr[], int maxStep )
{
  int j;
  arr[0] = randInt( 0, maxStep-1 );

  for ( j=1; j<size; j++ )
    arr[j] = arr[j-1] + randInt( 1, maxStep );
}

void printArray( int size, int arr[])
{
  const int N = 10;
  int j;
  
  for ( j=0; j<size; j++ )
  {
    if ( j%N == N-1 )
      printf("%4d\n", arr[j] );
    else
      printf("%4d ", arr[j] );    
  }
}

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

int main(int argc, char *argv[])
{
  const int SIZE = 100;
  int x[ SIZE ];
  
  srand( time(NULL) );
  fillArrayRandomAscending( SIZE, x, 10 );
  printArray( SIZE, x );
    
  printf("\n");
  return 0;
}

Comments: It might sometimes be useful to fill an array with a sequence of integers that mostly goes upward. The following function could be used for that, if you set minStep to a negative value:
void fillArrayRandomSequence( int size, int arr[], int minStep, int maxStep )
{
  int j;
  arr[0] = randInt( 0, maxStep );

  for ( j=1; j<size; j++ )
    arr[j] = arr[j-1] + randInt( minStep, maxStep );
}


Back to Puzzle Home