Friday, March 22, 2013

Virtual Memory Manager

Language: Java

Purpose:

To build part of an operating system--specifically a Virtual Memory Manager.

Synopsis:
This was quite a project. Now looking back over it after I have finished, I see some of the answers to the questions I had that I thought weren't ever answered. However my instructor just assigned the project and didn't know much about the specifics.
Here is the exact book instructions for the project:
Designing a Virtual Memory Manager


package virtualMMan;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;

public class VmmDriver {

    private final int TABLE_ENTRIES_OR_SIZE = 256;
    private final int PHYSICAL_MEMORY_SCALAR = 1;
    private int [] pageTable = new int [TABLE_ENTRIES_OR_SIZE];
    private int [] frameTable = new int [TABLE_ENTRIES_OR_SIZE]; 
    private HashMap victimFrameLocater = new HashMap<Integer,Integer>();  
    private ArrayList<Integer> framesFIFOQueue = new ArrayList<Integer>();
    private HashMap TLB = new HashMap<Integer,Integer>(17, 1);  
    private ArrayList<Integer> TLB_FIFOQueue = new ArrayList<Integer>();
    private byte [] physicalMemory = new byte [TABLE_ENTRIES_OR_SIZE*TABLE_ENTRIES_OR_SIZE];
    private int physicalMemoryPointer = 0;
    private int availableFrameCounter = 0;
    private int bitMask = 0x00FF;
    private double pageFaults, numOfAddresses, pageFaultRate, TLBHits = 0;

    public static void main(String[] args) {
        new VmmDriver().run();
    }        
    public void run(){

        //Input File with Virtual Addresses
        String filename = ("U:\\Project3\\src\\resources\\InputFile.txt");

        // the file representing the simulated  disk
        File backStorePath;
        RandomAccessFile backingStore = null;

        /*Create pageTable and 
         * initialize each index with -1.
         * This indicates that the entry in
         * the pageTable is invalid.*/
        for(int i = 0; i <(TABLE_ENTRIES_OR_SIZE-1); i++){
            pageTable[i] = -1; }


        /*Create frameTable and 
         * initialize each index starting at 0
         * and increasing by TABLE_ENTRIES_OR_SIZE
         * at each iteration*/
        int frameNum = 0;
        for(int i = 0; i < (TABLE_ENTRIES_OR_SIZE)-1; i++){
            frameNum = i*(TABLE_ENTRIES_OR_SIZE);
            frameTable[i] = frameNum;}

        BufferedReader br = null;  
        try
        {   

            File file = new File(filename);   
            FileReader fr = new FileReader(file);
            br = new BufferedReader(fr);
            String data;

            while((data = br.readLine()) != null)    
            {   
                /*Right-Shift virtual Address by 8 bits virtual 
                 * address space256).
                 * Use bitMask to "mask" Least Significant 0xFF bits*/
                int pageNumber = (Integer.parseInt(data) >> 8);
                int offset = (Integer.parseInt(data) & bitMask);

                int val = 0;
                int frameNumber = 0;

                //Page Fault handling
                if((!(TLB.containsKey(pageNumber)) && pageTable[pageNumber] == -1)){

                    try {
                        backStorePath = new 
                                File("U:\\Project3\\BACKING_STORE_A");
                        backingStore = new RandomAccessFile(backStorePath, "r");


                        // seek to byte position pageNumber * TABLE_ENTRIES_OR_SIZE
                        backingStore.seek((pageNumber)*(TABLE_ENTRIES_OR_SIZE));
                        backingStore.read(physicalMemory, physicalMemoryPointer, TABLE_ENTRIES_OR_SIZE);

                        val = physicalMemory[physicalMemoryPointer+offset];

                        physicalMemoryPointer +=TABLE_ENTRIES_OR_SIZE;

                        //Update PageTable
                        pageTable[pageNumber] = frameTable[availableFrameCounter];
                        frameNumber = pageTable[pageNumber];

                        availableFrameCounter++;

                        //Update TLB
                        if(TLB.size() <= 16){
                            addtoTLB(pageNumber,frameNumber);
                        }
                        else{
                            TLB.remove(TLB_FIFOQueue.get(0));

                        }

                        pageFaults++;
                        //Place value in physicalMemory
                        //physicalMemory[frameNumber] = val;
                        //Take Frame number "or" it with offset to get physical address
                        int physicalAddress = frameNumber  | offset;
                        System.out.println("Virtual address: " + data +" Physical address: " 
                                + physicalAddress + " Value: " + val);
                        //System.out.println("PageNumber: " + pageNumber
                        //+ " FrameNumber: " + frameNumber + " Offset: " + offset);
                        numOfAddresses++;
                    }
                    catch (IOException e) {
                        System.err.println ("Unable to start the disk");
                        //System.exit(1);
                    }
                    finally {
                        backingStore.close();
                    }

                }//if
                else{
                    if(TLB.containsKey(pageNumber)){

                        frameNumber = checkTLB (pageNumber);
                        int physicalAddress = frameNumber | offset;
                        System.out.println("Virtual address: " + data +" Physical address: " 
                                + physicalAddress + " Value: " +  physicalMemory[frameNumber+offset]);
                        TLBHits++;
                        numOfAddresses++;
                    }
                    else{                //Take pageNumber as index and get Frame number from Page table
                        frameNumber = pageTable[pageNumber];
                        //Take Frame number  "or" it with offset to get physical address
                        int physicalAddress = frameNumber | offset;
                        System.out.println("Virtual address: " + data +" Physical address: " 
                                + physicalAddress + " Value: " +  physicalMemory[frameNumber+offset]);
                        //System.out.println("PageNumber: " + pageNumber + 
                        //" FrameNumber: " + frameNumber + " Offset: " + offset);
                        numOfAddresses++;
                    }            
                }//else
            }//while
        }//try
        catch(ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
        }
        catch(IOException e){
            System.out.println(e + "File: " + "\"" + filename + "\"" + " not Found.");
        }
        finally{
            try{
                if(br != null){
                    br.close();
                }
            }
            catch(IOException e){
                e.printStackTrace();
            }
        }
        printStats();
    }//run()
    public void addtoTLB (int pageNumber, int frameNumber ){     
        // Put value into Hash Map
        TLB.put(pageNumber, frameNumber);
        TLB_FIFOQueue.add(pageNumber);

    }//addtoTLB
    public int checkTLB (int pageNumber){
        return (int) TLB.get(pageNumber);

    }//checkTLB

    public void printStats(){
        pageFaultRate = pageFaults/numOfAddresses;
        System.out.println("Number of Translated Addresses = " + (int)numOfAddresses);
        System.out.println("Page Faults = " + (int)pageFaults);
        System.out.println("Page Fault Rate = " + pageFaultRate);
        System.out.println("TLB Hits = " + (int)TLBHits);
        System.out.println("TLB Hit Rate = " + (TLBHits/numOfAddresses));
    }

}

InputFile.txt
correct output for InputFile.txt
Generate a Backing Store file
Random Access File example

Note:
Our instructor told us that we did not have to do the modifications as stated at the end of the instructions. So this implementation only accounts for physical memory size and virtual memory size being the same. My grade was 93%. The reason is I compared my output to the correct output using the website http://text-compare.com/ and all of my values were correct yet some of my translated addresses were not correct. Not sure where I went wrong. Also my statistics were all correct as well. I spend about 30 hours on this project.
 

Thursday, March 21, 2013

Prolog Projects

Language: Prolog

Purpose:

Various book exercises from Modern Programming Languages: A Practical Introduction, by Adam Brooks Webber to be exposed to the logical programming language Prolog.
 
"Project 1" :
 
Exercises 1 - 6 from chapter 19
- Define a mother predicate so that mother(X,Y) says that X is the mother of Y.
- Define a father predicate so that father(X,Y) says that X is the father of Y.
- Define a sister predicate so that sister(X,Y) says that X is the sister of Y. Be careful, a person cannot be her own sister.
- Define a grandson predicate so that grandson(X,Y) says that X is the grandson of Y.
- Define the firstCousin predicate so that firstCousin(X,Y) says that X is the first cousin of Y. Be careful, a person cannot be his or her own cousin, nor can a brother or sister also be cousin.
- Define the descendant predicate so that descendant(X,Y) says that X is the descendant of Y.



parent(X,Y) :- mother(X,Y), female(X).
parent(X,Y) :- father(X,Y), male(X).

sibling(X,Y) :- parent(Z,X), parent(Z,Y), X \= Y.

sister(X,Y) :- sibling(X,Y), female(Y).

grandparent(C,D) :- parent(C,E), parent(E,D).

grandson(X,Y) :- grandparent(X,Y), male(X).

firstCousin(X,Y) :- parent(Z,X), parent(W,Y), sibling(Z,W).

descendant(X,Y) :- parent(X,Y).
descendant(X,Y) :- parent(Z,X), descendant(Z,Y).

female(sabrina).
female(audrey).
female(maria).
female(christine).

male(jose).
male(juan).
male(diego).
male(carlos).

mother(sabrina,audrey).
mother(sabrina,maria).
mother(audrey,juan).
mother(christine,diego).

father(jose,audrey).
father(jose,maria).
father(carlos,sabrina).
father(carlos,christine).


"Project 2" : An Adventure Game

Exercise 6 from chapter 20
Add the following features to the adventure game from this chapter:
- There is a gate between the fork in the path and the mountaintop. the gate is a separate location; that is, the player must move from at(you,fork) to at(you,gate) and then to at(you,mountaintop).
- To move forward through the gate the player must first unlock it with a key.
- The key is somewhere in the maze. The player must find it and explicitly pick it up.
- If the player tries to pass through the gate while still holding the key, he or she is killed by lightning. (To get the treasure, the player must first open the gate, then put down the key, and then pass through.)
Start from the code in this chapter ( which is also available on this book's web site, http://www.webber-labs.com/mpl.html). Part of your implementation should be a general way for the player to pick things up, carry them, and put them down. Design your solution so that I would be easy to add additional objects for the player to pick up and put down.
 
 

/*
  This is a little adventure game.  There are three
  entities: you, a treasure, and an ogre.  There are 
  six places: a valley, a path, a cliff, a fork, a maze, 
  a gate, and a mountaintop.  Your goal is to get the
  treasure without being killed first, but there will
  be challenges along the way.
*/

/*
  First, text descriptions of all places within the
  game.
*/
description(valley,
  'You are in a pleasant valley, with a trail ahead.').
description(path,
  'You are on a path, with ravines on both sides.').
description(cliff,
  'You are teetering on the edge of a cliff.').
description(fork,
  'You are at a fork in the path.').
description(maze(_),
  'You are in a maze of twisty trails, all alike.').
description(mountaintop,
  'You are on the mountaintop.').
description(gate,
  'You are right at a pearly white gate TO HEAVEN.').

/*
  report prints the description of your current
  location.  It is usually called directly as an
  automated routine call.
*/
report :-
  at(you,Loc),
  description(Loc,Y),
  write(Y), nl.

/*
  These connect predicates establish the map.
  The meaning of connect(X,Dir,Y) is that if you
  are at X and you move in direction Dir, you
  get to Y.  Recognized directions are
  forward, right, and left.
*/
connect(valley,forward,path).
connect(path,right,cliff).
connect(path,left,cliff).
connect(path,forward,fork).
connect(fork,left,maze(0)).
connect(fork,right,gate).
connect(gate,forward,mountaintop).
connect(maze(0),left,maze(1)).
connect(maze(1),right,maze(2)).
connect(maze(2),left,fork).
connect(maze(0),right,maze(3)).
connect(maze(_),_,maze(0)).

/*
  move(Dir) moves you in a direction Dir, then
  prints the description of your updated location.
  If you are at the gate and the gate is locked,
  then it alerts you, gives you a hint to unlock it,
  and reports your location.  If the active controller
  is the builder than this is overridden.
*/
move(Dir)  :-
  at(you,gate),
  connect(gate,Dir,Dest),
  gate(locked) ->
  write('The gate is locked.  You must have a key to open the gate.\n'),
  report ; at(you,gate), connect(gate,Dir,_), gate(unlocked), at(key,you), write('ZAAAAAP!  Poseidon\'s bolt got you in the bottom.  You\'re toast.  Oh, and you\'re dead.'), retract(at(you,gate)), assert(at(you,done)).
/*
  But if you are at the gate and the gate is unlocked,
  or you are moving between any other locations via
  a valid direction Dir, then travel to the new
  location and report it.
*/
move(Dir)  :-
  at(you,Loc),
  connect(Loc,Dir,Next),
  at(key,you) ->
  retract(at(key,you)),
  retract(at(you,Loc)),
  assert(at(you,Next)),
  assert(at(key,you)),
  report ; connect(Place,Dir,Step),
  retract(at(you,Place)),
  assert(at(you,Step)),
  report.
/*
  But if the movement was not a legal direction,
  print an error message and don't move.
*/
move(_)  :-
  write('That is not a legal move.\n'),
  report.

/*
  Shorthand for moves.
*/
forward :- move(forward).
left :- move(left).
right :- move(right).

/*
  Actions.
*/
take(key)  :- at(you,Loc), at(key,Loc), not(Loc = you), 
retract(at(key,Loc)), assert(at(key,you)), write('You have swallowed the key...I mean taken it.\n'), report.
take(key)  :- write('I\'m sorry, but you already have the key.  You can\'t take it twice bozo!\n'), report.

drop(key)  :- at(you,Loc), at(key,you), not(Loc = you) -> retract(at(key,you)), assert(at(key,Loc)), write('You have dropped the key.\n'), report ; write('You don\'t have a key in your 
inventory. Check inventory with \'inventory\'.\n'), report.


unlock(gate)  :- gate(unlocked) -> write('Unfortunately, a colossal swarm of Africanized bees migrating with Egyptian scarabs in the shape of Imotep\'s uuuuuugly face...scared you away from the pearly gate momentarily.  That or you aren\'t even at the gate, don\'t have the key in your inventory, or you were so distracted that you didn\'t notice the gate was already unlocked.\n'), report ; at(you,gate), at(key,you), retract(gate(locked)), assert(gate(unlocked)), write('You have unlocked the pearly gate with your creepy key.\n'), report.

lock(gate)  :- gate(locked) -> write('Unfortunately, a colossal swarm of Africanized bees 
migrating with Egyptian scarabs in the shape of Imotep\'s uuuuuugly face...scared you away from the pearly gate 
momentarily.  That or you aren\'t even at the gate, don\'t have the key in your inventory, or you were so 
distracted that you didn\'t notice the gate was already locked.\n'), report ; at(you,gate), at(key,you),  retract(gate(unlocked)), assert(gate(locked)), write('You have locked the pearly gate with your creepy key.\n'), report.

/*
  Shorthand for actions.
*/
takeKey  :- take(key).
dropKey  :- drop(key).
unlockGate  :- unlock(gate).
lockGate  :- lock(gate).
inventory  :-
  write('Your Inventory:\n'),
  at(key,you) -> write('Key\n'), report ; write('Empty.\n'), report.

/*
  If you and the ogre are at the same place, it 
  kills you.
*/
ogre :-
  at(ogre,Loc),
  at(you,Loc),
  write('An ogre sucks your brain out through\n'),
  write('your eye sockets, and you die.\n'),
  retract(at(you,Loc)),
  assert(at(you,done)).
/*
  But if you and the ogre are not in the same place,
  nothing happens.
*/
ogre.

key :-
  at(you,Loc),
  at(key,Loc),
  write('There is a key on the ground with a skull and crossbones on it along with a warning label.\n').
key.

/*
  If you and the treasure are at the same place, you
  win.
*/
treasure :-
  at(treasure,Loc),
  at(you,Loc),
  write('There is a treasure here.\n'),
  write('Congratulations, you win!\n'),
  retract(at(you,Loc)),
  assert(at(you,done)).
/*
  But if you and the treasure are not in the same
  place, nothing happens.
*/
treasure.

/*
  If you are at the cliff, you fall off and die.
*/
cliff :-
  at(you,cliff),
  write('You fall off and die.\n'),
  retract(at(you,cliff)),
  assert(at(you,done)).
/*
  But if you are not at the cliff nothing happens.
*/
cliff.

/*
  Main loop.  Stop if player won or lost.
*/
main :- 
  at(you,done),
  write('Thanks for playing.\n').
/*
  Main loop.  Not done, so get a move from the user
  and make it.  Then run all our special behaviors.  
  Then repeat.
*/
main :-
  key,
  write('\nNext move -- '),
  read(Move),
  call(Move),
  ogre,
  treasure,
  cliff,
  main.

/*
  This is the starting point for the game.  We
  assert the initial conditions, print an initial
  report, then start the main loop.
*/
go :-
  retractall(at(_,_)), % clean up from previous runs
  assert(gate(locked)),
  assert(at(key,fork)),
  assert(at(you,valley)),
  assert(at(ogre,maze(3))),
  assert(at(treasure,mountaintop)),
  write('This is an adventure game. \n'),
  write('Legal moves are left, right, or forward.\n'),
  write('End each move with a period.\n\n'),
  report,
  main.

Perl

Language: Perl

Purpose:

Various book exercises from Modern Programming Languages: A Practical Introduction, by Adam Brooks Webber to be exposed to the high level, general purpose, interpreted (not compiled), dynamic programming language Perl.

Note: I never got grades back for this project but I assume I did well since I passed the class with an A. The program has legal syntax and should run just fine.

 


  # 1.    Write a program that computes 
   #the circumference and area of a circle 
   #(use 3.141592654 as the value of pi). 
   #Prompt for input and read the radius from standard input.
   
      

   print "Circumference of a Circle";
   $pi = 3.141592654;
   print "Please enter a radius\n";
   $radius = <STDIN>;
   print "Circumference of a circle with the radius of $radius is:\n 2*$pi*$radius";
   

 # 2.    Write a program that prompts 
 #for a string and a number on separate 
 #lines. Print the string the number 
 #of times indicated by the input number.
   

   print "Please type a String.\n";
   $theString = <STDIN>;
   print "Now enter the number of times \"$theString\" is to be written.\n";
   $numOfTimes = <STDIN>;
   

   if($theString eq "\n"){
    print "Empty string.";
   }
   else{
    foreach(1..$numOfTimes){
        print "$theString";
    }
   }
   

   #3. Write a program that reads a list 
   #of numbers from standard input 
   #until an end-of-file (ctrl-z). 
   #Print the corresponding name 
   #for each number in the input 
   #list.
   

   @flinstones = qw / Fred Wilma Barney Betty Dino Pebbles BamBam /;
   

   $index = 0;
   while($line ne eof){
    $line = <STDIN>;
    print "\n";
    $numList[index] = $line;
    index++;
   }
   index = 0;
   $numListLength = @numList;
   

   foreach (1..$numListLength){
   

    if($numList[index] > numListLength){
        print "No such index: $numbList[index]\n";
    }
    else{
        print "$flinstones[$numbList[index]]\n";
    }
   index++;
   

   }
   

   #Project 2
   

   #1.    Write a subroutine called &total 
   #that returns the total of a list of 
   #numbers. The list is to be the input, 
   #the answer is to be returned.
   
   

   
    my @numbers = qw( 1 3 5 7 9 );
    my $numberTotal = &total(@numbers);
    print “The total of \@numbers is $numberTotal\n”;
    print “Enter some numbers on separate lines: ”;
    my newTotal = &total(<STDIN>);
    print “The total of \@numbers is $numberTotal\n”;



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

Sunday, October 7, 2012

Tortoise and the Hare Simulation

Tortoise and the Hare Race


Language: C

Purpose:

A Simulation of the famous Race. I had to print out the position of the Tortoise (T) and the Hare (H) at every "tic" (each iteration of a loop). I decided to just use an array and replace the indexes where the Tortoise and the Hare were position on the "race track." Here are the guidelines our professor gave us:


Problem Statement
(Simulation: The Tortoise and the Hare) In this problem, you’ll recreate one of the truly great moments in history, namely the classic race of the tortoise and the hare. You’ll use random number generation to develop a simulation of this memorable event.
Our contenders begin the race at "square 1" of 70 squares. Each square represents a possible position along the race course. The finish line is at square 70. The first contender to reach or pass square 70 is rewarded with a pail of fresh carrots and lettuce. The course weaves its way up the side of a slippery mountain, so occasionally the contenders lose ground. There is a clock that ticks once per second (one pass through the calculation loop). With each tick of the clock, your program should adjust the position of the animals according to the rules below. Use variables to keep track of the positions of the animals (i.e., position numbers are 1–70).
Start each animal at position 1 (i.e., the "starting gate"). If an animal slips left before square 1, move the animal back to square 1. Generate the percentages in the preceding table by producing a random integer, i, in the range
1 ≤ i ≤10. For the tortoise, perform a ・fast plod・ when 1 ≤ i ≤5, a ・slip・ when 6 ≤ i ≤7, or a ・slow plod・ when 8 ≤ i ≤10. Use a similar technique to move the hare.


WINS!!! YAY!!! If the hare wins, print Hare wins. Yuch. If both animals win on the same tick of the clock, you may want to favor the turtle (the "underdog"), or you may want to print It's a tie. If neither animal wins, perform the loop again to simulate the next tick of the clock. When you are ready to run your program, assemble a group of fans to watch the race. You'll be amazed at how involved your audience gets!

Use at least two subroutines (functions) from moving the tortoise and the hare with the form:

void moveTortoise( int *turtlePtr ); //header of function for moving the tortoise

Start of a Sample Session (1. T fast, H sleeps; 2. T fast, H sleeps; 3. T fast, H big hop; 4. T slow, H big slip; … )

ON YOUR MARK, GET SET

BANG !!!!

AND THEY'RE OFF !!!!

H T

H       T

         OUCH!!!

          H      T

 


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

//Prototypes
void moveTortoise( int *turtlePtr );
void moveHare( int *rabbitPtr );

//Global Variables
int harePosition = 0;
int tortPosition = 0;
int *turtlePtr = &tortPosition;
int *rabbitPtr = &harePosition;

 void main(void)
{
    //Local Variables
    int race = 1;
    size_t i;
    srand ( time(NULL) );

    //Start the Race
    puts("ON YOUR MARK, GET SET\nBANG !!!!!\nAND THEY'RE OFF!!!!!\n");
    puts("H T");

    //Race Loop: every Iteration is one "tic."
    while(race == 1){

        moveTortoise(turtlePtr);
        moveHare(rabbitPtr);
        
        if(*rabbitPtr < 0){
            *rabbitPtr = 0;
        }
        else if(*turtlePtr < 2){
            *turtlePtr = 2;
        }
        else if(*rabbitPtr == *turtlePtr){
            int k;
                for(k = 0; k < *rabbitPtr-1; k++){
                printf(" ");
                }
            printf("Ouch!\n");
        }
        
    //Print the Status of the Race.
        for( i = 0; i < 70; i++){
        
            if(i == *rabbitPtr){
            printf("H");
            }
            else if (i == *turtlePtr){
                printf("T");
            }
            else{
                    printf(" ");
            }
        }
        printf("\n");

    //Win Conditions
        if( *rabbitPtr >= 70){
            puts("\nHare wins. Yuch.");
            race = 0;
            }
        if(*turtlePtr >= 70){
            puts("\nTORTOISE WINS!!! YAY!!!");
            race = 0;
            }
         if(*rabbitPtr >= 70 && *turtlePtr >= 70){
            puts("\nIt's a tie.");
            race = 0;
            }
    }
}//Function main

 /* Takes a psuedo-random value and then based on that value increments or decrements
  * the *turtlePtr (tortPosition) value.
  *
  * @param *turtlePtr  - Position of the animal. 
  */
void moveTortoise( int *turtlePtr ){
    
     int value  = rand() % 10 + 1;

    switch(value){
    case 1 :
    case 2 :
    case 3 :
    case 4 :
    case 5 :
        *turtlePtr += 3;
        break;
    case 6 :
    case 7 :
        *turtlePtr -= 6;
        break;
    case 8 :
    case 9 :
    case 10 :
        *turtlePtr += 1;
        break;
    }//end Switch
}
 /* Takes a psuedo-random value and then based on that value increments or decrements
  * the *rabbitPtr (harePosition) value.
  *
  * @param *rabbitPtr  - Position of the animal. 
  */
void moveHare( int *rabbitPtr ){
    
     int value  = rand() % 10 + 1;

    switch(value){
    case 1 :
    case 2 :
        *rabbitPtr += 0;
        break;
    case 3 :
    case 4 :
        *rabbitPtr += 9;
        break;
    case 5 :
        *rabbitPtr -= 12;
        break;
    case 6 :
    case 7 :
    case 8 :
        *rabbitPtr += 1;
        break;
    case 9 :
    case 10 :
        *rabbitPtr -= 2;
        break;
    }//end Switch

}





Thursday, September 27, 2012

Cash Register Simulation

Language: Java & C

Purpose:

A comparison between Java and C. The Simulation takes an amount that the customer paid and calculates the change that the customer is owed.


Cash Register Simulation in Java:

 import java.util.Scanner;

   public class CashRegister
   {
      public static void main(String[] args)
      { 
      
      // Declare variables.
      
         int amountOwed = 0;
         int amountPaid = 0;
         int totalChange = 0;
         int dollars = 0;
         int quarters = 0;
         int dimes = 0;
         int nickels = 0;
         int pennies = 0;
         int remainingChange = 0;
      

      //Get input from user and calculate total change
      

         System.out.println("What is the amount owed?");
         Scanner keyboard = new Scanner(System.in);
         amountOwed =  keyboard.nextInt();         
         System.out.println("What is the amount paid?");
         amountPaid =  keyboard.nextInt();
         totalChange = amountPaid - amountOwed;
      

      // Calculate values
      

         dollars = totalChange / 100;
         remainingChange = totalChange - (dollars*100);
         quarters = remainingChange / 25;
         remainingChange = remainingChange - (quarters*25);
         dimes =  remainingChange / 10;
         remainingChange = remainingChange - (dimes*10);
         nickels =  remainingChange / 5;
         remainingChange = remainingChange - (nickels*5);
         pennies = remainingChange;
         

      

      // Display my variables.
      

         System.out.println("Amount owed: " + amountOwed);
         System.out.println("Amount paid: " + amountPaid);
         System.out.println("Total change is " + totalChange);
         System.out.println(dollars + " dollars, "+ quarters + " quarters, " + dimes + " dimes, " + nickels + " nickels, and " + pennies + " pennies ");
       
      }
   }




Cash Register Simulation in C:

#include <stdio.h>;

void main(void){

    //local variables
         int amountOwed = 0;
         int amountPaid = 0;
         int totalChange = 0;
         int dollars = 0;
         int quarters = 0;
         int dimes = 0;
         int nickels = 0;
         int pennies = 0;
         int remainingChange = 0;

    //Ask for Amount Paid and what is owed

         printf("Enter the amount the customer paid: ");
         scanf("%d",&amountPaid);
         printf("\nEnter the amount the customer owed: ");
         scanf("%d",&amountOwed);
         totalChange = amountPaid - amountOwed;

    //Calculate values

         dollars = totalChange / 100;
        // remainingChange = totalChange - (dollars*100);
         quarters = (totalChange % 100) / 25;
        // quarters = remainingChange / 25;
         remainingChange = remainingChange - (quarters*25);
         dimes = ((totalChange % 100) %25) / 10;
       //  remainingChange = remainingChange - (dimes*10);
         nickels =  (((totalChange % 100) %25) % 10) / 5;
         //remainingChange = remainingChange - (nickels*5);
         pennies = ((((totalChange % 100) %25) % 10) % 5)/ 1;

          printf("\nTheir change is %d", totalChange);
          printf("\n%d Dollars, ", dollars);
          printf("%d Quarters, ", quarters);
          printf("%d Dimes, ", dimes);
          printf("%d Nickels, ", nickels);
          printf("and %d pennies ", pennies);


}

Note: I used modulous in the Program in C but I comment out the exact same code that was from the Java source Code.

Conditional Compound Form

Conditional Compound Form mnemonic:


 p  → q (p, then q or p implies q)


Idea: Think of p being a man and q being the woman, who happen to be dancing. The First leads the second so the man leads the woman.   Only time when  p → q is false: "When p is true and q is false, both are falsely doing the waltz."

  • Meaning  p→ q is false.

When  p→ q is vacuously true: "When p is false, it doesn't matter to q--they are vacuously true.
  • When p and q are dancing and p isn't doing the dance right, regardless of if q is doing the dance right or wrong  p→ q is true.

Caveat:In order for this mnemonic to work you have to know both.

Additional Note: When p and q are both true  p→ q is true.

Truth Table:(From wikipedia)


Tuesday, September 11, 2012

Format My Source Code for Blogging

Format My Source Code for Blogging: Paste your text here.

I use this bloggers Greg Houston's Code to format my source code for my blog.

Monday, September 10, 2012

"My Vector" Project

Language: Java

Purpose:

This is my first program from my first Data Structures class. Using two arrays (data structure) as a "Vector" (a set of n real numbers that could grow) I had to perform addition, subtraction, dot-product, check for equivalence, scaler-product, and absolute value. The definitions for the methods that our instructor gave us is as follows:

A vector x consists of n real components [x1, x2, …, xn]. The operations between two vectors x = [x1, x2, …, xn] and y = [y1, y2, …, yn] are defined as follows:

addition                       [x1 + y1, x2 + y2, …, xn + yn]

subtraction                    [x1 - y1, x2 - y2, …, xn - yn]

dot-product                    x · y = x1 * y1 + x2 * y2 + … + xn * yn

equivalence                    x == y   if  (x1 = y1 and x2 = y2 and … and xn = yn)

scalar-product                 s * x = [s * x1, s * x2, …, s * xn],  where s is a real number.
absolute-value                 | x | = Ö (x · x)

The requirements were two classes a "MyVector" Class that held the mathmatical methods and a "Driver" class with the hard coded values of the two arrays as well as the main method.

Classes:
MyVector class housed the all of the mathematical methods.

package project1;

import java.util.*;

public class MyVector {

//Feilds
    ArrayList vector = new ArrayList();
    ArrayList copyVect = new ArrayList();
    double[] initCopy;

    /**
     * Constructor : constructs the object
     * @param <code>double</code> values inside an array
     * 
     */
    public MyVector(double[] initValues) {
        initCopy = new double[initValues.length];

        for (int i = 0; i < initValues.length; i++) {

            vector.add(i, initValues[i]);
            initCopy[i] = initValues[i];
        }
    }

    /**
     * Copy Constructor: Copies the original values of the object used when
     * invoking this method.
     *
     * @param original - object to hold original values.
     */
    public MyVector(MyVector original) {

        copyVect = new ArrayList(original.vector);
    }

    /**
     * Returns the value of a given index in the
     * <code>ArrayList vector</code> or the <code>Object</code> from the 
     * copy constructor 
     *
     * @param the index of the value to return.
     * @return value at the index given.
     */
    public double getValue(int index) {

        double tempVal = 0.0;
        if (!(this.vector.isEmpty())) {

            return tempVal = (Double) this.vector.get(index);

        } else {

            return tempVal = (Double) this.copyVect.get(index);
        }

    }

    /**
     * Addition method which adds the element of the same index of 
     * two ArrayLists
     *  
     *
     * @param myVector object
     * @return object that contains the results
     */
    public MyVector plus(MyVector a) {
        MyVector c = new MyVector(a);
        double temp = 0.0;
        double temp2 = 0.0;

        for (int i = 0; i < a.copyVect.size(); i++) {
            temp = (Double) a.copyVect.get(i);
            temp2 = (Double) this.vector.get(i);
            c.vector.add(i, temp + temp2);
        }
        return c;
    }

    /**
     * Subtraction method which subtracts the element of the same index of 
     * two ArrayLists
     *  
     *
     * @param myVector object
     * @return object that contains the results
     */
    public MyVector minus(MyVector a) {
        MyVector c = new MyVector(a);
        double temp = 0.0;
        double temp2 = 0.0;
        for (int i = 0; i < a.copyVect.size(); i++) {
            temp = (Double) a.copyVect.get(i);
            temp2 = (Double) this.vector.get(i);
            c.vector.add(i, temp2 - temp);
        }
        return c;
    }

    /**
     * Multiplication by a constant
     *  
     *
     * @param the constant or scaler
     * @return object that contains the results
     */
    public MyVector scaledBy(Double a) {
        double[] initC = {0.0, 0.0, 0.0, 0.0, 0.0};
        MyVector c = new MyVector(initC);
        double temp = 0.0;
        if (!this.vector.isEmpty()) {
            for (int i = 0; i < this.vector.size(); i++) {
                temp = (Double) this.vector.get(i) * a;
                c.vector.add(i, temp);
            }
        } else {
            for (int i = 0; i < this.copyVect.size(); i++) {
                temp = (Double) this.copyVect.get(i) * a;
                c.vector.add(i, temp);
            }
        }
        return c;
    }

    /**
     * This returns a textual representation of the object placed before
     * invoking the object, i.e. vector.toString(); @Override ,
     * <code>Object</code> class toString method
     *
     * @return returns a String representation of the Object.
     */
    @Override
    public String toString() {

        String str = "";
        double temp = 0.0;
        if (!(this.vector.isEmpty())) {
            for (int i = 0; i < vector.size(); i++) {
                str += vector.get(i);
                if (i != (vector.size() - 1)) {
                    str += ", ";
                }
            }
        } else {
            for (int i = 0; i < copyVect.size(); i++) {
                str += copyVect.get(i);
                if (i != (copyVect.size() - 1)) {
                    str += ", ";
                }
            }
        }
        return "[" + str + "]";
    }

    /**
     * Returns a
     * <code>boolean</code> value depending on if one object is equal to
     * another.
     *
     * @Override equals() Method in Object Class
     *
     * @return boolean value
     */
    @Override
    public boolean equals(Object ob) {
        if (this == ob) {
            return true;
        }
        if (ob == null) {
            return false;
        }
        if (!(ob instanceof MyVector)) {
            return false;
        }
        MyVector compareVect = (MyVector) ob;
        return this.vector.equals(compareVect.vector);
    }

    /**
     * Absolute value method which finds the absolute value of a given 
     * element in a single ArrayList
     *  
     * @return object that contains the results
     */
    public MyVector abs() {
        MyVector c = new MyVector(this);
        double temp = 0.0;

        if (!(this.vector.isEmpty())) {
            for (int i = 0; i < this.vector.size(); i++) {
                temp = Math.abs((Double) this.vector.get(i));
                c.vector.add(i, temp);
            }
        } else {
            for (int i = 0; i < this.copyVect.size(); i++) {
                temp = Math.abs((Double) this.copyVect.get(i));
                c.vector.add(i, temp);
            }
        }
        return c;
    }

    /**
     * Dot product method multiplies each element of the same index 
     * and then adds all the separate elements up for one number.
     *  
     * @return <code>double</code> value
     */
    public double dot(MyVector a) {
        double temp, temp2, result = 0.0;
        double[] temp3 = {0.0, 0.0, 0.0, 0.0, 0.0};

        for (int i = 0; i < a.copyVect.size(); i++) {
            temp = (Double) a.copyVect.get(i);
            temp2 = (Double) this.vector.get(i);
            temp3[i] = temp * temp2;

        }
        for (int i = 0; i < temp3.length; i++) {
            result += temp3[i];
        }
        return result;
    }
}


MyVectorDriver class housed the main method and the two arrays that were the "vectors."

package project1;

public class MyVectorDriver {

    public static void main(String[] args) {

//Local variables
        double[] a = {1.5, 2.4, -7.0, 3.3, 5.5};
        double[] b = {2.5, 2.7, 10.1, -3.4, 5.6};
        double getValue, dot;
        Double scaler = 2.0;

//MyVector object instantiation
        MyVector v1 = new MyVector(a);
        MyVector v2 = new MyVector(v1);
        v1 = new MyVector(b);
        MyVector vectContainer;

//My Vector v1 printout
        System.out.println("MyVector v1\n");
        for (int i = 0; i < v2.copyVect.size(); i++) {
            getValue = v1.getValue(i);
            System.out.println("Position " + i + " of MyVector " + "is "
                    + getValue);
        }
        System.out.println("v1 = " + v1.toString()
                + " and is built from array (" + b[0] + " , " + b[1] + " , "
                + b[2] + " , " + b[3] + " , " + b[4] + ")\n");

//My Vector v2 printout
        System.out.println("MyVector v2\n");
        for (int i = 0; i < v1.vector.size(); i++) {
            getValue = v2.getValue(i);
            System.out.println("Position " + i + " of MyVector " + "is " 
                    + getValue);
        }
        System.out.println("v2 = " + v2.toString() 
                + " and is built from array (" + a[0] + " , " + a[1] + " , " 
                + a[2]+ " , " + a[3] + " , " + a[4] + ")\n");

//Equals Method demonstration
        if (v1.equals(v2)) {
            System.out.println(v1 + " == " + v2);
        }
        if (!(v1.equals(v2))) {
            System.out.println(v1 + " != " + v2);
        }
        if (v1.equals(v1)) {
            System.out.println(v1 + " == " + v1);
        }
        if (v2.equals(v2)) {
            System.out.println(v2 + " == " + v2);
        }



        System.out.println("\nComputations\n");

//Calling the addition method
        vectContainer = v1.plus(v2);
        System.out.println(v1 + " + " + v2 + " = " + vectContainer);

//Calling the Subtraction method
        vectContainer = v1.minus(v2);
        System.out.println(v1 + " - " + v2 + " = " + vectContainer);

//Calling the scaler method
        vectContainer = v1.scaledBy(scaler);
        System.out.println(scaler + " * " + v1 + " = " + vectContainer);
        vectContainer = v2.scaledBy(scaler);
        System.out.println(scaler + " * " + v2 + " = " + vectContainer);

//Calling absolute value method
        vectContainer = v1.abs();
        System.out.println("|" + v1 + "|" + " = " + vectContainer);
        vectContainer = v2.abs();
        System.out.println("|" + v2 + "|" + " = " + vectContainer);

//Calling dot product Mehtod
        dot = v1.dot(v2);
        System.out.println(v1 + " . " + v2 + " = " + dot);
    }
}


My grade on this particular project was 96/100.

Saturday, September 8, 2012

A Knight's Tour

A Knight's Tour

Language: Java

Synopsis:

The following code is a project that I had to complete for my first Data Structures class. It was a dreaded one among students because it was hard to wrap one's head around.

There were three classes that were given to us by our instructor: Application.java(this is an interface); BackTrack.java; and Position.java. These classes we did nothing with--they came as is. The other classes we either wrote from scratch or modified source code from a project from our text Data Structures and the Java Collections Framework, Third Edition called Maze.

Purpose:

The purpose or goal was to get the Knight on a X by X (e.g. 8 by 8) chess board to every square without visiting a square twice. The BackTrack class that we were given was a class with a recursive method that was executed if the square was already visited and so the knight would "BackTrack" until it could continue to a square that was not visited or if there wasn't any squares remaining to be visited.

File:Knights-Tour-Animation.gif
from: Wikipedia

Classes:
The BackTrack class was for "backtracking" the Knight when  it arrived at a square that had already been visited.
package project3;

import java.util.*;

public class BackTrack {

    protected Application app;

    /**
     * Initializes this BackTrack object from an application.
     *
     * @param app the application
     */
    public BackTrack(Application app) {
        this.app = app;
    } // constructor

    /**
     * Attempts to reach a goal through a given position.
     *
     * @param pos the given position.
     *
     * @return true if the attempt succeeds; otherwise, false.
     */
    public boolean tryToReachGoal(Position pos) {
        Iterator<Position> itr = app.iterator(pos);

        while (itr.hasNext()) {
            pos = itr.next();
            if (app.isOK(pos)) {
                app.markAsPossible(pos);
                if (app.isGoal(pos) || tryToReachGoal(pos)) {
                    return true;
                }
                app.markAsDeadEnd(pos);
            } // pos may be on a path to a goal
        } // while         
        return false;
    } // method tryToReachGoal
} // class BackTrack


The Application Interface was to help us design our knight class.

package project3;
import java.util.*;

public interface Application 
{
     /**
      * Determines if a given position is legal and not a dead end.
      *
      * @param pos - the given position.
      *
      * @return true if pos is a legal position and not a dead end.
      */     
     boolean isOK (Position pos);


     /**
      * Indicates that a given position is possibly on a path to a goal.
      *
      * @param pos the position that has been marked as possibly being on a 
      *                path to a goal.
      */
     void markAsPossible (Position pos);


     /**
      * Indicates whether a given position is a goal position.
      *
      * @param pos the position that may or may not be a goal position.
      *
      * @return true if pos is a goal position; false otherwise.
      */ 
     boolean isGoal (Position pos);
 

     /**
      * Indicates that a given position is not on any path to a goal position.
      *
      * @param pos the position that has been marked as not being on any path to 
      *                a goal position.
      */
     void markAsDeadEnd (Position pos);
 

     /**
      * Converts this Application object into a String object.
      *
      * @return the String representation of this Application object.
      */
     String toString();


     /**
      * Produces an Iterator object that starts at a given position.
      *
      * @param pos the position the Iterator object starts at.
      *
      * @return an Iterator object that accesses the positions directly
      *               available from pos.             
      */
     Iterator<Position> iterator (Position pos);

} // interface Application


The position class was used to keep track of the position at which the knight was on the any given year.
package project3;
public class Position 
{
        protected int row,
                      column;
            

    /**
         * Initializes this Position object to (0, 0).
         */        
        public Position () 
    {
            row = 0;
            column = 0;
        } // default constructor


    /**
         * Initializes this Position object to (row, column).
         *
         * @param row the row this Position object has been initialized to.
         * @param column the column this Position object has been initialized to.
         */
        public Position (int row, int column) 
    {
            this.row = row;
            this.column = column;
        } // constructor


    /**
         * Determines the row of this Position object.
         *
         * @return the row of this Position object.
         */
        public int getRow () 
    {
            return row;
        } // method getRow


    /**
         * Determines the column of this Position object.
         *
         * @return the column of this Position object.
         */        
        public int getColumn () 
    {
            return column;
        } // method getColumn

} // class Position


The Knight Class was the class that gave "knight" it's attributes--it implements the Application class. The Knight class has an inner class as well the KnightIterator Class.

package project3;

import java.util.Iterator;
import java.util.Scanner;

public class Knight implements Application {


    public static byte count = 1;
    public static final byte DEAD_END = 0;
    protected Position start,
            finish;
    protected byte[][] grid;

    public Knight(byte rows, byte columns, Position start) {

        grid = new byte[rows][columns];
        this.start = start;

    } // constructor

    public Position getStart() {
        return start;
    } // method getStart

    public Position getFinish() {
        return finish;
    } // method getFinish

    public byte[][] getGrid() {
        byte[][] gridCopy = new byte[grid.length][grid[0].length];

        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                gridCopy[i][j] = grid[i][j];
            }
        }
        return gridCopy;
    } // method gridCopy

    @Override
    public boolean isOK(Position pos) {

        return pos.getRow() >= 0 && pos.getRow() < grid.length
                && pos.getColumn() >= 0 && 
                pos.getColumn() < grid[0].length
                && grid[pos.getRow()][pos.getColumn()] == 0;

    }//method isOk

    @Override
    public void markAsPossible(Position pos) {
        if (this.isOK(pos)) {
            grid[pos.getRow()][pos.getColumn()] = count;
            count++;
        }

    }//method markAsPossible

    @Override
    public boolean isGoal(Position pos) {
        if (count == (grid.length * grid[0].length) + 1) {
            return true;
        } else {
            return false;
        }

    }//Method isGoal

    @Override
    public void markAsDeadEnd(Position pos) {

        grid[pos.getRow()][pos.getColumn()] = DEAD_END;
        count--;
    }//method markAsDeadEnd

    @Override
    public String toString() {
        String result = "\n";

        for (int row = 0; row < grid.length; row++) {
            for (int column = 0; column < grid[0].length; column++) {
                result += String.valueOf(grid[row][column]) + ' ';
            }
            result += "\n";
        } // for row = 0
        return result;
    } // method toString

    @Override
    public Iterator<Position> iterator(Position pos) {
        return new KnightIterator(pos);
    }

    protected class KnightIterator implements Iterator<Position> {

        //protected static final int MAX_MOVES = ;
        protected int row,
                column, count2;

        /**
         * Initializes this KnightIterator object to start at 
         * a given position.
         *
         * @param pos the position the Iterator objects starts at.
         */
        public KnightIterator(Position pos) {
            row = pos.getRow();
            column = pos.getColumn();
            count2 = 0;

        } // constructor

        /**
         * Determines if this KnightIterator object can advance to another
         * position.
         *
         * @return true if this KnightIterator object can advance; false
         * otherwise.
         */
        @Override
        public boolean hasNext() {
            return count2 < 8;
        } // method hasNext

        /**
         * Advances this KnightIterator object to the next position.
         *
         * @return the position advanced to.
         */
        @Override
        public Position next() {
            Position nextPosition = new Position();
            switch (count2++) {

                case 0:
                    nextPosition = new Position(row - 2, column + 1);
                    break;
                case 1:
                    nextPosition = new Position(row - 1, column + 2);
                    break;
                case 2:
                    nextPosition = new Position(row + 1, column + 2);
                    break;
                case 3:
                    nextPosition = new Position(row + 2, column + 1);
                    break;
                case 4:
                    nextPosition = new Position(row + 2, column - 1);
                    break;
                case 5:
                    nextPosition = new Position(row + 1, column - 2);
                    break;
                case 6:
                    nextPosition = new Position(row - 1, column - 2);
                    break;
                case 7:
                    nextPosition = new Position(row - 2, column - 1);
                    break;
            } // switch;                
            return nextPosition;
        } // method next

        @Override
        public void remove() {
            // removal is illegal for a KnightIterator object
            throw new UnsupportedOperationException();
        } // method remove
    } // class KnightIterator

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    }//main Method
}


The KnightUser class actually took the knight around the board. This class I modified from one of the book's source codes file you can find those on the books site.

package project3;

import java.io.*;
import java.util.*;

public class KnightUser {

    final String START_INVALID = "The start position is invalid.";
    final String SUCCESS = "\n\nA solution has been found:";
    final String FAILURE = "\n\nThere is no solution:";
    BackTrack backTrack;

    public static void main(String[] args) {
        new KnightUser().run();
    } // method main

    public void run() {

        //Get size of board and starting position from User

        System.out.print("Enter a number for the board size(Example: "
                + "8 would yield 8 X 8): ");
        Scanner keyboard = new Scanner(System.in);
        byte rows = keyboard.nextByte();
        byte columns = rows;
        System.out.print("Enter the starting row and column: ");
        Position start = new Position(keyboard.nextInt(), keyboard.nextInt());
        boolean isValid = false;

        while (!isValid) {
            try {
                Knight knight = new Knight(rows, columns, start);
                if (!knight.isOK(knight.getStart())) {
                    System.out.println(START_INVALID);
                } else {
                    if (searchBoard(knight)) {
                        System.out.println(SUCCESS);
                    } else {
                        System.out.println(FAILURE);
                    }
                    System.out.println(knight);
                } // else 
                isValid = true;
            } // try
            catch (NumberFormatException e) {
                System.out.println("\n" + e);
            } // catch
            catch (RuntimeException e) {
                System.out.println("\n" + e);
            } // catch
        }// while
    } // method run

    /**
     * Performs the Board search.
     *
     * @param knight – the knight to traverse that board.
     *
     * @return true - if a path from start to finish was found; otherwise, 
     * false
     */
    public boolean searchBoard(Knight knight) {
        Position start = knight.getStart();
        knight.markAsPossible(start);
        backTrack = new BackTrack(knight);

        if (knight.isGoal(start) || backTrack.tryToReachGoal(start)) {
            return true;
        }
        knight.markAsDeadEnd(start);
        return false;
    } // method searchMaze
} // class MazeUser


There were two other classes that I wrote that were test classes for the Knight class and the KnightUser class that used junit. My Grade on this one was 98%.
These are the books that got me through 4 CS classes.

Books Used:

Starting Out with Java: Early Objects (3rd Edition) 
by Tony Gaddis (click to see more from author)
Starting Out with Java: Early Objects (3rd Edition)
  • ISBN-10: 0321497686
  • ISBN-13: 978-0321497680

  • Data Structures and the Java Collections Framework [Paperback] 
    by William Collins (click to see book site)