13 Replies - 1719 Views - Last Post: 24 April 2012 - 01:06 PM Rate Topic: -----

#1 deepdivin247  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 20-April 12

Another Jumble Program in C

Posted 22 April 2012 - 08:31 PM

Hi everyone.

So let me start off by saying that the code here has nothing to do with the code in my other post. I wrote the latter one completely wrong, so I started over with the one below.

Now that iv'e realized what i'm being asked to do, I can correctly tell you guys what it is, I have to create a program that reads from a given list of dictionary words and from a list of given jumbled words. Then I have to compare the two, then print out what the jumbled word is and the actual word is. Not to hard of a program to construct in my opinion.

Btw, the dictionary file (jumbledct.txt) and the jumbled file (jumble.txt) both have an integer at the top, which is the amount of words in each file. The jumbled file is just a sample of one of the many text files I plan to run with the program.

Since I'm still a newbie at programming, Iv'e ran into another issue that I cant seem to figure out. I'm pretty sure I'm missing a few strcmp's. But my code isn't printing out correctly. Could someone please explain to me what I'm doing wrong?

Thanks for your help.

#include <stdio.h>
#include <string.h>

#define MAX_WORD_LEN 6
#define MAX_NUM_WORDS 30000

// Struct to use.
struct jumble {
    char word[MAX_WORD_LEN+1];
    char sort[MAX_WORD_LEN+1];
};

void bubblesort(char letters[], int length) {

    char temp;
    int i, j;

    // sort the length array
    for(i = 0; i < length; i++){
        for(j = 0; j < length-i-1; j++){
            if(letters[j] > letters[j+1]){
                temp = letters[j];
                letters[j] = letters[j+1];
                letters[j+1] = temp;

            }
        }
    }
}

int main() {

    struct jumble list[MAX_NUM_WORDS];

    int i, j;

    FILE* dictionary = fopen("jumbledct.txt", "r");
    FILE* jumbled = fopen("jumble.txt", "r");

    if ((dictionary == NULL) || (jumbled == NULL)){
        printf("Error, file does not exist.");
    }

    else{

        // Read in the number of words from the dictionary.
        int numwords;
        fscanf(dictionary, "%d", &numwords);

        int num_jumb;
        fscanf(jumbled, "%d", &num_jumb);

        // Go through each word.
        for (i = 1; i <= numwords; i++) {
            fscanf(dictionary, "%s", list[i].word);

            // Go through each jumbled word
            for (j = 1; j <= num_jumb; j++)
                fscanf(jumbled, "%s", list[i].sort);


                // Compare each word.
                strcmp(list[i].sort, list[i].word);

                //Initialize bubblesort array.
                bubblesort(list[i].sort, strlen(list[i].word));
        }

        if (num_jumb < 100){

            // Print out the words and their other arrangement.
            for (i = 1; i <= num_jumb; i++){
                    printf("Jumble Puzzle #%d: %s\n", i, list[i].sort);
                    printf("%s\n", list[i].word);
                    printf("\n");
                    printf("\n");
            }
        }

        else{
            printf("Your number must be less than 100.\n");
        }
    }

    return 0;
}

Attached File(s)



Is This A Good Question/Topic? 1
  • +

Replies To: Another Jumble Program in C

#2 deepdivin247  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 20-April 12

Re: Another Jumble Program in C

Posted 22 April 2012 - 08:54 PM

Previously discussed here.
Was This Post Helpful? 0
  • +
  • -

#3 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: Another Jumble Program in C

Posted 22 April 2012 - 10:47 PM

1. You can't sort your array of struct with the same bubble sort that you use to sort a string into abc... order.

2. Since the dictionary array is fairly large, you best use C's qsort ( quick sort ) to sort it.
And you will then need to define a compare function to pass to qsort ...
I would suggest sorting by length, then by the sorted string, then by the original string ... all in the same compare function.
typedef struct /* create array of these while reading dictionary file */
{
   char* orig;
   char* sort;
   int len;
} Dict ;

int myCmp( const void* a, const void* b )
{
   const Dict* x = (Dict*) a;
   const Dict* y = (Dict*) b;
   int cmp_len = x->len - y->len;
   if( cmp_len == 0 )
   {
      int cmp_sort = strcmp( x->sort, y->sort );
      if( cmp_sort == 0 ) return strcmp( x->orig, y->orig );
      else return cmp_sort;
   }
   else return  cmp_len;
}
/* ... */
qsort( ary, size, sizeof(Dict), myCmp );


This post has been edited by David W: 22 April 2012 - 10:56 PM

Was This Post Helpful? 1
  • +
  • -

#4 deepdivin247  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 20-April 12

Re: Another Jumble Program in C

Posted 23 April 2012 - 03:27 AM

Your code idea is most likely correct, but in the assignment, it says only to use the bubble sort function and the main function. And I dont think im supposed to use a qsort(). I wrote some new code, maybe this will help you to get a better idea of how the assignment was posted. I'm still a little stuck though, I know I need to take the jumble.txt file and alphabetize those words by letter then compare those words to the dictionary words, and compare the two to see if they are == to 0 and if so I just run a print command of the words that 'checked out'. Did I say that right?

#include <stdio.h>
#include <string.h>


#define MAX_WORD_LEN 6
#define MAX_NUM_WORDS 30000


// Struct to use.
typedef struct {
    char word[MAX_WORD_LEN+1];
    char sort[MAX_WORD_LEN+1];
} jumble_type;


void bubblesort(char letters[], int length) {


    char temp;
    int i, j;


    // sort the length array
    for(i = 0; i < length; i++){
        for(j = i; j < length; j++){
            if(letters[i] > letters[j]){
                temp = letters[j];
                letters[j] = letters[i];
                letters[i] = temp;


            }
        }
    }
}


int main() {


    jumble_type list[MAX_NUM_WORDS];
    jumble_type jumb[MAX_NUM_WORDS];


    int i, j, k, l;


    FILE* dictionary = fopen("jumbledct.txt", "r");
    FILE* jumbled = fopen("jumble.txt", "r");


    if ((dictionary == NULL) || (jumbled == NULL)){
        printf("Error, file does not exist.");
    }


    else{


        // Read in the number of words from the dictionary.
        int numwords;
        fscanf(dictionary, "%d", &numwords);


        int num_jumb;
        fscanf(jumbled, "%d", &num_jumb);


        // Go through each word.
        for (i = 0; i < numwords; i++) {
            fscanf(dictionary, "%s", list[i].word);
            strcpy(list[i].sort, list[i].word);
        }


            // Go through each jumbled word
            for (j = 0; j < num_jumb; j++) {
                fscanf(jumbled, "%s", list[j].word);
                strcpy(jumb[i].sort, jumb[i].word);
            }


        bubblesort(jumb[i].sort, strlen(list[i].sort));


        if (num_jumb < 100){


            // Print out the words and their other arrangement.
            for (l = 0; l < num_jumb; l++){
                    printf("Jumble Puzzle #%d: %s\n", l+1, list[l].word);
            }
                for (k = 0; k < numwords; k++) {
                    if (strcmp(list[i].word, list[l].word) == 0) {
                        printf("%s\n", list[k].sort);
                    }
                }
            }
            else{
                printf("Your number must be less than 100.\n");
            }
        }


    return 0;
}


Was This Post Helpful? 0
  • +
  • -

#5 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5805
  • View blog
  • Posts: 12,643
  • Joined: 16-October 07

Re: Another Jumble Program in C

Posted 23 April 2012 - 04:35 AM

You know what, I realized what you're doing. Ignore this one.

This post has been edited by baavgai: 23 April 2012 - 05:26 AM

Was This Post Helpful? 0
  • +
  • -

#6 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5805
  • View blog
  • Posts: 12,643
  • Joined: 16-October 07

Re: Another Jumble Program in C

Posted 23 April 2012 - 06:07 AM

Here's how I'd organize the code. I filled in the bubble sort, since yours it's really a bubble sort at all.

#include <stdio.h>
#include <string.h>


#define MAX_WORD_LEN 6
#define MAX_NUM_WORDS 30000

typedef char Word[MAX_WORD_LEN+1];

// Struct to use.
typedef struct {
    Word word, sort;
} jumble_type;

typedef struct {
    jumble_type items[MAX_NUM_WORDS];
    int size;
} Words;

void bubblesort(char *letters);
int load(Words *, const char *filename);
void findMatch(jumble_type *, Words *dict);

int main() {
	Words jumb, list;
	
	if(!load(&jumb, "jumble.txt") || !load(&list, "jumbledct.txt")) {
		printf("Error, file does not exist.\n");
	} else {
		int i;
		
		for(i=0; i<jumb.size; i++) {
			jumble_type *jt = &jumb.items[i];
			printf("Jumble Puzzle #%d: %s - %s\n", i+1, jt->word, jt->sort);
			findMatch(jt, &list);
		}
	}

    return 0;
}


void bubblesort(char *letters) {
    int swapped = 1;
	while(swapped) {
		char *p = letters;
		swapped = 0;
        while(p[1]!=0) {
        	if (p[1]<p[0]) {
        		char temp = p[0];
        		p[0] = p[1];
        		p[1] = temp;
        		swapped = 1;
        	}
        	p++;
        }
    }
}



Every time you read a word from a file, immediately make a valid array item...
// item in the array 
// jumble_type *item
fscanf(fh, "%s", item->word);
strcpy(item->sort, item->word);
bubblesort(item->sort);



Hope this helps.
Was This Post Helpful? 1
  • +
  • -

#7 deepdivin247  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 20-April 12

Re: Another Jumble Program in C

Posted 23 April 2012 - 10:06 AM

Your code looks awesome. But there are a few things in the assignment that have to stay how they were posted in my original code. Like the bubble sort for example. I completed the code, even if it isn't the most logical or quickest way, but it does run correctly. For your viewing pleasure:


#include <stdio.h>
#include <string.h>

#define MAX_WORD_LEN 6
#define MAX_NUM_WORDS 30000

// Struct to use.
typedef struct {
    char word[MAX_WORD_LEN+1];
    char sort[MAX_WORD_LEN+1];
} jumble_type;

void bubblesort(char letters[], int length) {

    char temp;
    int i, j;

    // Sort each word alphabetically by letter.
    for(i = 0; i < length; i++){
        for(j = i; j < length; j++){
            if(letters[i] > letters[j]){
                temp = letters[j];
                letters[j] = letters[i];
                letters[i] = temp;

            }
        }
    }
}

int main() {

    // Declare variables for dictionary and jumbled words.
    jumble_type list[MAX_NUM_WORDS];
    jumble_type jumb[MAX_NUM_WORDS];

    int i, j, k;

    // Open the files to write into.
    FILE* dictionary = fopen("jumbledct.txt", "r");
    FILE* jumbled = fopen("jumble.txt", "r");

    // Check to make sure files open.
    if ((dictionary == NULL) || (jumbled == NULL))
        printf("Error, file does not exist.");

    else {
        // Read in the number of words from the dictionary of words.
        int numwords;
        fscanf(dictionary, "%d", &numwords);

        // Read in the number of words from the jumble of words.
        int num_jumb;
        fscanf(jumbled, "%d", &num_jumb);

        // Go through each dictionary word, store in list, copy, then sort each.
        for (i = 0; i < numwords; i++) {
            fscanf(dictionary, "%s", list[i].word);
            strcpy(list[i].sort, list[i].word);
            bubblesort(list[i].sort, strlen(list[i].sort));
        }

            // Go through each jumbled word, store in jumb, copy, then sort each.
            for (i = 0; i < num_jumb; i++) {
                fscanf(jumbled, "%s", jumb[i].word);
                strcpy(jumb[i].sort, jumb[i].word);
                bubblesort(jumb[i].sort, strlen(jumb[i].sort));
            }

        // Make sure number of jumbled words x: 0 < x < 100
        if ((num_jumb > 0) && (num_jumb < 100)) {

            // Print out the jumbled words.
            for (j = 0; j < num_jumb; j++){
                printf("JUMBLE PUZZLE #%d: %s\n", j+1, jumb[j].word);

                // Compare each word, then print out all dictionary word solutions.
                int x=0;
                for (k = 0; k < numwords; k++) {
                    if (strcmp(jumb[j].sort, list[k].sort) == 0) {
                        printf("%s\n", list[k].word);
                        x++;
                        printf("\n");
                    }
                }

                // Print out no solutions.
                if (x == 0) {
                    printf("Sorry, this puzzle has no solutions.\n");
                    printf("\n");
                }
            }
        }

        // Print out error for negative values or values over 100.
        else
            printf("Your number must be greater than 0 and less than 100.\n");
    }

    return 0;
}



Thank you for all your help. Newbie question: How do I mark as solved? Or did this post just do that?
Was This Post Helpful? 0
  • +
  • -

#8 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: Another Jumble Program in C

Posted 23 April 2012 - 10:37 AM

Your coding future looks bright :)
You may want to exit right after you read from your scrambled word file the first 'word count' value if it is not within your limiting range?
There is not much point of doing computing work to later ignore?

Also you only need an array of a max 100 jumbled word struct's if the above is done.
Also, you may want to exit if the number of dictionary words read in at the first, exceeded the max room in your program array pre-fixed at compile time ...
Or ... exit, with a message, your dictionary file reading loop, when you reach the max size of the pre-fixed array?

This post has been edited by David W: 23 April 2012 - 10:53 AM

Was This Post Helpful? 1
  • +
  • -

#9 deepdivin247  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 20-April 12

Re: Another Jumble Program in C

Posted 23 April 2012 - 11:02 AM

View PostDavid W, on 23 April 2012 - 10:37 AM, said:

Your coding future looks bright :)
You may want to exit right after you read from your scrambled word file the first 'word count' value if it is not within your limiting range?
There is not much point of doing computing work to later ignore?

Also you only need an array of a max 100 jumbled word struct's if the above is done.
Also, you may want to exit if the number of dictionary words read in at the first, exceeded the max room in your program array pre-fixed at compile time ...
Or ... exit, with a message, your dictionary file reading loop, when you reach the max size of the pre-fixed array?


Oh my, quite a lot of exiting. Would exiting the files at the end be just as sufficient, or are you saying to exit right after I read from the file and the files don't exist? Like this:
// Check to make sure files open.
    if ((dictionary == NULL) || (jumbled == NULL)) {
        printf("Error, file does not exist.");
        
        // Close both files.
        fclose(ifp);
        fclose(ofp);
    }



I exited the files at the end just before the return 0; also.
Was This Post Helpful? 0
  • +
  • -

#10 deepdivin247  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 20-April 12

Re: Another Jumble Program in C

Posted 23 April 2012 - 11:13 AM

Oops, I meant to say:
// Close both files.
        fclose(dictionary);
        fclose(jumbled);


Was This Post Helpful? 0
  • +
  • -

#11 baavgai  Icon User is online

  • Dreaming Coder
  • member icon

Reputation: 5805
  • View blog
  • Posts: 12,643
  • Joined: 16-October 07

Re: Another Jumble Program in C

Posted 23 April 2012 - 11:58 AM

Looks good.

For the files, if the file handle is NULL, you actually don't want to mess with it. You often seen the descending into successive successful ifs:

int main() {
	FILE *jumbled, *dictionary;
	
	if ((dictionary = fopen("jumbledct.txt", "r"))==NULL) {
		printf("Error, file does not exist.");
	} else if ((jumbled = fopen("jumble.txt", "r"))==NULL) {
		printf("Error, file does not exist.");
		fclose(dictionary);
	} else {
		jumble_type list[MAX_NUM_WORDS], jumb[MAX_NUM_WORDS];
		// now you get down to business
		// ...
		fclose(jumbled);
		fclose(dictionary);
		// ...
		return 0
		
	}
	return 1;
}



Though, seriously, you're doing exactly the same thing for both files. It's a shame you don't have another function.
int readList(const char *filename, jumble_type *list) {
	FILE *fh;

	if ((fh = fopen(filename, "r"))==NULL) {
		return -1;
	} else {
		int i, numwords;
		fscanf(fh, "%d", &numwords);
		for (i = 0; i < numwords; i++) {
			fscanf(fh, "%s", list[i].word);
			strcpy(list[i].sort, list[i].word);
			bubblesort(list[i].sort, strlen(list[i].sort));
		}
		fclose(fh);
		return numwords;
	}
}

int main() {
	jumble_type list[MAX_NUM_WORDS], jumb[MAX_NUM_WORDS];
	int numwords, num_jumb;

	numwords = readList("jumbledct.txt", list);
	num_jumb = readList("jumble.txt", jumb);

	if (numwords==-1 || num_jumb==-1) {
		printf("Error, file does not exist.");
	} else {
		// Make sure number of jumbled words x: 0 < x < 100


Was This Post Helpful? 1
  • +
  • -

#12 deepdivin247  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 20-April 12

Re: Another Jumble Program in C

Posted 23 April 2012 - 01:03 PM

Okay, that does make sense. I edited the code, but then when I tried to test it, for ex. I changed the file name of jumbledct.txt to jumbledcts.txt, the program still ran. I'm sure thats an easy fix. But, if the way I wrote the Error Check:

// Check to make sure files open.
    if ((dictionary == NULL) || (jumbled == NULL)) {
        printf("Error, file does not exist.");
        
        // Close both files.
        fclose(dictionary);
        fclose(jumbled);
    }



is valid, then I'm happy with that. Or are you saying it should be written like one of the two above?
Was This Post Helpful? 0
  • +
  • -

#13 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: Another Jumble Program in C

Posted 23 April 2012 - 07:42 PM

Here is another way you may like to see ...

#include <stdio.h>
#include <string.h>

#define MAX_WORD_LEN 6
#define MAX_NUM_WORDS 30000
#define MAX_NUM_JUMB 100

typedef struct
{
    char word[MAX_WORD_LEN+1];
    char sort[MAX_WORD_LEN+1];
} jumble ; /* or use Jumble */

void bubblesort( char letters[], int length )
{
    char temp;
    int i, j;

    /* sort the length array */
    for( i = 0; i < length; ++i )
    {
        for( j = 0; j < length-i-1; ++j )
            if( letters[j] > letters[j+1] )
            {
                temp = letters[j];
                letters[j] = letters[j+1];
                letters[j+1] = temp;
            }
    }
}



int main()
{
    /* Declare variables for dictionary and jumbled words. */
    jumble dict[MAX_NUM_WORDS];
    jumble jumb[MAX_NUM_JUMB];

    /*  Open the files to read. */
    FILE* dictionary = fopen( "jumbledct.txt", "r" );
    FILE* jumbled = fopen( "jumble.txt", "r" );

    /*  Check to make sure files open. */
    if( dictionary == NULL || jumbled == NULL )
        printf( "Error opening files." );

    else
    {
        /* Read in the number of jumble and dictionary words. */
        int i, numwords, num_jumb;
        fscanf( jumbled, "%d", &num_jumb );
        if( num_jumb > MAX_NUM_JUMB )
        {
            printf( "%d file jumbled words exceeds max of %d\n",
                    num_jumb, MAX_NUM_JUMB );
            return -1;
        }
        
        fscanf( dictionary, "%d", &numwords );
        if( numwords > MAX_NUM_WORDS )
        {
            printf( "%d file dictionary words exceeds max of %d\n",
                    numwords, MAX_NUM_WORDS );
            return -2;
        }
        
        /*  OK ... Go through each dictionary word,
            store in dict, copy, then sort each. */
        for( i = 0; i < numwords; ++i )
        {
            fscanf( dictionary, "%s", dict[i].word );
            strcpy( dict[i].sort, dict[i].word );
            bubblesort( dict[i].sort, strlen( dict[i].sort) );
        }

        /* And ... go through each jumbled word,
            store in jumb, copy, then sort each. */
        for( i = 0; i < num_jumb; ++i )
        {
            fscanf( jumbled, "%s", jumb[i].word );
            strcpy( jumb[i].sort, jumb[i].word );
            bubblesort( jumb[i].sort, strlen( jumb[i].sort ) );
        }

        /* Print out the jumbled words. */
        for( i = 0; i < num_jumb; ++i )
        {
            int k, x = 0;
            printf( "\nJUMBLE PUZZLE #%d: %s\n", i+1, jumb[i].word );

            /* Compare each word, then print out all dictionary word solutions. */
            for( k = 0; k < numwords; ++k )
            {
                if( strcmp( jumb[i].sort, dict[k].sort ) == 0 )
                {
                    printf( "%s\n", dict[k].word );
                    ++x;
                }
            }

            /* Print out no solutions. */
            if( x == 0 )
                printf( "Sorry, this puzzle has no solutions.\n" );
        }
    }
    
    printf( "\nPress 'Enter' to continue ... " ); fflush( stdout );
    getchar();
    return 0;
}


This post has been edited by David W: 23 April 2012 - 09:52 PM

Was This Post Helpful? 1
  • +
  • -

#14 deepdivin247  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 22
  • Joined: 20-April 12

Re: Another Jumble Program in C

Posted 24 April 2012 - 01:06 PM

I ended up leaving the program the way I had it written, and turned it in. Yours would have worked as well but I don't think the testing of my program included testing the dictionaries amount of words. Aka the dictionary file will not be changing at all, only the jumble file. Which is why I included the parameters for the num_jumb being between 0 and 100. I will definitely be returning with more questions about other code in the future. Thank you very much. Chris
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1