Skip to content

Instantly share code, notes, and snippets.

@chrisdel101
Created April 30, 2018 00:23
Show Gist options
  • Select an option

  • Save chrisdel101/f34af62bd75454fe8511ec3750498556 to your computer and use it in GitHub Desktop.

Select an option

Save chrisdel101/f34af62bd75454fe8511ec3750498556 to your computer and use it in GitHub Desktop.
Implementing check()
// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "dictionary.h"
int hashValue(const char *word);
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
node *hash_table[HASHTABLE_SIZE] = {NULL};
// Returns true if word is in dictionary else false
bool check(const char *word)
{
char arr[LENGTH+1];
// HASH VALUE
// hash to get bucket/array index
int hash_index = hashValue(word);
// set head to first node in bucket/array
node *head = hash_table[hash_index];
// SET WORD TO LOWER
for(int i = 0; i < strlen(word);i++)
{
arr[i] = tolower(word[i]);
}
// printf("string: %s\n", arr);
// set cursor originallyy to head
node *cursor = head;
while(cursor != NULL)
{
// if(strcmp(arr, head->word) == 0)
// {
// puts("equal");
// return 0;
// }
printf("%s\n",cursor->word);
cursor = head->next;
// printf("%s\n", arr);
head = cursor;
}
return true;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
FILE *inptr = fopen(dictionary, "r");
char temp[LENGTH+1];
// load dictionary to test
while(fscanf(inptr,"%s",temp) != EOF)
{
// malloc mem
node *mem = malloc(sizeof(node));
if(mem == NULL)
{
return 1;
}
// copy line into node's word
strcpy(mem->word, temp);
// hash it
int hash_index = hashValue(temp);
// if null, head is empty
if(hash_table[hash_index] == NULL)
{
// insert at head of linked list
// same as head = mem
hash_table[hash_index] = mem;
// make next null
mem->next = NULL;
}
else
{
// set next to current head
mem->next = hash_table[hash_index];
// reassign head to new node
hash_table[hash_index] = mem;
}
}
fclose(inptr);
puts("made it to end");
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
// TODO
return 0;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
// TODO
return false;
}
int hashValue(const char *word)
{
unsigned int hash = 0;
for (int i=0, n=strlen(word); i<n; i++) {
hash = (hash << 2) ^ word[i];
}
// returns a number
return hash % sizeof(HASHTABLE_SIZE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment