B11 Answer


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

/* Puzzle B11 -- generate and print N random characters 'a' .. 'z' */

/* Generate a random integer  min <= r <= max */
int randInt(int min, int max)
{
  return rand() % (max - min + 1) + min;
}

/* Generate a random character  'a' .. 'z' */
char randChar()
{
  return 'a' + randInt(0, 25);
}

const int limit = 500;   /* number of characters to generate */

const int groupSize = 6; /* five random chars, followed by a space */
const int lineSize = 60; /* must be N*groupsize */

int main(int argc, char *argv[])
{
  int j, pos;
  char line[lineSize + 1]; /* +1 for the null terminator */

  srand(time(NULL));
  pos = 0;
  for (j = 0; j < limit; j++)
  {
    line[pos] = randChar();
    pos++;

    if (pos == lineSize-1)
    {
      line[lineSize-1] = (char)0;
      printf("%s\n", line);
      pos = 0;
    }
    else if (pos%groupSize == groupSize - 1)
    {
      line[pos] = ' ';
      pos++;
    }

  }

  /* deal with the last, possibly incomplete line */
  if (pos != 0)
  {
    line[pos] = (char)0;
    printf("%s\n", line);
  }

  printf("\n");
  system("pause");
  return 0;
}

Comments: ASCII-coded characters are actually small integers. So to generate characters in the range 'a' .. 'z', generate a random integer in the range 0..25 and add it to 'a'. For this to work, the integers for the characters 'a' .. 'z' must follow in order, which they do.

The output portion of the above program buffers an entire line of characters before it is output. This may be more bother than it is worth, although on my computer a simpler version of the program takes 10 times longer to run. The simpler version of the program uses putchar() for each character, but uses it 60 times per line:

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

/* Puzzle B11alt -- generate and print N random characters 'a' .. 'z' */

/* Generate a random integer  min <= r <= max */
int randInt( int min, int max )
{
  return rand()%(max-min+1) + min ;
}

/* Generate a random character  'a' .. 'z' */
char randChar()
{
  return 'a' + randInt(0, 25) ;
}

const int limit = 50000 ; /* number of characters to generate */

const int groupSize = 6; /* number of characters in a printed group */
const int lineSize = 60; /* generated characters per line */
                         /* (not counting spaces between groups */

int main(int argc, char *argv[])
{
  int ch;
  int j ;

  srand( time(NULL) );

  for ( j=0; j < limit; j++ )
  {
    ch = randChar();
    putchar( ch );

    if ( j%lineSize == lineSize-1 )
      putchar('\n');

    else if ( j%groupSize == groupSize-1 )
      putchar(' ');
  }

  printf("\n");
  system("pause");  
  return 0;
}  
 

back