CS106B Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

6/4 Overview

- go through slideshow and add to cheat sheet

5/29 Section

- Recursion
base case
recursive call(s)

- Recursive backtracking
base case. return true
optional base case, return false
for each possible path in this current function
choose a path // often means removing the option from a set of workable paths
recurse on this path
if (true) return true
else un-choose the path
return false

- Memory
pointer = memory address that stores something in heap
int x = 3;
int* xp = &x; // xp points to x
int y = *xp; // y = 3, the value xp points to

int[] array = new int[5]; // createsS an array holding 1, 2, 3, 4, 5


int* arrp = &array[2]; // points to 3 in array
int arr = array[2]; // creates a copy of this on the heap instead of a pointer
int z = *array; // z = 1
int* arrp2 = array + 3; // points to 4 in array

- Struct
a piece of memory that contains multiple fields

- Hash Map
values into the hash() function, which returns an index for the hash buckets array
an array of pointers to linked lists
if multiple values have the same index, chain together nodes
if load factor is too high, increase size of array and rehash everything

-Tree Map / Binary Search Tree


for each node, left child is smaller, right child is larger
when searching, O(log n) // only have to search 1 of 2 paths per node
- Heap
minHeap: every parent is smaller than its children
children of parentIndex: 2 * parentIndex and 2 * parentIndex + 1
to remove: get rid of root node, move last node and place on top, bubble down
switch with smallest child always

- Graph
set of vertices and edges
directed edge: only goes one way
cycle: mark every node checked on path, check every possible path
recursive backtracking, use set

- Depth First Search


search the deepest possible path first, follow path to the end
recursively backtrack as deeply as possible

- Breadth First Search


store shortest paths, iteratively look through from set of paths
check every single path of increasing length from smallest to largest

5/22 Section: Graphs

Detecting cycles

static bool containsCycles(BasicGraph &graph) {


Set<Vertex*> beingLookedFor;
Set<Vertex*> prevVisited;
Set<Vertex*> toBeVisited = graph.getVertexSet;

while (!toBeVisited.isEmpty()) {
Vertex* v = toBeVisited.front(); // grabs an element from the front of the set
Set<Vertex*> beingLookedFor;
if (isReachable(v, graph, beingLookedFor, prevVisited)) return true;
toBeVisited -= prevVisited;
}

return false;
}

bool isReachable(Vertex* currVertex, BasicGraph& g, Set<Vertex*>& beingLookedFor,


Set<Vertex*> prevVisited) {
if (beingLookedFor.contains(currVertex)) return true; //there is a cycle, currVertex
//is in current path
if (prevVisited.contains(currVertex)) return false; // already checked this node and it has
// no cycles

beingLookededFor.add(currVertex); // add node to current path


for(Vertex* v : g.getNeighbors(currVertex)) { // iterate through all neighbors of node
if (isReachable(v, g, beingLookedFor, prevVisited)) return true; // recurse
}
beingLookedFor.remove(currVertex); // remove this node from the current path
prevVisited.add(currVertex); // add this node to the nodes that dont have cycles
return false; // there are no cycles
}

5/15 Section: HashMaps

void myHashMap::add(string key, int val) { // :: means to be part of the hashmap class
int index = hash(key);
node * curr = buckets[index];
if (curr == NULL) {
node* newNode = new node;
newNode -> key = key;
newNode -> value = val;
curr = newNode;
} else {
while (curr != NULL) {
if (curr -> key == key) {
curr -> value = val;
return;
}
curr = curr -> next;
}
// now that curr == NULL, you dont know where you are, so append new node in
the beginning instead of at the end
node* newNode = new node;
newNode -> key = key;
newNode -> value = val;
curr = buckets[index]; // keeps a handle on the linked list
buckets[index] = newNode;
newNode -> next = curr;
}
size++;
if (((double)size) / numBuckets > MAX_LOAD) { // check load factor
resize();
}
}

void myHashMap::resize() { // resize the array to be 2*original size + 1 and then go through
every single node in the array and rehash them
int oldBuckets = numBuckets;
numBuckets = numBuckets*2 + 1; // want numBuckets to stay odd
node** newBuckets = new node*[numBuckets];
for (int i = 0; i < numBuckets; i++) {
newBuckets[i] == NULL; // makes sure everything is null, no garbage memory
}
for (int i = 0; i < oldBuckets; i++) {
while (buckets[i] != NULL) { // pull node from front of linked list, change pointer
node * curr = buckets[i];
if (buckets[i] -> next != NULL) buckets[i] = buckets [i] -> next;
int index = hash(curr -> key);
curr -> next = newBuckets[index];
newBuckets[index] = curr;
}
}
delete buckets[];
buckets = newBuckets;
}

5/9

- Heapsort
1. Insert unsorted elements one at a time into a heap until all are added
2. Remove them from the heap one at a time (remove the next biggest item for max-heap; next
smallest item for min-heap)

5/5

#ifndef // if not defined


#define // then define it

--

IntVector::IntVector() { // declares a class


this->data = new int[10]; // dynamically allocated memory; have to delete!
this->count = 0;
this->capacity = 10;
}

IntVector::~IntVector() { // destructor function


delete [] data;
}

void IntVector::set(int index, int value) {


if (index < 0 || index > count-1) {
error(Vector index out of bounds.);
}
data[index] = value;
}

void IntVector::clear() {
count = 0;
delete [] data;
capacity = 10;
data = new int[capacity];
}

void IntVector::isEmpty() const {


return count == 0;
}

--

- structure of a .h file
// foobar.h
#ifndef __foobar_h // protection in case multiple .cpp files include foobar.h
#define _foobar_h // so that contents wont get declared twice
#endif

- operator overloading

bool operator <(IntVector& v1, IntVector& v2); // .h


bool operator <(IntVector& v1, IntVector& v2) { // .cpp
statements;
};

5/2
- to copy over a new array, have to iterate through
- delete [] data // deletes an array called data on the heap

5/1

struct coord { int a; int b; } // houses multiple pieces of data in an abstraction

int y = 3; // declares y = 3 on stack


int * x = &y; // x on stack points to y = 3 on stack
int j = 3; // declares j = 3 on stack
x = &j; // x points to j
coord * p;
p = new coord; // new puts something on heap that points (on stack) points to
// returns a pointer to the object created on the heap
p -> a = 7; // sets a in p on heap as 7; arrow dereferences it for you
p -> b = 3;
y = p -> a; // sets y = 7
x = & (p -> a); // x now points to p -> a (7)

--

linked lists: a struct containing an integer and a pointer to the next one

4/25

- f1 is O(f2) iff f1 <= c * f2 (c is a constant), after some point n0

4/7

- ifstream // input file stream; always pass by &reference


- reverse polish notation (postfix): 4 3 * 4 3 * + // * operates on 4 and 3
// equivalent to (4*3) + (4*3)
- stacks and RPN: encounter a number, PUSH; an operator, POP
43*725*++ // 12 7 2 5 * + + 12 7 10 + + 12 17 +
- stack.h stacks, simpio.h getline, <iostream> cout, <fstream> file operations
- to read a file with stacks:
ifstream infile;
string name = getLine(File to open: );
infile.open(name);
-OR-
promptUserForFile(infile,File to open: ); // in filelib.h
- QT Creator: put files to use in resources file

4/4

- concatenating C-style strings


string s = hi;
s += !; //works

string s = hi + !; // does not work

- string.find
string name = Donald Knuth;
if (name.find(Knu) != string:npos) {
name.erase(7.5) // Donald
}

- vector: encapsulation of elements of the same type

- grid: 2D vector
Ex. Queen Safety

#include grid.h

int main() {
Grid<bool> board(8,8);
clearBoard(board);
return 0;
}

static void clearBoard(Grid<bool> board){


for (int i = 0; i<board.numRows(); i++) {
for (int j = 0; j<board.numCols(); j++) {
board[i][j] = false;
}
}
}

4/2

- declare functions first / above main(), sometimes unable to order functions in a way such that it
is implemented before it is used (mutual recursion; functions call each other)
- header
#include <iostream>
#include console.h // Stanford library
using namespace std;
- cout << // console output
- cin >>
- endl; // make a new line
- recursion: when a function calls itself
- int main() {
cout << stuff << endl;
getLin(); // allows for us to see stuff before main exits
return 0;
}
- int& //int reference, affects originally copy of int

You might also like