tdulik

Crossword puzzle generator in C

Dec 1st, 2020 (edited)
570
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <string.h>
  5. int main()
  6. {
  7.     printf("Crossword generator:\n");
  8.     FILE *f = fopen("d:\\temp\\words\\words.txt", "r");
  9.     if (f==NULL) {
  10.         puts("Error opening the file!");
  11.         return 0;
  12.     }
  13.     fseek(f, 0, SEEK_END);
  14.     long size = ftell(f);
  15.     fseek(f, 0, SEEK_SET);
  16.  
  17.     char * array=malloc(size);
  18.     if (array == NULL) {
  19.         fputs("Memory allocation error!", stderr);
  20.         return EXIT_FAILURE;
  21.     }
  22.     int c, i = 0, lines=0;
  23.     while ((c=fgetc(f))!=EOF) {
  24.         if (c=='\n') {
  25.             lines++;
  26.             c=0;       //replace \n by 0 (end of string)
  27.         }
  28.         array[i++] = c;
  29.     }
  30.     int * word_index = malloc(lines*sizeof(int));
  31.     if (word_index == NULL) {
  32.         fputs("Memory allocation error!", stderr);
  33.         return EXIT_FAILURE;
  34.     }
  35.     word_index[0]=0;
  36.     for (int j=0, line_nr=1; j<i; j++) {
  37.         if (array[j]==0) word_index[line_nr++]=j+1;
  38.     }
  39. //    printf("The file is stored in RAM, its size = %d bytes, nr. of lines=%d\n", i, lines);
  40.     srand(time(NULL));
  41.     int solution_index=(rand()*rand()) % lines;  //0..lines-1
  42.     char * solution = array+word_index[solution_index];
  43.     printf("Puzzle solution=%s\n", solution);
  44.  
  45.     for (unsigned i=0; i<strlen(solution); i++) {
  46.        char letter=solution[i];
  47.        char *ptr;
  48.        char * word;
  49.        do {
  50.            int index=(rand()*rand()) % lines;  //0..lines-1
  51.            word = array+word_index[index];
  52.            ptr=strchr(word, letter);
  53.        } while(ptr==NULL);
  54.        for (int j=0; j<40-(ptr-word); j++) putchar(' ');
  55.        *ptr = 0;
  56.        printf("%s", word);
  57.        *ptr = letter;
  58.        printf("|%c|%s\n", letter, ptr+1);
  59.     }
  60. }
  61.  
RAW Paste Data