daily pastebin goal
52%
SHARE
TWEET

Untitled

a guest Mar 22nd, 2019 50 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * File: Warmup.cpp
  3.  * ----------------
  4.  * Name: [TODO: enter name here]
  5.  * Section: [TODO: enter section leader here]
  6.  * This program generates a hash code based on user's name.
  7.  * As given, this code has two compiler errors you need to track down
  8.  * and fix in order to get the program up and running.
  9.  * [Originally written by Julie Zelenski]
  10.  */
  11.  
  12. #include <iostream>
  13. #include <string>
  14. #include "console.h"
  15. "include "simpio.h"
  16. using namespace std;
  17.  
  18. /* Constants */
  19.  
  20. const int HASH_SEED = 5381;               /* Starting point for first cycle */
  21. const int HASH_MULTIPLIER = 33;           /* Multiplier for each cycle      */
  22. const int HASH_MASK = unsigned(-1) >> 1;  /* All 1 bits except the sign     */
  23.  
  24. /* Function prototypes */
  25.  
  26. int hashCode(string str);
  27.  
  28. /* Main program to test the hash function */
  29.  
  30. int main() {
  31.     string name;
  32.     cin >> name;
  33.     int code = hashCode(name);
  34.     cout << "The hash code for your name is " << code << "." << endl;
  35.     return 0;
  36. }
  37.  
  38. /*
  39.  * Function: hash
  40.  * Usage: int code = hashCode(key);
  41.  * --------------------------------
  42.  * This function takes the key and uses it to derive a hash code,
  43.  * which is nonnegative integer related to the key by a deterministic
  44.  * function that distributes keys well across the space of integers.
  45.  * The general method is called linear congruence, which is also used
  46.  * in random-number generators.  The specific algorithm used here is
  47.  * called djb2 after the initials of its inventor, Daniel J. Bernstein,
  48.  * Professor of Mathematics at the University of Illinois at Chicago.
  49.  */
  50. int hashCode(string str) {
  51.     unsigned hash = HASH_SEED;
  52.     int nchars = str.length();
  53.     for (int i = 0; i < nchars; i++) {
  54.         hash = HASH_MULTIPLIER * hash + str[i];
  55.     }
  56.     return (hash & HASH_MASK);
  57. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top