Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <string.h>
- int main()
- {
- printf("Crossword generator:\n");
- FILE *f = fopen("d:\\temp\\words\\words.txt", "r");
- if (f==NULL) {
- puts("Error opening the file!");
- return 0;
- }
- fseek(f, 0, SEEK_END);
- long size = ftell(f);
- fseek(f, 0, SEEK_SET);
- char * array=malloc(size);
- if (array == NULL) {
- fputs("Memory allocation error!", stderr);
- return EXIT_FAILURE;
- }
- int c, i = 0, lines=0;
- while ((c=fgetc(f))!=EOF) {
- if (c=='\n') {
- lines++;
- c=0; //replace \n by 0 (end of string)
- }
- array[i++] = c;
- }
- int * word_index = malloc(lines*sizeof(int));
- if (word_index == NULL) {
- fputs("Memory allocation error!", stderr);
- return EXIT_FAILURE;
- }
- word_index[0]=0;
- for (int j=0, line_nr=1; j<i; j++) {
- if (array[j]==0) word_index[line_nr++]=j+1;
- }
- // printf("The file is stored in RAM, its size = %d bytes, nr. of lines=%d\n", i, lines);
- srand(time(NULL));
- int solution_index=(rand()*rand()) % lines; //0..lines-1
- char * solution = array+word_index[solution_index];
- printf("Puzzle solution=%s\n", solution);
- for (unsigned i=0; i<strlen(solution); i++) {
- char letter=solution[i];
- char *ptr;
- char * word;
- do {
- int index=(rand()*rand()) % lines; //0..lines-1
- word = array+word_index[index];
- ptr=strchr(word, letter);
- } while(ptr==NULL);
- for (int j=0; j<40-(ptr-word); j++) putchar(' ');
- *ptr = 0;
- printf("%s", word);
- *ptr = letter;
- printf("|%c|%s\n", letter, ptr+1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement