Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

hashing in c language 1

Status
Not open for further replies.

tan6262

Programmer
Nov 1, 2000
3
US
how would i read in a text file that will be used as a hashed list search? the text includes a 5 digit student id #, the number of years spent at that college ranging from 1-6 years, the number of units completed for the first year, the number of units completed for the second year, and so on(eg. if the student has spent 3 years there, he will have 3 separate unit totals for year 1, year 2 and year 3. each field is separated by spaces.
since the # of years spent there ranges, it is suggested to create a linked list to store the yearly unit totals.
 
One way is to create a struct to hold your student data and then a separate struct to represent the # of units as a linked list:

struct units_completed {
int units; /* # of units */
int year; /* year the units were completed */
struct units_completed *next;
};

struct Student {
long id;
short years;
struct units_completed *unit_list;
};

BUT, since you say that the maximum years is 6, a better strategy may be to ditch the linked list and just go with an array:

#define MAX_YEARS 6

struct Student {
long id;
short years;
int unit_list[MAX_YEARS];
};

unit_list[0] would be the 1st year and the number of units would be the value found there. This doesn't waste very much space if the number of students is small.

Now read the text file, creating a new student for each student in the file and reading in the data. Of course, you'll have to write a number of support functions to create a student, destroy a student, add a unit to the unit list etc.

As far as the searching portion goes, hashing is one way but you'll need a string to hash that's unique to the student. This could be done by converting the id field to a string using sprintf(), running it through a hashing algorithm, then storing the entry in a hash table. If hash tables are new to you, K&R 2 has an example and I'm sure you'll come up with several hits that explain the concept and the pros and cons of different hashing algorithms.

Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top