Sunday, November 16, 2014

Finite Automata Regular Expression Generator in Java

 Hailey Hanson
    HaileyLHanson@gmail.com
  
Here is a regular expression engine written in Java. The program reads in a text file as regular expressions separated by new lines.
The regular expressions are taken in in postfixed notation and then created into Nondeterministic Finite Automata (NFA).

To build the software, the text file titled test.txt will need to be present. The file can then be run within a Java compiler(I used Eclipse Kepler).

The files included in this archive are:

1) Main.java  
    My main program that calls upon my other processes
  
2) Machine.java
    Where the bulk of my program sits and constructs NFAs from reading Regular Expressions in through a text file
  
3) FinAut.java
    Where my Finite Automata object is stored
  
4) Transition
    This is where my regular expression transitions are stored as linked lists


******************************************************


package home;

//import Machine;

public class Main {

    public static void main(String[] args) {
        new Machine();

    }

}


*****************************************************
 
package home;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;

public class Machine {

    private BufferedReader br;
    private String line;
    int i = 0;

    private LinkedList FAmachine;    //linkedlist of machines that will be stuck together
    private int currentState = 0;
    private FinAut FA1; // FinAut
    private FinAut FA2;

    public Machine()
    {
        FAmachine = new LinkedList();

        try
        {
            br = new BufferedReader(new FileReader("test.txt"));
        } catch (FileNotFoundException e1)
        {
            e1.printStackTrace();
        }// read in a line from RE
   
        int i = 0;
        char c;

            try
            {
                while ((line = br.readLine()) != null)
                {
                    for (i = 0; i < (line.length()); i++)
                    {
                        c = line.charAt(i);
                        System.out.println(c);

                        if (c == '&')
                        {
                            FA2=FAmachine.pop();
                            FA1=FAmachine.pop();
                            FA1.listOfTransitions.add(new transition(FA1.endState,FA2.startState,'E')); //add epsilon transition onto end of FA1
                            while (!FA2.listOfTransitions.isEmpty()){//while not at end of list
                                FA1.listOfTransitions.add(FA2.listOfTransitions.remove());//take end of FA2 and put at end of FA1
                            }
                            FA1.endState = FA2.endState; //make FA1 into the new single FA
                            FAmachine.push(FA1);// push(NFA that accepts the concatenation of
           
                            for(i=0;i                                System.out.println(FA1.listOfTransitions.get(i).state1 +" "+ FA1.listOfTransitions.get(i).state2 + " " + FA1.listOfTransitions.get(i).symbol);
                            }//end of for loop
                        }
                               
                        else if (c == '+')// push(NFA that accepts L(nFA1) + L(nFA2));
                        {
                            FA2 =FAmachine.pop();
                            FA1 = FAmachine.pop();
                            FA1.listOfTransitions.add(new transition(currentState++, FA1.startState, 'E'));//epsilon from new start to FA1 old start
                            FA1.listOfTransitions.add(new transition(currentState-1, FA2.startState, 'E'));//epsilon from new start to FA2 old start
                            FA1.listOfTransitions.add(new transition(FA1.endState, currentState++, 'E'));//epsilon from FA1 end to new end
                            FA1.listOfTransitions.add(new transition(FA2.endState, currentState-1, 'E'));//epsilon from FA2 end to new end
                           
                            FA1.startState = currentState-1;//update FA1 start to new start
                            FA1.endState = currentState; //update FA1 end to new end
                           
                            //take transitions from errthang and put into FA1
                            while (!FA2.listOfTransitions.isEmpty()){//while not at end of list
                                FA1.listOfTransitions.add(FA2.listOfTransitions.remove());//take end of FA2 and put at end of FA1
                            }
                            for(i=0;i                                System.out.println(FA1.listOfTransitions.get(i).state1 +" "+ FA1.listOfTransitions.get(i).state2 + " " + FA1.listOfTransitions.get(i).symbol);
                        //    System.out.println("+");
                           
                        } else if (c == '*')
                        {
                            FA2 =FAmachine.pop();
                            FA1 = FAmachine.pop();
                            FA1.listOfTransitions.add(new transition(currentState++, FA1.startState, 'E'));//epsilon from new start to FA1 old start
                            FA1.listOfTransitions.add(new transition(currentState-1, FA2.startState, 'E'));//epsilon from new start to FA2 old start
                            FA1.listOfTransitions.add(new transition(FA1.endState, currentState-1, 'E'));//epsilon from FA1 end to new start
                            FA1.listOfTransitions.add(new transition(FA2.endState, currentState-1, 'E'));//epsilon from FA2 end to new start
                            FA1.listOfTransitions.add(new transition(currentState++, FA1.startState, 'E'));//make all new start state with epsilon transition
                           
                            FA1.startState = currentState-1;//update FA1 start to new start
                           
                            //take transitions from errthang and put into FA1
                            while (!FA2.listOfTransitions.isEmpty()){//while not at end of list
                                FA1.listOfTransitions.add(FA2.listOfTransitions.remove());//take end of FA2 and put at end of FA1
                            }
                            for(i=0;i                                System.out.println(FA1.listOfTransitions.get(i).state1 +" "+ FA1.listOfTransitions.get(i).state2 + " " + FA1.listOfTransitions.get(i).symbol);
                        } else
                        {
                            FAmachine.push(new FinAut(currentState++, currentState++, c));
                            //System.out.println("c = " + c);
                        }

                        // System.out.println(line.next());
                        //System.out.println("line # ");

                    }
                }
            } catch (IOException e)
            {
                e.printStackTrace();
            }// end of while

        finally {
            if (br != null)
            {
            //    br.close();
            }
   
        }
    }
}// end of class Machine

******************************************************


package home;

import java.util.LinkedList;

public class FinAut {

    public int startState;
    public int endState;
    public LinkedList listOfTransitions;
   

    public FinAut(int start, int end, char c) {

        this.startState = start;
        this.endState = end;
        listOfTransitions = new LinkedList();
        listOfTransitions.add(new transition(startState, endState, c));

    }// end of FinAut method
}// end of FinAut class
 

************************************************

package home;

public class transition {
    int state1;
    int state2;
    char symbol;
   
    public transition(int startState, int endState, char c){
        this.state1=startState;
        this.state2=endState;
        this.symbol=c;
       
    }//end of transition method

}//end of class transition

Sunday, November 9, 2014

*ATTENTION*

I will be moving to a self-hosted blog in the (very) near future.

My new blog will be more up-to-date, so swing back by for the commencement of a new URL!

Wednesday, May 21, 2014

Linked List of Lists: Listception

My second assignment was pretty cool since I started separating things out into several classes (separated here by comment lines). The program description is below.

package hanson_h_2;

//hailey hanson
//Programming Assignment 2
//April 30th, 2014
//
//This program will read in from a text file, separate the words and get rid of punctuation and lowercase letters (making them all caps)
//then it will sort the words into alphabetical order and print them in a list that includes the numbered position
//of the word so that instead of listing a word twice, it will be listed as word: #occurance, #occurance, etc.
//

public class hanson_h_2{

public static void main(String[] args) {

wordIndex wi = new wordIndex("C:\\Users\\vicki\\Desktop\\java_text_file.txt");
}
}
/********************************************************************/

package hanson_h_2;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class wordIndex {

boolean statusVar;
wList myList = new wList();

int counter=0; //will keep track of word numbers

public wordIndex(String filename) {

Scanner s = null;
String word = null;

try {
s = new Scanner(new File(filename));
while(s.hasNext()){
word = s.next();
word = word.toUpperCase();
word = word.replaceAll("[^a-zA-Z]",  "");
counter++;
myList.add(word, counter);
statusVar = true;
}
} catch (FileNotFoundException e) {
statusVar = false;
}
print();
}

boolean status(){
if (statusVar == true)
return true;
else
return false;
}

void print(){
// prints the sorted list of words - one per line - followed by a space-separated
// list of references (in increasing order). The reference is the word #,
// beginning with 1 for the first word, 2 for the second, etc.
if(status() == true)
myList.print();
else if (status() == false)
System.out.println("Sorry, couldn't open file");


}

}

/********************************************************************************/

package hanson_h_2;

public class wList {

wNode header; //this is the sentinel node

public wList() {//not sure about these parameters
header = new wNode(null, null);//empty list (header points to zero and is zero and stuff)
}//end of wList constructor

void add(String data, int index){ //will add new wNode onto wList in alphabetical order
wNode newNode = null;

if (header.next == null){ //if list is empty
newNode = new wNode(data, header.next);
header.next = newNode;
newNode.list = new rList();
newNode.list.add(index);
}//end of if statement

else{ //there is already at least one thing in the list
wNode traverseNode = header.next; //will step through list to check for comparisons between these 2 nodes

while (traverseNode != null){//look through wList
if (data.equals(traverseNode.data)){ //if two wNodes have the same data
traverseNode.list.add(index); //add the index of the word onto the rList
return; //get outta town... add method town
}//end of if statement

traverseNode =  traverseNode.next; //move to  next node in wList
}//end of while loop

traverseNode = header.next; //if the node is not already in wList, move back to beginning of wList
wNode previousNode = header;

while (traverseNode != null){
if (data.compareTo(traverseNode.data) < 0){
newNode = new wNode(data, traverseNode); //make new node and put it in before right node
previousNode.next = newNode; //change previous pointer
break;
}//end of if statement
if (traverseNode.next == null){ //if this is the last thing in the list
newNode = new wNode(data, traverseNode.next); //make your node with the data piece, put it at end
traverseNode.next = newNode; //switch previous node's pointer to point to new node
break;
}//end of if statement
previousNode = traverseNode;
traverseNode = traverseNode.next; //move along through wList
}//end of while loop

newNode.list = new rList();
newNode.list.add(index);//add index number to the rList

}//end of else
}//end of add method

public void print(){
wNode currentNode = header.next; //start at beginning on wList
while (currentNode != null){
System.out.print(currentNode.data);//print the word
currentNode.list.print(); //print its position
System.out.println("\n"); //print a newline
currentNode = currentNode.next; //go to next node
}//end of while
}//end of print()

public class wNode
{

String data; //the data will be a word from my index
wNode next; //pointer to next node
rList list; //header node to rList. Is number associated with word

public wNode(String data, wNode next){
this.data = data;
this.next = next;
}//end of wNode constructor
}//end of wNode class
}//end of wList class

/********************************************************************************/

package hanson_h_2;

public class rList {

rNode header;

public rList() {
header = new rNode(0, null);
}

void add(int ref){  //adds word to list and ref to the end of the list
rNode currentNode = header.nextNode;

if (header.nextNode == null){
rNode newNode = new rNode(ref, header.nextNode);
header.nextNode = newNode;
}
else {
while(currentNode.nextNode != null) //while i am not at the end of the list
currentNode = currentNode.nextNode; //step forward one node
rNode newNode = new rNode(ref, currentNode.nextNode);
currentNode.nextNode = newNode;
}
}

public void print(){
rNode currentNode = header.nextNode;
while (currentNode != null){
System.out.print(" " + currentNode.index);
currentNode = currentNode.nextNode;
}
}

private class rNode {

int index; //data piece of node to tell where word is located in file
rNode nextNode; //pointer to next node
//should maybe set nextNode equal to null...?

public rNode(int ref, rNode next) {
index = ref;
nextNode = next;
}

}

}

The Beginnings of Java: Rational Numbers Program

So here I am just under a month away from my summer vacation. I met with an adviser this morning at WSU-Vancouver and decided that I won't be taking a class this summer since it won't take any time off of my last two years of school. So this means that my near future will consist of making coffee, enjoying the sun and hopefully getting a clue on GitHub. My adviser advised me (ha) to think about taking on an English minor since I told her I really like writing. I'm kind of torn, though, since I can't see giving more time and money to school while I'm already struggling to pay my tuition for the next two years.

The struggle is real.

I started working at a coffee shop a few weeks ago, on top of my Physics TA job, so I've been extremely busy trying to balance those, a Tech Writing class and also learning Java!
I meant to post my Java Hello World program forever and a day ago, but now it seems insignificant since I'm doing big scary programs like this. This was my first assignment in my Advanced Data Structures class and, as I've mentioned, I love clean, organized writing so I like this code :)

//Hailey Hanson
// April 18, 2014
//Programming Assignment 1-Rational Numbers
//
//This program will take in rational numbers and add, subtract, multiple, divide, reduce and convert them to doubles (if prompted)
//

public class Rat {

private int num; //numerator of fraction
private int denom; //denominator of fraction

Rat (int num, int denom)//will be referenced when there are two inputs
{
this.num = num;
this.denom = denom;
}

Rat (int num)//will be referenced with there is one input
{
this.num = num;
this.denom = 1;
}

public int num() //returns numerator of x (a rational number)
{
return num; //return x's numerator piece
}

public int denom()
{
return denom; //returns x's denominator piece
}

public Rat add(Rat n) //adds "this" Rat to n Rat
{
int newnum = (this.num()*n.denom())+(this.denom()*n.num()); //makes new numerator
int newdenom = (this.denom()*n.denom()); //makes new denominator
Rat newRat = new Rat(newnum,newdenom);//makes new Rat using new num and denom
newRat.reduce();
return newRat;
}

public Rat sub(Rat n) //subtracts "this" Rat and n Rat
{
int newnum = (this.num()*n.denom())-(this.denom()*n.num());//makes new numerator
int newdenom = (this.denom()*n.denom());//makes new denominator
Rat newRat = new Rat(newnum,newdenom);//makes new Rat
newRat.reduce();
return newRat;
}

public Rat times(Rat n) //multiplies "this" Rat and n Rat
{
Rat newRat = new Rat(n.num()*this.num(), n.denom()*this.denom());//makes new Rat
newRat.reduce();
return newRat;
}

public Rat div(Rat n)//divides "this" Rat and n Rat
{
Rat newRat = new Rat(this.num()*n.denom(), n.num()*this.denom());//makes new Rat
newRat.reduce();
return newRat;
}

public double toDouble()//converts Rat to a double
{
if (this.denom == 0)//if undefined
{
if (this.num()>0)//undefined and positive = infinity
{
return(Double.POSITIVE_INFINITY);
}
else if(this.num() == 0)//undefined and 0 = NaN
{
return(Double.NaN);
}
else if (this.num() <0 and="" negative="-infinity</p" undefined=""> {
return(Double.NEGATIVE_INFINITY);
}
}
return ((double) this.num()/this.denom());
}

private int GCF(int a,int b)//find greatest common factor to use in reduce method
{
if (a%b ==0) return b;
else while(a%b != 0)
{
int x = a%b;
a=b;
b=x;
}
return b;
}

public void reduce()//would normally be private, but will be public for testing purposes
{
if (denom !=0)
{
if(num == 0)
{
denom = 1;//special request for assignment
}
else
{
int gcf = GCF(num, denom);
num=num/gcf; ///reduce numerator
denom=denom/gcf;//reduce denominator
}
}
}

public void print() //print method
{
this.reduce(); //reduce Rat  before printing

if(denom == 1)
{
System.out.println(num);//reduce fractions with denominator of 1
}
else if (denom < 0 )
{
System.out.println(this.num*(-1) + "/"+ (-1)*this.denom()); //fix negative fractions
}
else
{
System.out.println(this.num() + "/" + this.denom()); //print normal rational fraction
}
}
}

Saturday, April 12, 2014

New Quarter - New Opportunities

Hello Blog-Readers!

          I finished out last quarter with my best GPA so far in college and although it wasn't quite as high as I was hoping, I'm still really happy with how it turned out.
         This was nice going into spring break because I was feeling good by the time I took a cross-country (vertically) roadtrip to Arizona to see my brother and meet my nephew :)
          I also stopped in some very cool places along the way including the Hoover Dam, the Grand Canyon and Zion National Park (which is totally my new second favorite place after Arches National Park)

 Just look how cool it is!!!(Yes, that's me up there)

          But anyway, I started Spring quarter last Monday and I'm really excited about my programming class. I'm taking advanced data structures and this will be my first class taught in Java. I'm really glad to be starting something more high-level and visual because C was feeling pretty dry after a year and a half on the command line.
          I also went to the North West regional Women in Computer (NWrWIC) conference today in Portland. This was definitely my favorite conference yet. I'm starting to feel more comfortable and less like I'm the biggest amateur in the room (which, yeah, I know, I've never really been), but I'm just feeling a lot more comfortable. I also went into this conference assuming that all Summer 2014 internships were already filled, so I didn't put pressure on myself to network much and it turned out to be my best networking yet! I'm up tonight applying for internships at Puppet Labs in Portland and Intel in Hillsboro. I'd be completely psyched to get either of these, so we'll see!
       

Thursday, March 13, 2014

Autonomous Vehicle Project

I and my two lab partners spent about three weeks programming a PICchip, in assembly language, to move this truck in an oval and have it return to the spot it started at. We used pulse width modulation, interrupts and a lot of tweaking of timing to make it loop and return to the same spot.

Something we noticed during our trials was that the truck ran at different speeds depending on how long it had been running for. When we realized that warming our truck up first would give more consistent results, we began warming it up before each test.


Bubble Sort in Assembly Language

Here's a homework assignment where I had to implement a bubble sort in Assembly Language. My professor gave us specific values to put into the first 8 data memory locations, then we had to sort those values and keep them all in those first 8 spaces in memory.
I love this code. Very simple, clean and best of all, it works!

;------------------------
;FILE: main.asm
;DESC HW9
;Date: 3-10-2014
;Device: PIC18F1220
;-----------------------

                list p=18F1220
                radix hex
                config WDT=OFF, LVP=OFF

#include P18F1220.INC

I equ 0x50                                    ;make I register (somewhere out of the way)
INEXT equ 0x52                                ;make INEXT register (somewhere out of the way)
TEMP equ 0x54                                 ;make TEMP register (somewhere out of the way)

                MOVLW 0X00                    ;put 0 into WREG
                MOVWF FSR0L                   ;inititalize FSR0L to 0
                MOVWF INDF0                   ;initialize INDF0 to 0
                MOVWF I                       ;initialize I to 0
                MOVWF INEXT                   ;initialize INEXT to 0        
               

                                                                                                ;initialize locations 0x00-0x07 with numbers from assignment description
                MOVLW d'10'    
                MOVWF INDF0                    ;put decimal 10 into location 0
               
                INCF FSR0L                     ;FRS0=1. Location of INDF0=1
                MOVLW d'16'    
                MOVWF INDF0                    ;put decimal 16 into location 1

                INCF FSR0L                     ;FRS0=2. Location of INDF0=2
                MOVLW d'1'
                MOVWF INDF0                    ;put decimal 1 into location 2

                INCF FSR0L                     ;FRS0=3. Location of INDF0=3
                MOVLW d'5'
                MOVWF INDF0                    ;put decimal 5 into location 3

                INCF FSR0L                     ;FRS0=4. Location of INDF0=4
                MOVLW d'15'
                MOVWF INDF0                    ;put decimal 15 into location 4

                INCF FSR0L                     ;FRS0=5. Location of INDF0=5
                MOVLW d'11'
                MOVWF INDF0                    ;put decimal 11 into location 5

                INCF FSR0L                     ;FRS0=6. Location of INDF0=6
                MOVLW d'2'
                MOVWF INDF0                    ;put decimal 2 into location 6

                INCF FSR0L                     ;FRS0=7. Location of INDF0=7
                MOVLW d'6'
                MOVWF INDF0                    ;put decimal 6 into location 7

mainloop:

                MOVLW 0X01
                MOVWF FSR0L                    ;FSR0L is set to 1 so that bubble                                                ;loop will start at location 0
                BRA bubble

endloop:
                BRA endloop                    ;will probably never be reached...

switch:                                        ;will be accessed if two numbers                                                  ;need to be switched int he array
                MOVFF I, TEMP                  ;move contents of I into TEMP register
                MOVFF INEXT, I                 ;move contents of INEXT into I
                MOVFF TEMP, INEXT              ;move contents of TEMP into INEXT
                                                                                                                                 ;so now I is INEXT and INEXT is I
                DECF FSR0L                     ;go back one space in memory
                MOVFF I, INDF0                 ;put I into location of FSR0
                INCF FSR0L                     ;go to next location
                MOVFF INEXT, INDF0             ;put INEXT into next location of FSR0
                INCF FSR0L         

                MOVLW d'7'
                SUBWF FSR0L,W                  ;subtract 7 from FSR0L and store in WREG
                BNN mainloop                   ;if FSR0L>7, start new pass 
                                               ;(branch to mainloop

bubble:
                DECF FSR0L                     ;take FSR0 back one spot
                MOVFF INDF0, I                 ;move 10 into I register
                INCF FSR0L                     ;FSR0L is now 1. So looking at                                                    ;location 1 where 16 sits
                MOVFF INDF0, INEXT             ;move 16 into INEXT register
                                                                                                                                 ;compare I and INEXT
                MOVF I, W                      ;put value of I into WREG
                SUBWF INEXT, W                 ;subtract WREG(I) from INEXT
                BN switch                      ;if I>INEXT, branch to switch loop
                INCF FSR0L                     ;increment FSR0 so that the next                                                  ;loop will be looking at the next                                                ;location
                BRA bubble                     

                end

Friday, February 28, 2014

Assembly Language Incrementation code using FSR0 and INDF0

This was a homework code written for my microprocessors class a few days ago.  I thought I should  post something today since I'm going to be passing out business cards at the Society of Women Engineets conference today and tomorrow so if that's what brought you to my blog, then I'm glad you were curious enough to stop by!  Feel free to contact me via email or phone with any questions. My phone number is on my card as well. 
;--------------------------
;FILE: main.asm
;DESC HW8
;Date: 3-3-2014
;Device: PIC18F1220
;--------------------------

​list p=18F1220
​radix hex
​config WDT=OFF, LVP=OFF

#include P18F1220.INC

NUM EQU 0x21​​​;put NUM somewhere out of the way

​MOVLW 0x01​
​MOVWF NUM​​​;initialize NUM to 1
​MOVFF NUM, INDF0​​;initialize INDF0 to 1
​MOVLW 0X00
​MOVWF FSR0L​​​;initialize FRS0 to 0

loop:​​​​​;where incrementation will take place
​MOVLW d'2'​
​ADDWF NUM​​​;add decimal 2 to $NUM
​
​MOVLW 0x01
​ADDWF FSR0L​​​;increment FSR0 (0 to 15), also increments location of INDF0 from 0 to 15

​MOVFF NUM, INDF0​;move contents of NUM into INDF0

​MOVLW 0x0F
​SUBWF FSR0L,W​​;subtract 15 from FSR0L, store in WREG
​BNZ loop​​​;if FSR0 != 15, go back and loop again. Else proceed to endloop

endloop:
​BRA endloop​​​;Bask in glory of filling first 16 locations (0-15)

          end 

Wednesday, February 19, 2014

Binary Tree Builder and Editor

This code has been about a month in the making, adding on different pieces every week. I finished it a while ago and forgot to post it! I've been very busy with my classes and work lately (I work as a Physics TA at my college) so I haven't been keeping up with the internet world too much. I think I like this code, though. In the last couple weeks I've gotten away from my /****/ boxes /****/. They were nice while they lasted, but now I think they're looking kind of sloppy and I like pretty things so they had to go.   

 //Hailey Hanson
  2 //CS 222 Programming Assignment #3
  3 //January 21, 2014
  4
  5 //This program should prompt the user with a '>' to enter a series of commands which can be found under the help menu
  6 //If the user enters an integer, that integer will be added to their tree. They can then search their tree, delete things from the tree and print the tree out
  7
  8 #include
  9 #include
 10 #include
 11 #include
 12
 13 //Node Structure
 14 /*********************************************************/
 15 struct node{                                            //
 16         int data;                                       //
 17         struct node *right, *left;                      //
 18 };                                                      //
 19 /********************************************************/
  20
 21 //Insert Function
 22 /******************************************************/
 23 //This function should insert integers into the tree, arranging them
 24 //in infix order so that the middle value is at the root of the tree
 25 struct node* insert(struct node *root, int num){
 26         if (root == NULL){
 27                 root=malloc(sizeof(struct node));
 28                 root->data=num;
 29                 root->left=root->right=NULL;
 30                 return(root);
 31         }//end of if
 32         else if (num < root->data){
 33                 root->left = insert(root->left, num);
 34                 return(root);
 35         }//end of else if
 36         else if (num > root->data){
 37                 root->right = insert(root->right, num);
 38                 return(root);
 39         }//end of else if
 40 }//end of insert function
 41 /******************************************************/
 42
 43
 44 //Traverse List Function
 45 /********************************************************/
 46 int traverse(struct node *root){
 47         if (root == NULL) {return(0);}
 48         else{
 49                 int count_left, count_right;
 50                 count_left=traverse(root->left);
 51                 printf("%d ", root->data);
 52                 count_right=traverse(root->right);
 53                 if (count_left>count_right) return(count_left+1);
 54                 else return (count_right+1);
 55         }//end of else
 56 }//end of traverse function
 57 /********************************************************/
 58
 59 //Depth Function
 60 /*******************************************************/
 61 //to be called within the balance function
 62 int depth(struct node *root){
 63         if (root == NULL) return (0);
 64         else {
 65                 int count_left, count_right;
 66                 count_left=depth(root->left);
 67                 count_right=depth(root->right);
 68                 if (count_left>count_right) return(count_left+1);//return larger depth value
 69                 else return (count_right+1);                    //of return smaller
 70         }//end of else
 71 }//end of depth ftn
 72 //should return deepest tree length
 73 /*******************************************************/
 74
 75
 76 //Balanced/Not Balanced Function
 77 /*******************************************************/
 78 int balance(struct node *root){
 79         if (root == NULL) return 1;
 80         if ((balance(root->left)) &&(balance(root->right)) && (abs(depth(root->left)-depth(root->right))<=1))
 81                 return 1;
 82          return 0;
 83 }//end of balance function
 84 /******************************************************/
 85
 86 //Search Function
 87 /*******************************************************/
 88 //searches tree for an integer
 89 int search(struct node *root, int num){ //ftn takes in the tree and a number to search for the number in the tree
 90         if (root == NULL) return (0);
 91         if (num == root->data) return (1);
 92         if (num > root->data){
 93                 return search (root->right, num);
 94         }//end of if
 95         if (num < root->data){
 96                 return (search (root->left, num));
 97         }//end of if
 98 }//end of search function
 99 /*********************************************************/
100
101 //Delete Function
102 /********************************************************/
103 //deletes a node from the tree
104 struct node* delete(struct node *root, int num){
105         if (root == NULL) return(NULL);
106
107         if (numdata) {
108                 root->left=delete(root->left, num);
109         }//end of else if
110
111         else if (num>root->data){
112                 root->right=delete(root->right, num);
113         }//end of else if
114
115         else {
116                 if ((root->left == NULL) && (root->right == NULL)){     //if root has no children
117                         free(root);                                     //free root
118                         return(NULL);
119                 }//end of if
120                 if ((root->left != NULL) && (root->right == NULL)){     //if root has only left child
121                         struct node *temp = root->left;
122                         free(root);                                     //free left child
123                         return(temp);
124                 }//end of if
125                 if ((root->left == NULL) && (root->right != NULL)){     //if root has only right child
126                         struct node *temp = root->right;
127                         free(root);                                     //free right child
128                         return(temp);
129                 }//end of if
130                 if ((root->left != NULL) && (root->right != NULL)){     //if root has two children
131                         struct node *temp = root->right;                //temp is the successor of root
132                         while (temp->left != NULL)
133                                 temp=temp->left;                        //traverse to the left
134                         root->data=temp->data;
135                         root->right=delete(root->right, temp->data);    //recursively delete node with temp's data
136                         return(root);
137                 }//end of if
138                 else printf("To proceed to the help menu, type a ? \n");
139                 return(root);
140         }//end of else
141 return(root);
142 }//end of delete ftn
143
144 /*********************************************************/
145
146
147 //HELP MENU
148 /*********************************************************/
149 //helps a brutha out
150 void help(){
151
152         printf("******************************************HELP MENU*************************************************\n");
153         printf("If you wish to EXIT the program, type 'Q' at any time (with no quotes)\n");
154         printf("If you wish to ADD a number to the tree, just type an integer and then hit enter\n");
155         printf("If you wish to SEARCH for a number in the tree, type an s followed by a space and then the integer.\n");
156         printf("If you wish to DELETE a number from the tree, type a d followed by a space and then the integer.\n");
157         printf("If you wish to see the entire tree, type a p and then hit enter\n");
158         printf("To return to this help menu, type a ?\n");
159         printf("****************************************************************************************************\n");
160         }//end of help menu
161
162 /*********************************************************/
163
164 int main(){
165
166 //Binary Tree Formation
167 /**********************************************************/
168         struct node *root;
169         root=NULL;
170         int num;
171 /**********************************************************/
172
173 //Receiving Input from User
174 /*********************************************************/
175
176 while (1){                              //This will keep my loop going so the user puts multiple inputs in the tree
177
178                 char input[6];
179
180                 printf(">");                                    //prompt
181                 fgets(input, 256, stdin);
182
183                 char mode;                                       //choice of Q, s, d, p or ?
184                 int num;                                        //number in tree
185
186                 int type_1, type_2, type_3;
187
188                 type_2 = sscanf(input, "%c %d", &mode, &num);   //user entered a mode, then a number
189                 type_1 = sscanf(input, "%d", &num);             //user entered just a number
190                 type_3 = sscanf(input, "%c", &mode);            //should be a ? or p
191
192                 if((type_3 == 1) && (type_2 != 2) && (type_1 != 1)){    //If user enters a character, not two characters     or 1 number
193                         switch (mode)
194                         {
195                                 case 'p':
196                                         printf("\nMax Depth = %d\n", traverse(root));   //If user enters p, print max dep    th from traverse function
197                                         if (balance(root) == 1) printf("\nTree is Balanced\n");
198                                         else printf("\nTree is NOT Balanced\n");
199                                         break;
200                                 case '?': help();               //if user enters ?, send to help menu
201                                         break;
202                                 case 'Q': exit(0);              //if user enters Q, quit program
203                                         break;
204                                 default: printf("\nYou have entered an incorrect input. Proceed to the help menu. Do not     pass go. Do not collect $200.\n\n");
205                                         help();                 //if user is incompetent, send to help menu
206                                         break;
207                         }//end of switch
208                 }//end of if statement
209                 else if ((type_2 == 2) && (type_1 != 1)) {                              //if user enters a char and a num
210                         switch (mode)
211                         {
212                                 case 's': search(root, num);    //if user enters s followed by number, search tree for th    at number
213                                 if (search(root, num) == 1) printf("%d Is already in the tree\n", num);
214                                 else printf("%d is not in the tree\n", num);
215                                         break;
216                                  case 'd':
217                                       if(search(root, num) ==1) root=delete(root, num);
218                                         else printf("%d is not in the list\n", num);
219                                          break;
220                                 default: printf("\nYou have entered an incorrect input. Proceed to the help menu. Do not     pass go. Do not collect $200.\n\n");
221                                         help();                 //if user is incompetent, send to help menu
222                                         break;
223                         }//end of switch
224                 }//end of else if
225                 else if (type_1 == 1){                          //if user enters 1 number
226                         if((search(root , num)) == 1)printf("%d Is already in the tree\n", num);
227
228                         else{
229                                 root=insert(root, num);
230                                 printf("%d has been added to the tree\n", num);
231                         }//end of else
232                 }//end of else if
233
234                 else{                                           //else if user is completely disoriented and overwhelmed,     send to help menu.
235                         printf("\nYou have entered an incorrect input. Proceed to the help menu. Do not pass go. Do not c    ollect $200.\n\n");
236                         help();
237                 }//end of else
238
239         }//end of while(1)
240 }//end of main