Tuesday, March 5, 2013

ML (Standard Meta Language New Jersey

Language: ML (Standard Meta Language, New Jersey)

Purpose:

Various book exercises from Modern Programming Languages: A Practical Introduction, by Adam Brooks Webber to be exposed to the functional language ML or SML.
(*Write a function min3 of type int * int * int -> int that 
returns the smallest of three integers.*)
(* BLOCK COMMENT *)
 
fun min3(a:int,b:int,c:int) =if ((a<b) andalso (a<c)) then a else (if (b<c) then b else c);
 
(*__________*)

(*Write a function cycle of type 'a list * int -> 'a list that taks a 
list and an integer n as input and returns the same list, 
but with the first element cycled to the end of the list n times. *)

fun cycle(num, a:int) = if (a<= 0) then num else  cycle(tl(num) @ [hd(num)], a-1);

(*I got marked down for this one since it didn't handle the nil list.*)


(*__________*)


 
(*Write a function isPrime of type int ->bool that returns 
true if and only if its integer parameter is a prime number. 
Your function need not behave well if the parameter is negative.
*)
 
fun isPrime(a:int) =if(a<2) then false else if (a = 2) 
then true else let fun recur (i)= if ( i * i > a) 
then true else if( ((a mod i )= 0) andalso (i <> a)) 
then false else (recur(i+1)) in recur 2 end;


(*Note that <> means 'not equal' in ML.*)

(*__________*)


(*Write a function select of type 'a list  * ('a -> bool ) -> a' 
list that takes a list and a function f as parameters. Your 
function should apply f to each element of the list and 
should return a new list containing only those elements of 
the original list for which f is returned true. (The elements 
of the new list may be given in any order.)*)

 

fun select (list, func) = if null list then [] else if func(hd list) then select (tl list,func) @ [hd list] else select(tl list, func);

(*Grader made this note to me GRADE: 14/15
fun select(nil,func) = nil | select(list,func) = ...*)

Wednesday, November 14, 2012

Complex Number Operations

Language: C++

Purpose:

Performing mathematical operations on complex numbers by overloading operators (+= , -=, etc.) to work with two "Complex number objects" (or just one depending on the operation).
Explanation:

In C++ it is possible to overload mathematical operators. The syntax in the code below will get you started. Also check out learncpp.com chapter 9 for a more in depth look.

I have posted below three files required by my professor.


Complex Class (.cpp)

#include <stdlib.h>
#include <iostream>
#include <cmath>
#include "Complex.h"
using namespace std;

//Global variables
double a = 0;
double b = 0;
string t = "True";
string f = "False";


//Default (NoArgs) Constructor
Complex::Complex()
    :a(0), b(0)
{}

//One arg Constructor
Complex::Complex(double &a )
    :a(0), b(0)
{
    (*this).a = a;
}

//Two arg Constructor
Complex::Complex(double &a, double &b )
    :a(0), b(0)
{
    (*this).a = a;
    (*this).b = b;
}

//Accessor Functions
double Complex::getA()    
{return a;}
double Complex::getB()
{return b;}

//Add 2 Complex numbers together
Complex & ::addCom(Complex & com1, Complex & com2, Complex & temp)
{
    temp.a = com1.a;
    temp.b = com1.b;
    temp += com2;
    return temp;
}

//Subtract 1 Complex number from  another
Complex & ::subCom(Complex & com1, Complex & com2, Complex & temp)
{
    temp.a = com1.a;
    temp.b = com1.b;
    temp -= com2;
    return temp;
}

//Multiply 2 Complex numbers together
Complex & ::mulCom(Complex & com1, Complex & com2, Complex & temp)
{
    temp.a = com1.a;
    temp.b = com1.b;
    temp *= com2;
    return temp;
}

//divide 1 Complex number by another
Complex & ::divCom(Complex & com1, Complex & com2, Complex & temp){
        
    temp.a = com1.a;
    temp.b = com1.b;
    temp /= com2;
    return temp;
}

//Assign the value of one Complex number to another
Complex & ::assign(Complex & com1, Complex & com2, Complex & temp){
        
    com2 = com1;
    temp = com2;
    return temp;
}

//Check for equality
 string & ::isEqual(Complex & com1, Complex & com2){

    if(    com1 == com2){
        return t;
    }
    else{
        return f;
    }
}

 //Check for inequality
 string & ::isNotEqual(Complex & com1, Complex & com2){

    if(    com1 != com2){
        return t;
    }
    else{
        return f;
    }
}

//Absolute value of a Complex number
 Complex & ::absolute(Complex & com1, Complex & temp){

      temp.a = abs(com1.a);
      temp.b = abs(com1.b);
      return temp;
  }

//Operator overload = for Complex Numbers
void Complex::operator = (Complex & c)
{
    (*this).a = c.a;
    (*this).b = c.b;
}

//Operator overload += for Complex Numbers
void Complex::operator += (Complex & c)
{
    (*this).a += c.a;
    (*this).b += c.b;
}

//Operator overload -= for Complex Numbers
void Complex::operator -= (Complex & c)
{
   (*this).a -= c.a;
   (*this).b -= c.b;
}

//Operator overload *= for Complex Numbers
void Complex ::operator *= (Complex & c){
    
    double temp = (*this).a;
    (*this).a = ((*this).a*c.a) - ((*this).b*c.b);
    (*this).b = (((*this).b)*(c.a) + (temp)*c.b);
}

//Operator overload /= for Complex Numbers
void Complex ::operator /= (Complex & c){
    
    double temp = (*this).a;
    (*this).a = (((*this).a*c.a) + ((*this).b*c.b)) / ((c.a * c.a) + (c.b* c.b));
    (*this).b = (((*this).b*c.a) - ((temp)*c.b)) / ((c.a * c.a) + (c.b* c.b));
}

//Operator overload << for Complex Numbers
 ostream & operator << (ostream & out, Complex & c)
{
   out << "(" << c.getA()
       << ", " << c.getB()
       << ")" ;
   return out;
}

//Operator overload == for Complex Numbers
 bool operator == (Complex & l, Complex & r){

     if( l.a == r.a && l.b == r.b){
         return true;
     }
     else{
         return false;
     }

 }

 //Operator overload != for Complex Numbers
  bool operator != (Complex & l, Complex & r){

     if( l.a != r.a && l.b != r.b){
         return true;
     }
     else{
         return false;
     }

 }


Class test (.cpp)
#include "Complex.h"
#include <iostream>
#include <string>

int main(){

    //locals
    double a = 1.00;
    double b = -2.00;
    double c = 3.00;
    double d = 4.00;
    double e = -4.00;
    double f = 2.00;
    double zed = 0;
    
    //Instantiation of Complex number objects
    Complex complexNoArgs;
    Complex complexOneArg(a);
    Complex complexTwoArgs(a, b);
    Complex c1(a, b);
    Complex c2(c, b);
    Complex c3(a,f);
    Complex c4(c,b);
    Complex temp(zed,zed);

    //output stream
    //precision of 2 decimal places and using fixed 
    cout.precision(2);
    cout << "The constructor with no arguments produces " << fixed << complexNoArgs <<endl;
    cout << "The constructor with one arguments produces " << fixed << complexOneArg <<endl;
    cout << "The constructor with two arguments produces " << fixed << complexTwoArgs <<endl;
    cout << c1 << " + " << c2 << " = " << fixed << addCom(c1, c2, temp) <<endl;
    cout << c1 << " - " << c3 << " = " << fixed << subCom(c1, c3, temp) <<endl;
    cout << c1 << " * " << c4 << " = " << fixed << mulCom(c1, c4, temp) <<endl;
    cout << c1 << " / " << c4 << " = " << fixed << divCom(c1, c4, temp) <<endl;
    cout << "If c1 = " << c1 <<  fixed << ", the result of c2 = c1 is c2 = " <<  fixed << assign(c1, c2, temp) <<endl;
    cout << "If we now test c1 == c2 the result is " << isEqual(c1, c2) <<endl;
    cout << "If we now test c1 != c2 the result is " << isNotEqual(c1, c2) <<endl;
    cout << "If c1 = " << c1 <<  fixed <<" and c4 = " << c4 << fixed << " and we calculate c1 += c4, then c1 = " << addCom(c1, c4, temp) <<endl;
    cout << "If c1 = " << c1 <<  fixed <<" and c3 = " << c3 << fixed << " and we calculate c1 -= c3, then c1 = " << subCom(c1, c3, temp) <<endl;
    cout << "If c1 = " << c1 <<  fixed <<" and c4 = " << c4 << fixed << " and we calculate c1 *= c4, then c1 = " << mulCom(c1, c4, temp) <<endl;
    cout << "If c1 = " << c1 <<  fixed <<" and c4 = " << c4 << fixed << " and we calculate c1 /= c4, then c1 = " << divCom(c1, c4, temp) <<endl;
    cout << "If c1 = " << c1 <<  fixed <<" then abs(c1) is " << absolute(c1, temp) <<endl;
}


Header file Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H

#include <stdio.h>
#include <iostream>
using namespace std;

class Complex
{
    
    // output operator
    friend ostream & operator << (ostream & out, Complex & c);

    

public:

    //Non-member
    friend Complex & addCom(Complex & com1, Complex & com2, Complex & temp);
    friend Complex & subCom(Complex & com1, Complex & com2, Complex & temp);
    friend Complex & mulCom(Complex & com1, Complex & com2, Complex & temp);
    friend Complex & divCom(Complex & com1, Complex & com2, Complex & temp);
    friend Complex & assign(Complex & com1, Complex & com2, Complex & temp);
    friend string & isEqual(Complex & com1, Complex & com2);
    friend string & isNotEqual(Complex & com1, Complex & com2);
    friend Complex & absolute(Complex & com1, Complex & temp);

    Complex(); //Default Constructor
    Complex(double & a); //One argument
    Complex(double & a , double & b); //Two argument

    //accessor functions
    double getA();
    double getB();

     // comparison operators
    friend bool operator == (Complex & l, Complex & r);  // equality
    friend bool operator != (Complex & l, Complex & r);  // inequality


    //Assignment Operators
    void operator = (Complex & c);
    void operator += (Complex & c);
    void operator -= (Complex & c);
    void operator *= (Complex & c);
    void operator /= (Complex & c);
    
    

private:
   // data fields
   double a;  // x value
   double b;  // y value
   
};

#endif


Wednesday, October 31, 2012

Binary Serarch Tree Management in C

Language: C

Purpose:

Managing a Binary Search Tree in C using struct(s).

Explanation:
  Struct:
  A struct is the near equivalent of an object in other object oriented programming languages. However C is not an OOP language a struct helps with at least the organization and encapsulation of data.

  Pointer:
  A pointer is a variable whose values are memory addresses. So a pointer points to a variable that has the value you may want to use. In other words a pointer indirectly references a value. Accessing a variable through a pointer is called indirection. When you declare a pointer the template would be <type> *<variableName>; .
 The * is also used as the indirection operator or dereferencing operator. When the * is used in the following statement:

                        printf("%d" , *variablePointer);

would print the actual value that the pointer points to.
This is called dereferencing a pointer.
The & is also used when passing a variable to another function that has a pointer as it's parameter. When doing this in C one needs to pass the address of the variable in order to modify it's value:

doSomething( &variable);

Files: Since there are not classes in C, I have used only 1 "file."



#include <stdio.h>
#include <stdlib.h>

//Struct "object"
struct treeNode{
    struct treeNode *leftPtr;
    int data;
    struct treeNode *rightPtr;
};

//Typedefs
typedef struct treeNode TreeNode; 
typedef TreeNode *TreeNodePtr; 


//Prototypes
void addNode(TreeNodePtr *treePtr, int value);
void inOrder(TreeNodePtr treePtr);
void preOrder(TreeNodePtr treePtr);
void postOrder(TreeNodePtr treePtr);
void removeNode(TreeNodePtr *treePtr, int value);
TreeNodePtr removeAll(TreeNodePtr treePtr);


int main(void){

    //Local variables
    TreeNodePtr rootPtr = NULL;
    char choice = ' ';
    char dontQuit = 1;
    int order = 0;
    int addN = 0;
    int remN = 0;
    char yayNay;

    puts("Commands for managing a binary tree\nn - create a new binary tree\na - add a node to the tree\nr - remove a node\nt - traverse the tree\n\t1 - pre-order\n\t2 - in-order\n\t3 - post-order\nq - quit");

    while(dontQuit == 1){
        printf("%7s" ,"Enter: ");
        scanf("%1s", &choice);

        switch(choice){

        case 'n': //new tree
            if(rootPtr != NULL){
                printf("Create a new tree? y or n: ");
                scanf("%1s" , &yayNay);

                if(yayNay == 'y'){
                    rootPtr = removeAll(rootPtr);
                }
                if(yayNay == 'n'){
                    break;
                }
            }
            break;

        case 'a': //Add
            printf("%s", "Value to add: ");
            scanf("%3d" , &addN);
            addNode(&rootPtr, addN);
            break;

        case'r': //remove
            printf("%s", "Value to remove: ");
            scanf("%3d" , &remN);
            removeNode(&rootPtr, remN);
            break;

        case 't'://traverse
            printf("%23s" , "Pick type of traverse: ");
            scanf("%d", &order);

            if(order == 1){
                //call pre-order function
                preOrder(rootPtr);
                printf("\n");
                break;
            }
            if(order == 2){
                //call in order function
                inOrder(rootPtr);
                printf("\n");
                break;
            }
            if(order == 3){
                //call post order function
                postOrder(rootPtr);
                printf("\n");
                break;
            }
            else{
                puts("Invalid entry. Enter 1, 2, or 3 only.");
                break;
            }
        case 'q'://quit
            dontQuit = 0;
            exit(0);
        }//switch
    }    
    return 0;
}//end function main

void addNode(TreeNodePtr *treePtr, int value){

    //if tree is empty
    if(*treePtr == NULL){
        *treePtr = malloc(sizeof(TreeNode)); 

        if(*treePtr !=NULL){
            (*treePtr)->data = value;
            (*treePtr)->leftPtr = NULL;
            (*treePtr)->rightPtr = NULL;
            printf("%d added\n", value);
        }
        else{
            printf( "%d not inserted. No memory available.\n" , value);
        }
    }//end if
    else{ //tree is not empty

        //data to insert is less than data in current node
        if(value < (*treePtr )->data){
            addNode( &( (*treePtr)->leftPtr), value);

        }
        else if(value > (*treePtr )->data){
            addNode( &( (*treePtr)->rightPtr), value);

        }
        else{ //Duplicate data value is ignored
            printf( "%s", "duplicate\n");
        }
    }//end else

}//end function addNode

void inOrder(TreeNodePtr treePtr){

    if(treePtr != NULL){
        inOrder(treePtr->leftPtr);
        printf("%3d" , treePtr->data);
        inOrder(treePtr->rightPtr);
    }

}//end function inOrder

void preOrder(TreeNodePtr treePtr){

    if(treePtr != NULL){
        printf("%3d" , treePtr->data);
        preOrder(treePtr->leftPtr);
        preOrder(treePtr->rightPtr);
    }

}//end function preOrder

void postOrder(TreeNodePtr treePtr){

    if(treePtr != NULL){
        postOrder(treePtr->leftPtr);
        postOrder(treePtr->rightPtr);
        printf("%3d" , treePtr->data);
    }

}//end function postOrder
/*Function Remove is called when the user wants 
* to delete one value.
**/
void removeNode(TreeNodePtr *treePtr, int value) {

    TreeNodePtr current = *treePtr,parentTreePtr,tempTreePtr;

    if (!current){
        printf("Tree empty.\n");
        return;
    }
    if(current->data == value){

        if(!current->rightPtr && !current->leftPtr){
            *treePtr = NULL;
            free(current);
        }
        else if (!current->rightPtr) {
            *treePtr = current->leftPtr;
            free(current);
        }else {
            tempTreePtr = current->rightPtr;

            if(!tempTreePtr->leftPtr){
                tempTreePtr->leftPtr = current->leftPtr;
            }else{
                while (tempTreePtr->leftPtr) {
                    parentTreePtr = tempTreePtr;
                    tempTreePtr = tempTreePtr->leftPtr;
                }
                parentTreePtr->leftPtr = tempTreePtr->rightPtr;
                tempTreePtr->leftPtr = current->leftPtr;
                tempTreePtr->rightPtr = current->rightPtr;
            }
            *treePtr =tempTreePtr;
            free(current);
        }

    }//end if
    else if(value > current->data){
        removeNode(&(current->rightPtr), value);
    }
    else if(value < current->data){
        removeNode(&(current->leftPtr), value);
    }
}//end function removeNode

/*Function RemoveAll is called when the user wants 
* to start over.
**/
TreeNodePtr removeAll(TreeNodePtr treePtr){

    if(treePtr != NULL){
        removeAll(treePtr->leftPtr);
        removeAll(treePtr->rightPtr);
        treePtr = NULL;
    }
    return treePtr;

}//end function removeALL