Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 290
  • Last Modified:

Hash tables

Hi. I'm trying to implement the following hash functions.
1. h(x)= 1 + (x/k) * M
2. h(x)= 1 + x mod M
3. h(x)=1 + @x mod M

Where M is the table size. They should change keys into integers in the range from 1 to M. I'm using this to generate the numbers and send them to the hash function:

#include<iostream.h>
#include<stdlib.h>
main()
{
 int tablesize=32;
 int a[200];
 for(int i=0;i<200;i++)
 {
      i=rand()%5001;
        h(x)=hash(tablesize,i)
   }
 return 0;
}

1. How do I make the hash function?
2. Can hashing be used with text? Can you provide some examples?
Thanx
0
q_low
Asked:
q_low
  • 3
  • 2
1 Solution
 
RONSLOWCommented:
something like this would probably do...

int hash1(int M, int x) { return 1 + (x / k) * M; }
int hash2(int M, int x) { return 1 + x % m; }
int hash3(int M, int x) { return 1 + ???x % m; }
// whatever @x means
// don't know what you're talking about there
// you'll have to code that yourself

static int method = 1;

int hash(int M, int x) {
  switch (method) {
  case 1: return hash1(M,x);
  case 2: return hash1(M,x);
  case 3: return hash1(M,x);
  }
  return 0; // not a valid hash method
}

You can then set method to be 1, 2 or 3 as required.

And I think you want you code to say
  int x;
  for(int i=0;i<200;i++) {
    x=rand()%5001;
    a[x]=hash(tablesize,x);
  }
And then print out (or do something with) the hash values rather than just end the program.

To use with text, you usually loop for each each character, hash it and combine with the overall running hash value (eg add, or shift and add or whatever).  There are lots of examples around of hashing.

0
 
q_lowAuthor Commented:
in the first equation k will be the key.
what does the key means if i have a table of size 32?
0
 
q_lowAuthor Commented:
....
0
 
RONSLOWCommented:
the way you have shown the code, x is the key.  k being the key doesn't make sense .. because then what is x and where does k come from.

if your table size is 32, then .. well, your table size is 32.  Don't think it means anything in particular.

I think I answred you question satisfactorily.

0
 
q_lowAuthor Commented:
thanx
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now