CPT-Graphs-directed-weighted-ex1.svg

How to do stuff RESTfully

REST, standing for Representational state transfer, it lets the browser interact with the server and get things done without knowing anything about the server, the resources it has and the background operations used to perform the requested task. I far prefer REST APIs over SOAP any day! Take a look at the RESTful cookbook below to become familiar with Howto’s and best practices. This will by far make your interactions between server and client cleaner and easier! Pretty much any website I develop, I keep REST in mind, it will make future operations and scaling smoother.

– The RESTful cookbook

REST is hot! And REST is finally rediscovered by API programmers all over the world. But REST isn’t always as easy as it seems on first look. Dealing with HATEOAS, Code on demand and uniform interfaces can be really tricky and many people will fall back to not-so-restful approaches when things are starting to become more difficult. But it doesn’t need to be. Once you get to know REST, you will like it.

CPT-Graphs-directed-weighted-ex1.svg

Linked List Remove All

Here is a short insert on how to remove all Nodes of X value from a list. I use recursion and I believe I’ve created a pretty clean solution. This requires Nodes found in my earlier post.

#include "Node.h"

Node* head; //contains the head of our linked list

//Run the search and remove on the linked list starting at the head
//target is the value we are trying to remove from our list
void searchAndRemove(int target){
    searchAndRemove(target, head);
}


void searchAndRemove(int target, Node*& n){
    if(n != nullptr){
      if(n->data == target) { //if we found our target
        Node* temp = n;
        n = n->next; //delete and replace
        delete temp; //delete the node to clean up memory
        searchAndRemove(target, n); //continue the search, we need this to check the one used to replace
      } else {
        searchAndRemove(target, n->next); //continue the search
      }
    }
}

Let me know if you have any comments or improvements!

CPT-Graphs-directed-weighted-ex1.svg

Binary Search Tree Traversals in C++

So this will pretty much wrap up our short expedition into binary trees. Remember that these functions rely on my earlier posts dealing with the class and nodes.

The three types of traversals we will look at are:

  • Preorder (root, left, right)
  • Inorder (left, root, right)
  • Postorder (left, right, root)

Preorder Traversal

This type of traversal can be used to create duplicates of a tree and can be used to implement prefixes. Whatever order of values you put into a tree will be the order that preorder traversal gives you. So If I enter, 5 7 4 2 1 9 8 3 6 into a binary tree, when I use preorder traversal, I will expect to see 5 7 4 2 1 9 8 3 6.

void preorderTraversal (Node* n) {
    if (n != nullptr) { //make sure we have a value
        cout << n->data << endl; //Print out the current Node value
        preorderTraversal(n->left); //traverse down the left side
        preorderTraversal(n->right); //Once we return from the left, go down the right
    }
}

Inorder Traversal

This type of traversal will return data sorted in order. So if I entered, 5 7 4 2 1 9 8 3 6, I would expect to see 1 2 3 4 5 6 7 8 9.

  void inorderTraversal (Node* n) {
    if (n != nullptr) { //make sure we have a value
        inorderTraversal(n->left); //traverse down the left side
        cout << n->data << endl; //Print out the current Node value
        inorderTraversal(n->right); //Once we return from the print, go down the right
    }
}

Postorder Traversal

This type of traversal can be used to implement postfixes and can cleanly be used to destroy a tree with out leaving Nodes floating around corrupting memory. So if I entered, 5 7 4 2 1 9 8 3 6, I would expect to see 1 3 2 4 6 8 9 7 5

 void postorderTraversal (Node* n) {
    if (n != nullptr) { //make sure we have a value
        postorderTraversal(n->left); //traverse down the left side
        postorderTraversal(n->right); //Once we return from the left, go down the right
        cout << n->data << endl; //Print out the current Node value
    }
}

For more information on binary trees, I would checkout this article. It goes into detail on how traversals on called on the tree and gives some great visuals. I also liked this interactive visual for binary search trees in general.

Good luck!

CPT-Graphs-directed-weighted-ex1.svg

Sweet Binary Search Tree Print in C++

I found the basis of a print on Stackover flow the other day and changed it a little bit to be more compatible across compiler versions.

Happy Coding!

void print() {
    print(root, 0); //call it on your root/head node
}

For some reason my code editor wouldn’t do the left slashes so below is a screenshot.

Here is an example of what it will look like for the sequence 5 7 4 2 1 9 8 3 6:

CPT-Graphs-directed-weighted-ex1.svg

Binary Search Trees! Simple Class in C++

Here is a really basic binary tree class, it just includes the basics of creating, inserting, erasing, and returning size. In later posts I will talk about printing and traversals.

This class also uses the Node.h talked about in this earlier post. You’ll notice that I really like to use recursion, I think this is cleaner than looping.

#include <assert.h>
#include "Node.h"
using namespace std;

class Bst
{
    public:

        //constructor for when a head Node is provided and when it is not
        Bst() {
            root = nullptr;
        }

        Bst(Node *np) {
            root = np;
        }

        //destroy the tree, we need to go through and destroy each node
        ~Bst() {
            destroyTree(root);
        }

        //get the number of nodes in the tree
        int size() {
            return size(root);
        }

        //erase a value in the tree
        void erase(int item) {
            erase(item, root);
        }

        //insert a Node in the tree
        void insert(int item) {
            insert(item, root);
        }

    private:

        Node* root;

        //Go through each branch and recursively destroy all Nodes
        void destroyTree(Node*& n) {
            if (n != nullptr) {
                destroyTree(n->left);
                destroyTree(n->right);
                delete n;
            }
        }

        //For each Node return the number of left and right nodes
        //Add it up recursively to get the total size
        int size(Node* n) {
            if (n != nullptr) {
                int left = size(n->left);
                int right = size(n->right);
                int self = 1;
                return left + self + right;
            }
            return 0;
        }

        //Find the minimum Node value
        Node* findMin(Node* n){
            assert(n != nullptr);
            if (n->left != nullptr) {
                return findMin(n->left);
            }
            return n;
        }

        //this one is a beast
        //look through all the nodes recursively
        //once you find the node value there are numerous cases we need to look for
        //If the current node does not have left and right nodes, just delete it
        //If it does have a left or right node, set the child to the parent
        //If it has both left and right, we need to work some magic. First we find
        //the smallest value and set the node we want to delete to that value (removing it)
        void erase(int item, Node*& n) {
            if (n != nullptr) {
                if (item == n->data) {
                    if (n->right == nullptr && n->left == nullptr) {
                        delete n;
                        n = nullptr;
                    } else if (n->right == nullptr) {
                        Node* temp = n;
                        n = n->left;
                        delete n;
                    } else if (n->left == nullptr){
                        Node* temp = n;
                        n = n->right;
                        delete n;
                    } else {
                        Node *temp = findMin(n->right);
                        n->data = temp->data;
                        erase(item, n->right);
                    }
                } else if (item < n->data) {
                    erase(item, n->left);
                } else {
                    erase(item, n->right);
                } 
            }
        }

        //look through all the nodes
        //insert the node on the correct node, it will be added to the left if the value is less
        //added to the right if the value is greater
        void insert(int item, Node*& n) {
            if (n != nullptr) {
                if (item < n->data) {
                    insert(item, n->left);
                } else {
                    insert(item, n->right);
                }
            } else {
                n = new Node(item);
            }
        }
};

Let me know if you have any improvements or comments!

CPT-Graphs-directed-weighted-ex1.svg

Reading a File with C++

Here is just a simple example of reading a file with iostream. Just follow my comments to understand.

Good luck, sometimes newlines and spaces can mess you up, you may need to utilize an ignore() or something else.

#include <fstream>
#include <iostream> 
using namespace std;

void evaluateFile(string ins); //Do something with the file contents
void readFile(); //Read the file

int main(){
    readFile();
    return EXIT_SUCCESS;
}

void readFile(){
    ifstream input;
    string fileName;
    cout << "What is the full path of file to be read" << endl;
    getline(cin, fileName); //Prompt user for filename, needs to be the fill path
    input.open(fileName); //Open thhe file
    if (input.fail()){ //Fail case
        cout << "Sorry, cannot open file. Quitting now." << endl;
        exit(0);
    }
    while(!input.eof()){ //Read file until the end of file is reached
        string line;
        getline(input, line);
        evaluateFile(line);
    }
    input.close();
}

void evaluateFile(string line){
    cout << line << endl;
    //DO SOMETHING WITH THE FILE INPUT
}
CPT-Graphs-directed-weighted-ex1.svg

Setting a timer in C++

I wanted to time some functions to measure performance of different types of functions in order to find what action was optimal. Here is my code for measuring the time of a C++ action.

Basically, you collect a start clock() and a end clock() then find the total time it took to perform something by taking the difference between the two. By default the clock() function uses the CLOCKS_PER_SEC variable to convert the found clocks to seconds. My code shows how to get the result in seconds and Microseconds.

Happy Coding!

#include <time.h> //Need this for clock()

int main() {
    int seconds_to_micro = 1000000; //conversion from seconds to microseconds var 
    
    clock_t start = clock(); //Get starting point clock
    
    //***********PERFORM AN ACTION HERE********
    
    clock_t end = clock(); //Get ending point clock
    
    float time_in_seconds = static_cast<float>(end - start)/ CLOCKS_PER_SEC //in seconds
    float time_in_microseconds = static_cast<float>(end - start)/ CLOCKS_PER_SEC * seconds_to_micro; //in microseconds
    
    return;
}
CPT-Graphs-directed-weighted-ex1.svg

Intermediate and Advanced Software Carpentry in Python

I am taking a slight break from C++, going back to Python, one of my favorite languages ever! I found the following material on structuring Python code and it is great! Posting it here so I can always come back to it. I recommend it to all the Python enthusiast looking at ways to improve their coding structure.

Intermediate and Advanced Software Carpentry in Python

Welcome! You have stumbled upon the class handouts for a course I taught at Lawrence Livermore National Lab, June 12-June 14, 2007. These notes are intended to accompany my lecture, which was a demonstration of a variety of “intermediate” Python features and packages. Because the demonstration was interactive, these notes are not complete notes of what went on in the course. (Sorry about that; they have been updated from my actual handouts to be more complete…) However, all 70 pages are free to view and print, so enjoy.

CPT-Graphs-directed-weighted-ex1.svg

Simple List Class in C++

Here is an example of a simple List class I wrote. Follow the comments to understand what is going on. This uses the node structure I wrote about here.

Best of luck!

#include <cstdlib>
#include "Node.h" //Your Node class, see previous post

using namespace std;

class List
    {
        public:
            List(){
                head= NULL;
            }
            ~List(){
                destroyList(head);
            }
            void append(int d){
                head = append(head, d);
            }
            void print(){
                if (head != nullptr)
                print(head);
            }
            void insertInOrder(int d){
                head = insertInOrder(head, d);
            }
            bool findValue (int d){
                return findValue(head, d);
            }
            int getSize(){
                return getSize(head);
            }
    
        private:
            Node *head; //Remember this struct from the previous post

            /* Destroy the list
            * We recursively call the destroy function to cycle through a list to the end.
            * Once the end node is reached, it is deleted. Then as we progress back through
            * our recursive call, each associated node is deleted from the end up.
            * This is called by our destructor to clean everything up.
            */
            void destroyList(Node *n){
                if (n->next != nullptr){
                    destroyList(n->next);
                }
                delete n;
            }

            /* Add a Node to the end of a list
            * Use recursion to cycle through the list to the end
            * Once the end is reached, the next pointer of the last node will by nullptr.
            * A new Node will then be inserted replacing that nullptr and chaining to the list
            */
            Node* append(Node *n, int d){
                if (n == nullptr){
                    return new Node(d);
                }
                else {
                    n->next= append(n->next, d);
                }
                return n;
            }

            /* Print the List
            * Use recursion to loop through and print each Node in a list
            */
            void print(Node *n){
                cout << n->data << endl;
                if (n->next != nullptr){
                    print(n->next);
                }
            }

            /* Insert a Node in Numeric order
            * Loop throug a list using recursion
            * Once the inserting value is less than the current Node
            * we know we need to insert the Node in that position
            * else we keep cycling through
            */
            Node* insertInOrder(Node *n, int d){
                if (n == nullptr){
                    return new Node(d);
                }
                else if (d > n->data){
                    n->next= insertInOrder(n->next, d);
                }
                else {
                    Node* temp = n; //Temp copy
                    n = new Node(d); //Set the pointer to a new Node
                    n->next = temp; //Chain the original onto the new Node's next pointer
                }
                return n;
            }

            /* Find a Node
            * Loop through the enitre list using recursion
            * Return true once the Node value we want is found
            */
            bool findValue(Node *n, int d){
                if (n->data == d){
                    return true;
                }
                else if(n->next != nullptr){
                    return findValue(n->next, d);
                }
                return false;
            }

            /* Get the Size of a List
            * Use recursion to cycle through the list
            * all the while keeping a counter going of each Node encountered
            */
            int getSize(Node *n, int i = 0){
                if (n != nullptr){
                    ++i;
                    return getSize(n->next, i);
                }
                return i;
            }

    };
CPT-Graphs-directed-weighted-ex1.svg

The typical Node structure in C++

The next couple of posts are going to require the use of a node object. I’ve seen people make the node way more complicating then it should be as a class. The point of a node is to hold data and be aware of it’s neighbors. All you really need is a simple struct.

In the instance of a stack or list, a node just really needs to know who’s next after them. Note in the code below, to create a node, I need some data passed in, that’s it. It’s up to the coder to set the next pointer in their code that is utilizing the node.

struct Node
{
    int data;
    Node* next;

    Node(int d){
        data = d;
        next = nullptr;
    }
};

When we start looking at linked lists and binary search trees, we might consider a struct that is aware of the nodes on both sides of it. Again, it is up to the code using the node structure to set the left and right pointers to the right node neighbors.

struct Node
{
    int data;
    Node* left;
    Node* right;

    Node(int d){
        data = d;
        left = nullptr;
        right = nullptr;
    }
};

Pretty dang simple!