2013 CS140 Midterm Exam - Answer All Questions


Question 1 - Hashing

You have a hash table with 100 entries. Keys are strings, and you are using the djbhash hash function from lecture. You can see the result of djbhash on three strings to the right. I am giving you three scenarios below. For each scenario, tell me where the piece of data will go in the hash table when collisions are resolved with separate chaining, linear probing and quadratic probing. Use the answer sheet.
UNIX> echo Chloe Arpa | djbhash
2437388788
UNIX> echo Gabriel Isis | djbhash
600618099
UNIX> echo Austin Labyrinth | djbhash
2735462150
UNIX> 

Question 2 - Vector / Deque / List

void X(vector <double> &a);
Part A: Suppose I have a procedure X() with the prototype above. Implement that procedure in such a way that its performance will be very bad when a is a vector, but very good when a is a deque. I don't care what X() does, except it has to perform poorly when a is a vector and well when a is a deque. Explain to me why it is better with the deque. Please remember that you cannot call push_front() or pop_front() on a vector -- in your procedure, use methods that are common to both vectors and deques, such as push_back(), pop_back(), insert() or erase(). There are prototypes at the end of this page.

Part B: Explain to me in what situation you would use a list in preference to a vector or a deque. Be precise, and explain why.


Question 3 - Hexadecimal

What are the following values in hexadecimal?
  • A: 47
  • B: Binary 1010101001
  • C: 6*256 + 10
  • D: (0xcb << 1)

Question 4 - Stringstreams and Printf

The program to the right is in the file sid.cpp. Below are some Unix commands that will compile the program and run it on an input file. Tell me the output of the last Unix command. Do this on the answer sheet, where I have gray boxes that you can use, where each box is a space on the terminal.

UNIX> g++ sid.cpp
UNIX> cat input.txt
3.567 14.2
-5 Fred
  Dontonio
20.
17.4321
5000.01
UNIX> ./a.out < input.txt 10 Mario


Prototypes of Vector/Deque Methods

void push_back(double val);
void pop_back();
iterator insert(iterator pos, double value);
void erase(iterator pos);
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

main()
{
  string s;
  istringstream ss;
  int i;
  double d;

  while (cin >> s) {
    ss.clear();
    ss.str(s);
    if (ss >> d) {
      if (s.find('.') != string::npos) {
        printf("%-10s %7.3lf\n", s.c_str(), d);
      } else {
        i = d;
        printf("%-10s %7d\n", s.c_str(), i);
      }
    } else cout << s << endl;
  }
}