Advertisement
aaaaaa123456789

JV Programming Challenges, week 1, problem 1

Nov 13th, 2013
83
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. unsigned getNumber(void);
  5. char * getLine(void);
  6.  
  7. int main (void) {
  8.   unsigned lineCount;
  9.   do {
  10.     printf("Enter number of lines (please enter a positive integer): ");
  11.     lineCount = getNumber();
  12.   } while (!lineCount);
  13.   char ** lines = malloc(lineCount * sizeof(char *));
  14.   unsigned line;
  15.   for (line = 0; line < lineCount; line ++)
  16.     lines[line] = getLine();
  17.   putchar('\n'); // leaving a blank line
  18.   unsigned remaining = lineCount;
  19.   unsigned column;
  20.   for (column = 0; remaining; column ++) {
  21.     for (line = 0; line < lineCount; line ++) {
  22.       if (!lines[line]) {
  23.         putchar(' '); // leave a space for padding
  24.         continue;
  25.       }
  26.       if (lines[line][column])
  27.         putchar(lines[line][column]);
  28.       else {
  29.         free(lines[line]);
  30.         lines[line] = NULL;
  31.         remaining --;
  32.         putchar(' '); // leave a space for padding
  33.       }
  34.     }
  35.     putchar('\n');
  36.   }
  37.   return 0;
  38. }
  39.  
  40. unsigned getNumber (void) {
  41.   char * line = getLine();
  42.   char * current;
  43.   unsigned value = 0;
  44.   for (current = line; *current; current ++) {
  45.     if ((*current < '0') || (*current > '9')) {
  46.       value = 0;
  47.       break;
  48.     }
  49.     if ((10 * value + (*current - '0')) < value) {
  50.       printf("That number was too large, enter a smaller one please\n");
  51.       free(line);
  52.       return 0;
  53.     }
  54.     value *= 10;
  55.     value += *current - '0';
  56.   }
  57.   free(line);
  58.   if (!value) printf("Does 'positive integer' mean something different for you?\n");
  59.   return value;
  60. }
  61.  
  62. char * getLine (void) {
  63.   char * result = NULL;
  64.   unsigned resultLength = 0;
  65.   char current;
  66.   while (1) {
  67.     current = getchar();
  68.     if ((current == '\n') || (current == EOF)) break;
  69.     result = realloc(result, ++ resultLength);
  70.     result[resultLength - 1] = current;
  71.   }
  72.   result = realloc(result, resultLength + 1);
  73.   result[resultLength] = 0;
  74.   return result;
  75. }
Advertisement
RAW Paste Data Copied
Advertisement