Esempio n. 1
0
/************************************************************************
 * Takes a filename that contains one word (of lower case letters) per	*
 * line, reads the file contents, and builds an array of linked lists	*
 * and returns a pointer to this array. It also sets the aryLen 		*
 * parameter to size/length of the array returned from the function.	*
 ************************************************************************/
AryElement *buildAnagramArray(char *infile, int *aryLen){
	AryElement *ary = NULL;				// stores pointer to dynamically allocated array of structures
	char word[MAX_WORD_SIZE];			// stores a word read from the input file
	int curAryLen = INITIAL_ARRAY_SIZE;	// stores current length/size of the array
	int nbrUsedInAry = 0;				// stores number of actual entries in the array

	// prepare the input file for reading
	FILE *fp = fopen(infile,"r");
	if (fp == NULL) {
		fprintf(stderr,"Error opening file %s\n", infile);
		exit(EXIT_FAILURE);
	}
	
	ary = malloc(sizeof(AryElement)*INITIAL_ARRAY_SIZE);
	//AryElement: int size, Node *head
	//Node: char *text, node *next
	
	while (fscanf(fp, "%s", word) != EOF){
		//check if we are at the limit of our allocated space
		if(nbrUsedInAry == curAryLen){
			//reallocate our space
			curAryLen = curAryLen*2;
			ary = realloc(ary,sizeof(AryElement)*curAryLen);
		}
		//search array for anagrams
		bool foundAnagram = false;
		for(int i=0;i<nbrUsedInAry;i++){
			AryElement* aryElement = &ary[i];
			Node* temp = aryElement->head;
			if(areAnagrams(temp->text, word)){
				//the two words are anagrams
				ary[i].size++;
				//find the end of the current linked list
				while(temp->next != NULL){
					temp = temp->next;
				}
				//create node at the end of the current linked list
				temp->next = createNode(word);
				foundAnagram = true;
			}
			//word and ary[i] words aren't anagrams
		}
		if(foundAnagram == false){
			//there are no anagram matches for the current word. Create a new array element.
			//AryElement *newElem = malloc(sizeof(AryElement));
			ary[nbrUsedInAry].size = 1;
			ary[nbrUsedInAry].head = createNode(word);
			nbrUsedInAry++;
		}
	} //done scanning words from file
	
	//get rid of unused memory in array
	ary = realloc(ary,sizeof(AryElement)*nbrUsedInAry);
	//printf("Used %d out of %d total\n", nbrUsedInAry, curAryLen);
	fclose(fp);
	
	*aryLen = nbrUsedInAry;

    return ary;
}
Esempio n. 2
0
int main() {
  char input[2][MAX_INPUT_SIZE];
  readln(input[0]);
  readln(input[1]);

  if (areAnagrams(input[0], input[1]))
    printf("String are anagrams\n");
  else
    printf("Strings are not anagrams\n");

  return 0;
}