Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 118,311 C++ Programmers for FREE! Ask your question and get quick answers from experts. There are 1,690 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



Linear Probing with Hash Tables

 
Reply to this topicStart new topic

Linear Probing with Hash Tables

HulkingNightcrawler
post 6 Aug, 2008 - 10:57 PM
Post #1


New D.I.C Head

*
Joined: 26 Jun, 2008
Posts: 20

I am trying to write a program that will read data from a file and then put the data into a hash table using the Linear Probing approach. I have a book that dealing with algorithms and the sample code in the book I don't understand to well . I understand the hash function, it is just there to get the key for the table. But I don't understand what the #define means or the Key and key variable types. I don't think there is a Key variable type in C, but I could be wrong. I also don't understand how the pointer st is accessed like an array. Could all pointers be accessed like this? I know this code comes from an algorithm book so maybe I shouldn't be taking this code so literal but could could I get a little help on understanding the code.

CODE

#include <stdlib.h>
#include "Item.h"
#define null(A) (key(st[A]) == key(NULLitem))

static int N, M;
static Item *st;

void STinit(int max)
{
      int i;
      N=0; M = 2*max;
      st = malloc(M*sizeof(Item));
      for(i = 0; i < M; i++) st[i] = NULLitem;
}

int STcount() { return N; }

void STinsert(Item item)
{
      Key v = key(item);
      int i = hash(v, M);
      while(!null(i))
            i = (i + 1) % M;
      st[i] = item; N++;
}

Item STsearch (Key v)
{
      int i = hash(v, M);
      while( !null(i))
            if(v == key(st[i]))
                  return st[i];
            else
                  i = (i + 1) % M;
      return NULLitem;
}

int hash( char *v, int M)
{
      int h, a = 31415, b = 27183;
      for(h = 0; *v != '\0'; v++, a = a*b % (M - 1))
            h = (a*h + *v) % M;
      return h;
}

















User is offlineProfile CardPM

Go to the top of the page


NickDMax
post 7 Aug, 2008 - 03:18 PM
Post #2


2B||!2B

Group Icon
Joined: 18 Feb, 2007
Posts: 2,763



Thanked 37 times

Dream Kudos: 525
My Contributions


The code does seem incomplete. The data types "Item" and "Key" are indeed not not part of the ANSI C standard, however, you can take them to be generic -- Item is just the type that you would like to store in your hash table, and Key is the type that you would like to use for the key on the hash table.

#define -- this is a preprocessor directive.

#define Macro template_text
Whenever the C parser finds the Macro in the program it substitutes in the template_text. You can parameterize a macro:
#define Equals(param1, param2) (param1 == param2)

Now in my code I can use: if (Equals(x, y)) { ... }
which the compiler will see as: if((x == y)) { ... }

So in your code while(!null(i)) becomes while(!(key(st[i]) == key(NULLitem)))

QUOTE
I also don't understand how the pointer st is accessed like an array


the [] operator works like this A[i] = *(A+i). Want to have fun, try i[A] which equals *(i +A) -- this seems like very odd syntax, but it is technically perfectly valid C syntax.

QUOTE
Could all pointers be accessed like this?
A pointer points to a location in memory. Normally to access the data stored at that location you would use the dereferance operator(*). But you can use the array dereferance operator([]).

Take a look at my pointers tutorial. (just need the first few paragraphs).
User is offlineProfile CardPM

Go to the top of the page

HulkingNightcrawler
post 7 Aug, 2008 - 07:23 PM
Post #3


New D.I.C Head

*
Joined: 26 Jun, 2008
Posts: 20

Thanks that helped a lot. I think I am getting the hang of the code now but I am still having trouble getting the program to work. Whenever I run the program it just sits there. I tried putting in some printf statements to see where my program would mess up at but it doesn't wanna execute any of those lines of code. I think the program is getting hung up on oaInsert, any advice and I am trying to use the name of the student as the key??
CODE

#include <stdio.h>
#include <stdlib.h>


static int N, M;

struct studentType
{
char name[20];
int age;
int id;
float gpa;
};

typedef struct studentType student;
student theStudent;
student nullStudent;

student *oaTable;
student *currentPos;

int hash(char *v, int W);
void hashTable(int max);
int count ();
void insert(student addStudent);
student search(student searchStudent);



/*
*******************Main Function*************************************************
*/


int main(int argc, char *argv[])
{
   int count, datasize;  
   FILE* fdata=NULL;
   FILE* fsearch=NULL;
   student studentArray[200];
   student studentNameArray[200];
  
   printf("Hello World");
   if(argc != 3)
   {
    printf ("Invalid number of arguments");
    printf("\n");    
    exit(0);
   }
  
   printf("Hello World4");
   hashTable(200);
  

   /*read file 1*/
   count = 0;
   fdata = fopen(argv[1], "r");

   if (fdata == NULL)
   {
    fprintf(stderr, "Can't open input file input!\n");
    printf("Error: file %s doesn't exist.\n", argv[2]);    
    exit(1);
   }
  
   printf("Hello World3");
  
   while (fscanf(fdata, "%s %d %d %f", theStudent.name, &theStudent.age,&theStudent.id,&theStudent.gpa) != EOF)
   {
    
        studentArray[count]=theStudent;
    printf("Hello World1");
    insert(theStudent);
    printf("Hello World2");

        count++;
        datasize = count;
   }
  
  /*
  printf("%d", datasize);
  printf("\n");
  */
  printf("%s", studentArray[125].name);
  printf("\n");
  
  
  /* Opens search file.*/
  fsearch=fopen(argv[2], "r");
  if(!fsearch)
  {
    fprintf(stderr, "Can't open input file input!\n");
    printf("Error: file %s doesn't exist.\n", argv[2]);
    exit(1);
  }
  count = 0;
  while (fscanf(fsearch, "%s", theStudent.name) != EOF)
   {
        studentNameArray[count]=theStudent;        
        count++;
        datasize = count;
   }
  
  
  /* Closes both files. */
  fclose(fdata);
  fclose(fsearch);    
  return 0;
}

/*
My hash function for strings
*/

int hash(char *v, int W)
{
    int h, a = 31415, b = 27183;
    for( h= 0; *v != '\0'; v++, a = a*b % (W - 1))
        h = (a*b + *v) % W;
    return h;
}


/*
This function builds by hash table.
*/

void hashTable(int max)
{    
    int i;
    N = 0;
    M = 2*max;    
    oaTable = malloc(M*sizeof(student));
    currentPos = oaTable;
    for(i = 0; i < M; i++)
    {
        *currentPos = nullStudent;
        currentPos++;
    }
    currentPos = oaTable;
}
/*
Keeps count of the number of entries I have in my table
*/
int count ()
{
    return N;
}
/*
Inserts a student struct into hash table.
*/
void insert(student addStudent)
{
    char *v = addStudent.name;
    int i = hash(v,M);
    printf("Hello World");
    while(oaTable[i].name != nullStudent.name)
        i = (i + 1) % M;
    oaTable[i] = addStudent;
    N++;
}
/*
This funciton searches for the entry.
*/
student search(student searchStudent)
{
    char *v = searchStudent.name;
    int i = hash(v, M);
    while(oaTable[i].name != nullStudent.name)
    {
        if(searchStudent.name == oaTable[i].name)
            return oaTable[i];
        else
            i = (i + 1 ) % M;
    }
    return nullStudent;
}


User is offlineProfile CardPM

Go to the top of the page

Reply to this topicStart new topic
Time is now: 10/10/08 12:08PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month