Menu

Friday, 20 November 2015

Matrix Class Demo (Java Concept)

 */
package matrix;

/**
 *
 * Adeniran Adetunji
 */
public class Matrix {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
       
        MatrixMath calMatrix = new MatrixMath();
       
               
        double[][]matrix_A = calMatrix.createMatrix();
        double[][]matrix_B = calMatrix.createMatrix();
       
        calMatrix.enterMatrixElement(matrix_A);
        calMatrix.enterMatrixElement(matrix_B);
       
        double [][]matrix_C= calMatrix.addMatrix(matrix_A, matrix_B);
       
        calMatrix.displayMatrix(matrix_A);
        System.out.println(" ");
        calMatrix.displayMatrix(matrix_B);
        System.out.println(" ");
        calMatrix.displayMatrix(matrix_C);
       
}


Output
run:
Enter Number of row(s)2
Enter Number of column(s)2
Enter Number of row(s)2
Enter Number of column(s)2
Enter element in row: 1 column :1==>3
Enter element in row: 1 column :2==>14
Enter element in row: 2 column :1==>2
Enter element in row: 2 column :2==>3
Enter element in row: 1 column :1==>56
Enter element in row: 1 column :2==>2
Enter element in row: 2 column :1==>3
Enter element in row: 2 column :2==>45
3.0       14.0    
2.0       3.0      

56.0      2.0      
3.0       45.0    

59.0      16.0    
5.0       48.0    

BUILD SUCCESSFUL (total time: 30 seconds)

MatrixMaths Class (Java Concept)

package matrix;

/**
 *
 * Adeniran Adetunji
 */
public class MatrixMath extends MatrixC {
   
   
   double [][] addMatrix(double[][]augendMatrix, double[][]addendMatrix)
   {
       int x = augendMatrix.length;
       int y = augendMatrix[0].length;
       double [][]totalMatrix = new double[x][y];
     
     
       if((augendMatrix.length==addendMatrix.length)
               &&(augendMatrix[0].length==addendMatrix[0].length))
       {
           for(int i=0; i<augendMatrix.length; i++)
           {
               for (int k=0; k<augendMatrix[i].length; k++)
               {
                   totalMatrix[i][k]=getElement(augendMatrix, i, k )+
                              getElement(addendMatrix, i, k);
               }
           }
         
       }
       else
       {
           System.out.println("Matrix a not of the same dimension");
           System.out.println("Matrix Cannot be added");
       }
     
       return totalMatrix;
   }
   
}

Matrix Class (Java Concept)

package matrix;
import java.util.Scanner;

/**
    *
 * Adeniran Adetunji
 */
public class MatrixC {
   
    double [][]matrix;
   
    //Create Matrix of Row = x and Column=y
   
    MatrixC ()
    {
        matrix = new double[0][0];
    }
     double [][] createMatrix()
    {
        int x;
        int y;
        Scanner setMatrix = new Scanner (System.in);
        System.out.print("Enter Number of row(s)");
        x = setMatrix.nextInt();
        System.out.print("Enter Number of column(s)");
         y = setMatrix.nextInt();
        matrix = new double[x][y];
        initializeMatrix(matrix);
       
        return matrix;
       
      }
   
     double[][]createMatrix(double [][]matrix_1)
     {
         matrix = matrix_1;
         return matrix;
     }
   
     double[][] createColumnVector()
     {
        final int x= 1;
        int y;
      Scanner columnNo = new Scanner (System.in);
      System.out.print("Enter Number of Column(s): ");
      y = columnNo.nextInt();
     
      matrix=new double [x][y];
      initializeMatrix(matrix);
     
      return matrix;
     }
   
     double[][]createColumnVector(double[]cMatrix)
     {
       
         int y = cMatrix.length;
       
         matrix = new double [y][1];
       
         for (int i=0; i<matrix.length; i++)
         {
             for (int k=0; k<matrix[i].length; k++)
             {
                 matrix[i][k]=cMatrix[i];
               
             }
         }
       
         return matrix;
     }
   
     double [][] createRowVector()
     {
         final int y= 1;
        int x;
      Scanner columnNo = new Scanner (System.in);
      System.out.print("Enter Number of Row(s): ");
      x = columnNo.nextInt();
     
      matrix=new double [x][y];
      initializeMatrix(matrix);
     
      return matrix;
     }
   
     double [][]createRowVector(double[]rMatrix)
     {
        int y = rMatrix.length;
       
         matrix = new double [1][y];
       
         for (int i=0; i<matrix.length; i++)
         {
             for (int k=0; k<matrix[i].length; k++)
             {
                 matrix[i][k]=rMatrix[k];
               
             }
         }
       
         return matrix;
     }
   
     void initializeMatrix(double [][]matrix)
    {
        for (int i=0; i<matrix.length; i++)
        {
            for(int k=0; k<matrix[i].length; k++)
            {
                matrix[i][k]=0.0;
            }
        }
    }
     void displayMatrix(double[][]matrix1)
     {
         for(int i=0; i<matrix1.length; i++)
         {
             for(int k=0; k<matrix1[i].length; k++)
             {
                 System.out.printf("%-10.1f", matrix1[i][k]);
             }
             System.out.println("");
         }
       
     }
   
   
    //Initialize matrix of row i and column K with each element initialy equal to zero
   
   
    void enterMatrixElement(double[][]matrix)
    {
        for(int i=0; i<matrix.length; i++)
        {
            for(int k = 0; k<matrix[i].length; k++)
            {
                Scanner input_matrix_element = new Scanner (System.in);
                System.out.print("Enter element in "+ "row:"+" "+ (i+1)+" "+ "column :"+(k+1));
                System.out.print("==>");
                matrix[i][k]= input_matrix_element.nextInt();
            }
        }
    }
   
    boolean equalMatrix(double [][]matrix_1, double[][]matrix_2)
    {
       boolean test = false;
       
        if((matrix_1.length==matrix_2.length)
               &&(matrix_1[0].length==matrix_2[0].length))
        {
            for (int i = 0; i<matrix_1.length; i++)
            {
                for (int k = 0; k<matrix_1[i].length; i++)
                {
                    if(matrix_1[i][k]==matrix_2[i][k])
                    {
                        test = true;
                    }
                }
            }
        }
        else          
        {
            test =  false;
        }
        return test;
    }
   
   
    void clearMatrix (double[][]matrix)
    {
        initializeMatrix(matrix);
    }
   
    double [][] cloneMatrix(double[][]matrix)
    {
       return matrix;
    }
   
    double getElement(double[][]matrix, int x, int y)
    {
       double element = matrix[x][y];
     
       return element;
    }
   
    void  setElement( double[][]matrix, int x, int y, double z)
    {
       matrix[x][y]=z;
    }
   
    double [][]getColumn(double[][]matrix, int col_index)
    {
        int num = matrix.length;
       
        double [][] matrixR = new double[num][1];
       
        for (int i=0; i<matrix.length; i++)
        {
            matrixR[i][0]= matrix[i][col_index];
        }
       
        return matrixR;
    }
   
    boolean IsVector (double[][]matrix_c)
    {
        boolean result = false;
       
        if((matrix_c.length==1)||(matrix_c[0].length==1))
        {
            result = true;
        }
       
        return result;
       
    }
   
    boolean checkVectorEqualLength(double [][]matrix_A, double[][] matrix_B)
    {
   
        boolean result = false;
       
            if((matrix_A.length==matrix_B.length)&&(matrix_A[0].length==matrix_B[0].length))
            {
                result=true;
            }
            else if ((matrix_A.length==matrix_B[0].length)&&(matrix_A[0].length==matrix_B.length))
            {
                result = true;
            }
            else
            {
                result=false;
            }
         
         
       
        return result;
    }
   
    boolean equalDimension(double[][]matrix_A, double[][]matrix_B)
    {
        boolean check = false;
        if((matrix_A.length==matrix_B.length)&&(matrix_A[0].length==matrix_B[0].length))
        {
            check = true;
        }
       
        return check;
    }
   
    double dotProduct(double[][]matrix_A, double[][]matrix_B)
    {
        boolean check;
        boolean check2;
        double result=0;
       
        check = (IsVector(matrix_A)&&IsVector(matrix_B));
       check2 = ((check)&&(checkVectorEqualLength(matrix_A, matrix_B)));
        if(check2)
        {
             if((matrix_A.length==matrix_B.length)&&(matrix_A[0].length==matrix_B[0].length))
             {
                 for(int i=0; i<matrix_A.length; i++)
                 {
                     for(int k=0; k<matrix_A[i].length; k++)
                     {
                         result= result+(matrix_A[i][k]*matrix_B[i][k]);
                     }
                 }
             }
             if((matrix_A.length==matrix_B[0].length)&&(matrix_A[0].length==matrix_B.length))
             {
                 if(matrix_A.length==1)
                 {
                     for (int i=0; i<matrix_A.length; i++)
                     {
                         for (int k=0; k<matrix_B.length; k++)
                         {
                             result = result+(matrix_A[i][k]*matrix_B[k][i]);
                         }
                     }
                 }
                 if(matrix_B.length==1)
                     for(int i=0; i<matrix_B.length; i++)
                     {
                         for(int k=0; k<matrix_A.length; k++)
                         {
                             result = result+(matrix_B[i][k]*matrix_A[k][i]);
                         }
                     }
             }
               
        }
        else
        {
            System.out.println("Matrices are not compartible for dot product");
           
         
        }
       
        return result;
    }
   
   
    double [][] addMatrix (double[][] matrix_A, double [][]matrix_B)
    {
        double [][]result;
       
        result = new double[matrix_A.length][matrix_A[0].length];
        initializeMatrix(result);
           
        if(equalDimension(matrix_A, matrix_B))
        {
            result = new double[matrix_A.length][matrix_A[0].length];
            initializeMatrix(result);
            for(int i =0; i<matrix_A.length; i++)
            {
                for(int k=0; k<matrix_A[i].length; k++)
                {
                    result[i][k]=matrix_A[i][k]+matrix_B[i][k];
                }
               
            }
        }
        else
        {
            System.out.println("The matrices do not have the same dimesion");
        }
       
        return result;
       
    }
   

 
}

Wednesday, 14 October 2015

Java Concept (Matrix Operation using java array 1)

package matrix;
import java.util.Scanner;

/**
    *
 * @author Adeniran Adetunji
 */
public class MatrixC {
 
    double [][]matrix;
 
    //Create Matrix of Row = x and Column=y
     double [][] createMatrix()
    {
        int x=0;
        int y=0;
        Scanner setMatrix = new Scanner (System.in);
        System.out.print("Enter Number of row(s)");
        x = setMatrix.nextInt();
        System.out.print("Enter Number of column(s)");
         y = setMatrix.nextInt();
        matrix = new double[x][y];
        initializeMatrix(matrix);
     
        return matrix;
     
      }
 
//create Column vector i.e matrix of 1 row
     double[][] createColumnVector()
     {
        final int x= 1;
        int y;
      Scanner columnNo = new Scanner (System.in);
      System.out.print("Enter Number of Column(s): ");
      y = columnNo.nextInt();
   
      matrix=new double [x][y];
      initializeMatrix(matrix);
   
      return matrix;
     }
   
//create Row vector i.e. matrix of 1 column
     double [][] createRowVector()
     {
         final int y= 1;
        int x;
      Scanner columnNo = new Scanner (System.in);
      System.out.print("Enter Number of Row(s): ");
      x = columnNo.nextInt();
   
      matrix=new double [x][y];
      initializeMatrix(matrix);
   
      return matrix;
     }
   
     void displayMatrix(double[][]matrix1)
     {
         for(int i=0; i<matrix1.length; i++)
         {
             for(int k=0; k<matrix1[i].length; k++)
             {
                 System.out.printf("%-10.1f", matrix1[i][k]);
             }
             System.out.println("");
         }
       
     }
   
   
    //Initialize matrix of row i and column K with each element initialy equal to zero

    void initializeMatrix(double [][]matrix)
    {
        for (int i=0; i<matrix.length; i++)
        {
            for(int k=0; k<matrix[i].length; k++)
            {
                matrix[i][k]=0.0;
            }
        }
    }
 
//Update matrix or enter matrix elements

    void enterMatrixElement(double[][]matrix)
    {
        for(int i=0; i<matrix.length; i++)
        {
            for(int k = 0; k<matrix[i].length; k++)
            {
                Scanner input_matrix_element = new Scanner (System.in);
                System.out.print("Enter element in "+ "row:"+" "+ (i+1)+" "+ "column :"+(k+1));
                System.out.print("==>");
                matrix[i][k]= input_matrix_element.nextInt();
            }
        }
    }

=======================================================================
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package matrix;

/**
 *
 * @author DELL
 */
public class Matrix {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        MatrixC myMatrix = new MatrixC();

        System.out.println("Creating and Intializing Matrix");
        System.out.println("================================");
       double[][] matrixA = myMatrix.createMatrix();
       
       System.out.println("Entering elements in matrix indexes");
       System.out.println("===================================");
        myMatrix.enterMatrixElement(matrixA);
      
       System.out.println("Displaying Matrix Elements");
       System.out.println("==========================");
      
        myMatrix.displayMatrix(matrixA);
       
        System.out.println("Creating and initializing Column Vector");
        System.out.println("=======================================");
                           
       double[][]matrixB=myMatrix.createColumnVector();
       
       System.out.println("Entering elements in the Column Vector");
       System.out.println("======================================");
                           
       myMatrix.enterMatrixElement(matrixB);
       
       System.out.println("Displaying the elements in the column vector");
       System.out.println("============================================");
        myMatrix.displayMatrix(matrixB);
         
        
       System.out.println("Creating and Initializing row vector");
       System.out.println("======================================");
       double[][]matrixC =myMatrix.createRowVector();
        
        System.out.println("");
        
       System.out.println("Entering elements in the row Vector");
       System.out.println("===================================");
        myMatrix.enterMatrixElement(matrixC);
        
         System.out.println("Displaying elements of the Column Vector");
         System.out.println("=========================================");
        myMatrix.displayMatrix(matrixC);
        
        
    }
        
        
        
    }

OUTUPUT
run:

Creating and Initializing Matrix
================================
Enter Number of row(s)3
Enter Number of column(s)4

Entering elements in matrix indexes
===================================
Enter element in row: 1 column :1==>3
Enter element in row: 1 column :2==>12
Enter element in row: 1 column :3==>4
Enter element in row: 1 column :4==>12
Enter element in row: 2 column :1==>4
Enter element in row: 2 column :2==>5
Enter element in row: 2 column :3==>12
Enter element in row: 2 column :4==>2
Enter element in row: 3 column :1==>3
Enter element in row: 3 column :2==>4
Enter element in row: 3 column :3==>2
Enter element in row: 3 column :4==>2
Displaying Matrix Elements
==========================
3.0       12.0      4.0       12.0      
4.0       5.0       12.0      2.0       
3.0       4.0       2.0       2.0       

Creating and initializing Column Vector
=======================================
Enter Number of Column(s): 3
Entering elements in the Column Vector
======================================
Enter element in row: 1 column :1==>3
Enter element in row: 1 column :2==>3
Enter element in row: 1 column :3==>3

Displaying the elements in the column vector
============================================
3.0       3.0       3.0       

Creating and Initializing row vector
======================================
Enter Number of Row(s): 3

Entering elements in the row Vector
===================================
Enter element in row: 1 column :1==>33
Enter element in row: 2 column :1==>3
Enter element in row: 3 column :1==>33

Displaying elements of the Column Vector
=========================================
33.0      
3.0       
33.0      
BUILD SUCCESSFUL (total time: 41 seconds)

Sunday, 4 October 2015

Java Concept (Queue Data structure)

package queuedatastructure;

/**
 *
 * @author Adeniran Adetunji
 */
public class ArrayStaticQueue {
    //Declaring the instance variables of a queue. Initalizing head and tail to zero
    int headRef=0;
    int tailRef=0;
    char [] arrayQueue;
     
    //Method to create queue array
   void initializeQueue(int Size)
    {
     
       arrayQueue = new char[Size];
     
       for( int i=0; i<arrayQueue.length; i++)
       {
           arrayQueue[i] = '\u0000';
       }
    }
 
   //This method checks if queue is empty
  boolean isEmpty()
  {
      boolean test= true;
      for (int i=0; i<arrayQueue.length; i++)
      {
          if(arrayQueue[i]!='\u0000')
           
              test=false;
      }
   
      return test;
  }

  //This method test if queue is full
  boolean isFull()
  {
      boolean test = true;
   
      for (int i=0; i<arrayQueue.length; i++)
      {
          if(arrayQueue[i]=='\u0000')
           
              test = false;
      }
   
      return test;
  }

  //This method adds item to queue
 void addItem( char c)
 {
     // The test determines if the queue is full
     boolean test=isFull();
     // If the queue is full
     if(test)
     {
     //The system should print QUEUE IS FULL
         System.out.println("Queue is Full");
     }
     else
     {
        arrayQueue[tailRef]=c;
     }
   
     setTail();
 }
   
//This method set new tail location after adding item to queue
  void setTail()
  {
//Test if queue is full
 boolean  test=isFull();
     //if is full
     if(test)
     {
         //Then tail index becomes -1
         tailRef=-1;
     }
     //If queue is not full
     else
     {
         //Get the current tail index in nTail variable
     int nTail = tailRef;
   
     //Check for free space to the right-side of the tail
         for(int i=tailRef; tailRef<arrayQueue.length; i++)
         {
             //if found...
             if(arrayQueue[i]=='\u0000')
             {
                 //set new tail at the index of the free space
                 tailRef=i;
                 //break out of the loop
                 break;
             }
         }
         //Test if tailRef is not updated by the loop above
         //If test is true: that is loop is not updated
      if (nTail==tailRef)
      {
          //start searching for the free space from the begining of the
          //queue i.e. from index 0
          for (int k=0; k<arrayQueue.length; k++)
          {
             //Get first free space
             if(arrayQueue[k]=='\u0000')
             {
                 //Update tailRef at the index of the first free space gotten
                 tailRef=k;
                 //break out of the loop
                 break;
             }
          }
      }
     }
  }
  //This method removes item from queue
 void removeItem()
 {
     boolean test = isEmpty();
   
     if(test)
     {
         System.out.print("Queue is empty");
     }
     else
     {
       
         arrayQueue[headRef]='\u0000';
       
         if(tailRef==-1)
         {
             tailRef=headRef;
         }
       
     }
   
     setHead();  
 }

 //This method set new head location after removing item from queue
 void setHead()
 {
    boolean test = isEmpty();
         if(test)
         {
           
         headRef=0;
       
         }
         else
         {
             if(headRef+1<arrayQueue.length)
             {
               
              headRef=headRef+1;
             }
             else
             {
                 for(int i=0; i<arrayQueue.length; i++)
                 {
                     if(arrayQueue[i]!='\u0000')
                       
                         headRef=i;
                     break;
                 }
             }
         }
 }
   
 }

....Class Instance...
package queuedatastructure;

/**
 *
 * @author Adeniran Adetunji
 */
public class QueueDataStructure {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
     
        ArrayStaticQueue myQueue = new ArrayStaticQueue();
     
        myQueue.initializeQueue(5); //Initializes queue that can hold five characters
     
 /*1.*/ for (int i = 0; i<myQueue.arrayQueue.length; i++)
       {
           System.out.println(myQueue.arrayQueue[i]);
       }    

/*2*/    boolean check = myQueue.isEmpty();

            System.out.println(check);

/*3*/ System.out.println("Head =" + myQueue.headRef);
         System.out.println("Tail =" + myQueue.tailRef);

/*4*/  myQueue.addItem('A');
/*1.*/ for (int i = 0; i<myQueue.arrayQueue.length; i++)
       {
           System.out.println(myQueue.arrayQueue[i]);
       }  

 /*2*/ check = myQueue.isEmpty();

       System.out.println(check);
     
 /*3*/ System.out.println("Head =" + myQueue.headRef);
       System.out.println("Tail =" + myQueue.tailRef);
  /*5*/ myQueue.addItem('B');
       myQueue.addItem('C');
       myQueue.addItem('D');
       myQueue.addItem('E');

 /*1.*/ for (int i = 0; i<myQueue.arrayQueue.length; i++)
       {
           System.out.println(myQueue.arrayQueue[i]);
       }  

 /*2*/ check = myQueue.isEmpty();
     
       System.out.println(check);
     
 /*3*/ System.out.println("Head =" + myQueue.headRef);
       System.out.println("Tail =" + myQueue.tailRef);

              check=myQueue.isFull();
 /*6*/     System.out.println(check);

 /*7*/   myQueue.addItem('F');
/*8*/  myQueue.removeItem();
 /*1.*/ for (int i = 0; i<myQueue.arrayQueue.length; i++)
       {
           System.out.println(myQueue.arrayQueue[i]);
       }  

 /*3*/ System.out.println("Head =" + myQueue.headRef);
       System.out.println("Tail =" + myQueue.tailRef);
     
/*9*/  myQueue.removeItem();
 /*1.*/ for (int i = 0; i<myQueue.arrayQueue.length; i++)
       {
           System.out.println(myQueue.arrayQueue[i]);
       }  

 /*3*/ System.out.println("Head =" + myQueue.headRef);
       System.out.println("Tail =" + myQueue.tailRef);

 /*10*/ myQueue.removeItem();
 /*1.*/ for (int i = 0; i<myQueue.arrayQueue.length; i++)
       {
           System.out.println(myQueue.arrayQueue[i]);
       }  

 /*3*/ System.out.println("Head =" + myQueue.headRef);
       System.out.println("Tail =" + myQueue.tailRef);

 /*11*/ myQueue.addItem('F');
 /*12*/ myQueue.removeItem();
 /*1.*/ for (int i = 0; i<myQueue.arrayQueue.length; i++)
       {
           System.out.println(myQueue.arrayQueue[i]);
       }  

 /*3*/ System.out.println("Head =" + myQueue.headRef);
       System.out.println("Tail =" + myQueue.tailRef);



     
     
}
}


Output
run:
1.





2. true      
3. Head =0
   Tail =0

4.A




1. false
2. Head =0
3. Tail =1
//After adding item at /*5*/
1.A
   B
   C
   D
   E
2.false
3.Head =0
4.Tail =-1
6.True
7.Queue is Full
//After /*8*/
1.
   B
   C
   D
   E
3.Head =1
4.Tail =0
//After  /*9*/

C
D
E
Head =2
Tail =0
//After /*10*/
1.


   D
   E
3.Head =3
4.Tail =0
//After  /*11*/ & /*12*/
F


E
Head =4
Tail =1
BUILD SUCCESSFUL (total time: 9 seconds)


















Friday, 25 September 2015

Java concept (Stack Implementation)

Using Stack To reverse Input String


/*
 * To change this license header, choose License Headers in Project  *Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package stackimplementation;

import java.util.Scanner;

/*
  @author Adeniran Adetunji
 */

/* 
This program uses stack implementation to reverse a string e.g. Input "CAT" will output "TAC"
*/

public class StackImplementation {
   
/* Declare class variables Top: which keeps track the top of the stack, Size: the size of the stack that is predetermined, stack implementationwithan array "myStack".
*/

    int size;
    char [] myStack;
    int top;
    
    //set stack size to accomodate the string input
    
    void setSize(String n) 
   {
             
       int stackSize = n.length();
       
       size = stackSize;
       myStack = new char [size];
       top = myStack.length;
    }
    
    //push string character-by-character into stack
    void push(String myWord) 
   {
       
       if (top<=0)
       {
           System.out.println("Stack is full");
       }
       else
       {
       for (int i = 0; i<myWord.length(); i++)
       {
           
             myStack[top-1]=myWord.charAt(i);
           
           top--; //update top
       }
       
   }
   }
    
    //POP string in Last-in-first-out order from stack
     String pop()
    {
      String outString="";
      
      if (top==myStack.length)
      {
      System.out.println("Stack is Empty, Enter String to reverse");
      }
       for (int i= 0; i<myStack.length; i++) 
       {
           outString = outString+myStack[i];
           
           top++;
       }
      
     
      return outString;
    }
    

     //reverse string using push and pop methods
     String reverse(String n)
     {
         setSize(n);
         push(n);
         n = pop();
         
         return n;
         
     }
   
     /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
       String str;  //Declaratio of string to be reversed
       
       Scanner read = new Scanner(System.in);  
       
       System.out.println("Enter String Input: ");
       str = read.nextLine();  //read string from keyboard input
       
       //Declare a new stackImplementaton object
      StackImplementation reverseString = new StackImplementation();
       
       //reverse string input using stackImplementation
       str = reverseString.reverse(str);
       
       //Prints input string in reverse order   
       System.out.println(str);
          
   }
        
    }


OUTPUT:

run:

Enter String Input: 

Tunji

ijnuT

BUILD SUCCESSFUL (total time: 3 seconds)


    
Please comment or suggest better implementation: Tunji4physics2@gmail.com

Wednesday, 23 September 2015

Java Concept

Array List: Insertion and Deletion Mechanism

Code:
/*
 * This is a simple program that enable dynamic deletion and.
 * insertion of data element from and into an array object.
 */
package arraydatastructure;

import java.util.Arrays;

/**
 *
 * @author Adeniran Adetunji
 */
public class Insert_Delete_from_Array {
    
//This method delete element at position 'pos' from and array 'data'


 public int [] deleteElement (int[]data, int pos)
{
    //check if postion 'pos' is within the length of the array
    
    if(pos >= 0 && pos <data.length)
{
            
    int[] dataCopy = new int[data.length-1];
    
   
    System.arraycopy (data, 0, dataCopy, 0, (pos-1));
    
    System.arraycopy(data, pos,dataCopy, pos-1, 
                      dataCopy.length-(pos-1));
    
    data=dataCopy;
    
       
    }
    return data;
    }
     
 //Method to insert data element into an array

    public int [] InsertElement (int[]dataA,int data, int pos)
{
    
    if(pos >= 0 && pos <dataA.length)
    {
        
         int[]dataCopy= new int[dataA.length+1];
    
     //adding element to array
    
    System.arraycopy(dataA, 0, dataCopy, 0, pos-1);
    
    dataCopy[pos-1] = data;
    
    System.arraycopy(dataA, pos-1, dataCopy, pos, 
                     dataA.length-(pos-1));
    
    dataA = dataCopy;
    }
    
    return dataA;
  
}
  // Testing the methods in the 'main' method
      public static void main(String args[]) {
          
          //creating array 'a' with data 1,2,3,4,5,6,7,8,9,10
          int[]a = {1,2,3,4,5,6,7,8,9,10};
          
          //converting array 'a' to string and print
          System.out.println(Arrays.toString(a));
          
          //creating and object of the type Insert_Delete_from_Array
          
          Insert_Delete_from_Array obj = new                                   Insert_Delete_from_Array();
          
          //delet element at postion 7 from array a
          a = obj.deleteElement(a, 7);
          
          //Convert array 'a' to string and print
          System.out.println(Arrays.toString(a));
          
          //insert '21' into postiont '8' in array 'a'
          a = obj.InsertElement(a, 21, 8);
          
          System.out.println(Arrays.toString(a));
          
          
      }
}

Output:

run:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

[1, 2, 3, 4, 5, 6, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 8, 21, 9, 10]
BUILD SUCCESSFUL (total time: 9 seconds)



Saturday, 12 September 2015

Introductio to Logic and Number System Tutorial Questions

Tutorial Questions 


(a) What is the largest binary number that can be expressed with 24 bits? What are the equivalent decimal and hexadecimal number?
(b)   Determine the base/radix of the numbers in each case for the following operations to be correct:
         (i)  29 + 17 = 40    (ii) 7 + 6  = 15    (iii)  67 + 24 = 113
(c)  Covert the hexadecimal number AD54 to binary, and then convert it from binary to octal
(d) Convert the decimal number 198 to binary in two ways: (a) convert directly to binary; (b) convert first to hexadecimal and then from hexadecimal to binary. Which method is faster?
(e) Express the following numbers in decimal:

         (i)  (10110.0101)2         (ii)  (69.8)16     (ii)  (73.65)   (iv)  (1110.0101)2   (v)  (BEBE.C)16
(f) Differentiate between Analog and Digital electronic system with respect to the following concept;  i.                    Signal   ii.  Representation of value.   iii.   Technology/Technique   iv.  Response to noisev.  Uses/Application.   
(g)  Number systems are characterized by the following;
            i.   The number of independent digits used in the number system.
            ii.  The place value of different digits constituting a value in the system.
            iii.  The maximum number that can be written with a given number of digits. Explain these    characteristics with respect to the following number systems using arbitrary examples;
           1.    Decimal   2.  Octal   3.  Hexadecimal   4.  Binary.                                                                     
(h)  Determine the base/radix (number system) of the number in each case for the following operation to be correct.
i.                    29+17 = 40 
ii.                  7+6 = 15 
iii.                67+24+133
(i) Solve each of the following using comfortable number of bits subtraction problems using 2’s complement arithmetic.
        i.  011111112 - 7810 
       ii.  001100102 - 12310 
       iii.   010010012 - 11110
      iv.   (3E91)16 – (1DEF)16 
(j) Write out the expression for the Boolean function bellow;





(k)  Simplify the expression in (i), and hence implement the logic circuit for the simplified       expression.
(l) Show that;
 , using perfect induction method.


(m)  In a scenario to design a bank vault lock; there are three (3) key holders to the lock; the manager, senior bank officer, and a cashier. To open the vault, at least two (2) keys  (i.e. two key holders) must be available. If the cashier is to open the vault, the managers’ key must be available. Design a logic circuit to implement the vault lock following these procedure;
       1. Define the input and output variables.
       2. Obtain the Boolean expression for the lock
       3. Simplify the expression obtained in (ii)
       4. Design the logic circuit for the vault lock.

Friday, 6 February 2015

Introduction To Digital Electronics and Logic (Chapter 3: Digital Arithmetic)



3.0       DIGITAL ARITHMETIC
Data presentation and representation is for a purpose, haven discussed different ways of representing digital data, and the next step is to study how this data are manipulated in specific operations.
The types of manipulative operations data are performed on data include arithmetic operations20 and logic operations21. Basic arithmetic operations include addition, subtraction, multiplication and division. While basic logic operations are; AND, OR and NOT. In this chapter, we will discuss the rules that govern arithmetic operations on digital data. In later chapters we will study logic operations on digital data.
3.1       Binary Addition and Subtraction Rules
Arithmetic rules for binary numbers are quite straightforward, and similar to those used in decimal arithmetic. The rules for addition of binary numbers are:
Table 3.1: Rules of binary addition

Addition 
Sum
Carry
0  +  0
0
0
0  +  1
1
0
1  +  0
1
0
1  +  1
0
1
1 + 1 + 1
1
1
 







 Binary addition22 is carried out just like the decimal addition that we are used to, in decimal addition, when the result of the addition in a particular digit is equal or greater than the radix/base value of the system (i.e. ten for decimal), it produces a carry to the next higher bit and the sum will be the ‘result’ of addition minus the radix/base value.
For example:
 


  


For  7 +  3, the result is ‘10’ which is equal to the radix/base of decimal system a carry is produce to the next higher digit and radix value (‘10’) is deducted from the result ‘10’ remain ‘0’ as the sum. For 8 + 7, result is ‘15’ obviously greater than the radix value ‘10’ carry ‘1’ is produced to the next higher digit, radix value ‘10’ is deducted from ‘15’, thus remaining sum  of  ‘5’. In the case of 2 + 8, the result is 8 which is less than the radix value, no carry is produce and the sum is ‘8’.
This same process applies for the binary arithmetic rule described in table 3.1 above, 0 + 0 result to ‘0’, this result is less than the binary radix value which is ‘2’, thus leaving the sum as ‘0’ and no carry is produced. Same for 0 + 1 and 1 + 0 which produces a sum of ‘1’ and no carry i.e. ‘0’.
For 1 + 1,  the result of addition is 2 which is equal/greater than the radix value ‘2’, thus produces a carry ‘1’ and by deducting the radix value ‘2’ from the result of addition ‘2’ it leaves the sum as ‘0’. For 1 + 1 +1,  the result is ‘3’ obviously will produce a carry ‘1’, deducting radix value ‘2’ from addition result ‘3’, we are left with sum of ‘1’.

Binary subtraction rules
Again likened to the decimal rules of subtraction, when we deduct a lesser number from a larger number the subtraction is straight forward e.g.  8 – 2  = ‘difference’   6 (in decimal). But when a large number is being subtracted from a lesser number, a borrow is required from the next higher digit e.g. 5 – 8 = ‘Difference’   7 ‘borrow’ 1, in this case, the borrow from the higher digit takes up the radix value ‘10’ in the next lower digit. The rules for binary subtraction23 are summarized in table 3.2 bellow.

Table 3.2: Rules of binary subtraction


Subtraction
Difference
Borrow
0  -  0
0
0
0  -  1
1
1
1  -  0
1
0
1  -  1
0
1
1 – 1 -1
1
1
 

















3.2 Binary Addition and Subtraction with larger bits
Our illustration so far has been on one bit binary and in a practical situation; addition and subtraction in binary are usually in larger bits. We discuss with examples the process of adding and subtracting binary numbers of larger bits.

















In the examples above we have illustrated how binary numbers of more bits can be added or subtracted from one another. But there is a clause; what if we have a situation where we are required to subtract 1110 (1011)  from 910 (1001) i.e.  1011 – 1001.
for example;
  
9          1001
-  11       - 1011This operation is not possible with unsigned binary representation
-    2                    
 


So far we have dealt with binary additions of only POSITIVE numbers or subtractions that yield only POSITIVE results. The reason for this is that it is not possible in PURE (or unsigned) binary to signify whether a number is positive or negative. This we lead us to the next topic on Signed binary numbers.

3.3   Signed Binary24
To represent a binary number signifying its sign, we have to device a means of identifying the sign within the range of symbols available to the binary number system, i.e. {0 and 1}. In signed binary number, we represent the sign of a particular number, using the MSB of the number as the sign bit and remaining bits as the magnitude bits.  ‘0’ denotes Positive (+)  and ‘1’ mean Negative (-), for example;










In the eight bit binary representation of decimal +27 and -27 above, the MSB denotes the sign of the number, while the remaining seven bits represents the magnitude of the number. 


The use of signed binary with sign bit to perform arithmetic operation in digital system involves a lot more work, because certain bit in the stream must be treated as special, this means it will require a more complex and thus expensive circuits. Aim of digital electronics designers is to optimize design by making the circuit simpler, more functional and less expensive.
A better means of performing digital arithmetic with adequate representation and interpretation of signed numbers is the use of complements of binary numbers. These are One’s complement and Two’s complement representation.
 
3.4   Complements of binary numbers
Complements are used in digital computers to simplify the subtraction operation and for logical manipulation. Simplifying operations leads to simpler, less expensive circuits to implement the operations. For binary numbers, we have 1’s complement and 2’s complement.
In mathematics, subtraction can be implemented in a variety of different ways as A – B, is the same as saying A + (-B) or –B + A. Using complements, subtraction of two binary numbers can be performed by simply using addition, i.e. A – B = A + (-B), -B is the complement of B.

3.4.1   One’s  Complement25
The complement (or opposite) of +4 is −4.  One’s Complement (1’s complement) is a way of representing negative binary numbers in a signed binary number system. In 1’s complement, positive numbers (also called non-complements) remain unchanged as before with the sign-magnitude numbers.
Negative numbers however, are represented by taking the 1’s complement of the positive number. To obtain 1’s compliment of a binary number, we subtract each digit of the number from 1. For example;












We will observe in the examples above that, when subtracting binary digit from ‘1’, we can have either 1 – 0  = 1 or  1 – 1 =  0, which causes the bit to change from 0 to 1 or from 1 to 0m respectively. Therefore, 1’s complement of a binary number is formed by changing 1’s to 0’s and 0’s to 1’s.
For example:
+510 is 000001012 and   510 is 111110102 (1’s Complement)
In the example above, the most significant bit (MSB) in the negative number –510 is 1, just as in signed binary. The remaining 7 bits of the negative number however are not the same as in signed binary notation. They are just the complement of the remaining 7 bits, and these give the value or magnitude of the number.

Binary Addition26  and Subtraction with 1’s Complement
Both addition and subtraction in 1’s complement are addition; subtraction is just the addition of the 1’s complement of the Subtrahend i.e.  8 – 3 = 8 + (-3). 
The steps are as follows;
1.      Convert negative numbers to its equivalent 1’s complements
2.      Leave all positive numbers unchanged
3.      Perform binary addition on the numbers
4.      Add any carry out of the sign bit to the result.
5.      It the result is negative (i.e. MSB = 1) find its 1’s complement.
6.      If the result is positive (i.e. MSB = 0) leave the result as it is.


Let’s illustrate these steps with examples.
Example 3.4 Add -4 and + 6 using ones compliment




















The result in this case is a negative number because the MSB =  1, therefore we have to determine the complement of the number i.e. the positive value of the number by finding its 1’compliment;
1’s complement of 11111000 ≡  00000111  =  +7,  therefore the answer 11111000 = -7 (correct)
Note that, n-bit notation can be used to represent numbers in the range from –(2n-1 – 1) to +(2n-1-1) using the 1’s complement format.
Using 1’s complement in binary addition and subtraction has limitation in that we have to consider the overflow into a non-existing bit to obtain a correct value of our operation. This took us to the next better option which is 2’s complement.

3.4.2   Two’s Complement27
Two’s complement (2’s Complement) notation solves the problem of the relationship between positive and negative numbers, and achieves accurate results in subtractions without the need to consider the carry into a non-existing binary bit.
To perform binary subtraction28 the twos complement system uses the technique of complementing the number to be subtracted.
To produce a negative number in two complement system, we simply find the 1’s complement of the number and add 1.
For example;
2’s complement of +6 ≡  000000110  =  11111001  (1’s complement)
                                                                      +           1
                                                                     11111010   (2’s complement)


Addition and Subtraction using 2’s complement
1.      Convert negative numbers to its equivalent 2’s complements
2.      Leave all positive numbers unchanged
3.      Perform binary addition on the numbers
4.       Discard any carry out of the sign bit.
5.      It the result is negative (i.e. MSB = 1) find its 2’s complement.
6.      If the result is positive (i.e. MSB = 0) leave the result as it is.

Example 3.6: Add +5 and -5 in binary using 2’s complement.



 




























Again, n-bit notation can be used to represent numbers in the range from –(2n-1 ) to +(2n-1-1) using the 1’s complement format.

Overflow29
In order to obtain a correct answer, we must ensure that the result had a sufficient number of bits to accommodate the sum. If we start with two n-bit numbers and the sum occupies n + 1 bits, we say that an overflow occurs.  When one performs the addition with paper and pencil, an overflow is not a problem, because we are not limited by the width of the page. We just add another 0 to a positive number or another 1 to a negative number in the most significant position to extend the number to n+1 bits and then perform the addition. Overflow is a problem in computer because the number of bits that hold a number is finite, and a result that exceeds the finite value by 1 cannot be accommodated.
For example;
 
Example 3.8:
            With four bits perform -6 -3 using 2’s complement..
            + 6 ≡  0110 
            + 3 ≡  0011 
            -  6 ≡  1010  (2’s complement)
            -  3 ≡  1101 (2’s complement)








The result obtain in example 3.8 is obviously wrong, -6-3 = -9 not +7, discrepancy in the answer is due to the fact that the expected result can not be accommodate in four bit binary, for a sign binary representation as mentioned earlier, N bit number will represent from – 2N-1-1  to +2N-1-1 decimal number.  In this example, 4 bit can represent -24-1to +24-1-1 i.e. -8 to +7. The expected result of -9 is not within this range and thus overflow occurs. To detect overflow in signed binary addition; if the carry-in to the sign bit is not equal to carry-out of the sign bit, overflow has occur. That, is to obtain correct result with addition in 2’s complement, the carry-in to the sign bit must be the same with the carry out of the sign bit. For example 3.8, carry-in to the sign bit is ‘0’ while carry-out of the sign bit is ‘1’.
           
Earlier in the this chapter, we stated that the basic binary arithmetic operations are addition, subtraction, multiplication and division. We have been able to discuss how digital circuit perform addition and subtraction as addition of negative numbers.We will not cover binary multiplication and division in this text, but it is worth mentioning that multiplication is performed as repeated addition while subtraction is performed as repeated subtraction in digital circuit. In this chapter we have extensively discussed the process of binary addition and subtraction, earlier we mentioned that the basic binary arithmetic operations are addition, subtraction, multiplication and division. We will not cover binary multiplication and binary division in this text, but it is helpful for exploration reader to mention here that, binary multiplication is simply repeated addition30 while binary division is simply repeated subtraction31.

Exercise 3

a.      Obtain the 1’s and 2’s Complements of the following binary numbers:

i.  00010000  ii. 00000000  iii.  11011010           iv.  10101010
v. 10000101  vi. 11111111
b.      Write the eight-bit 2’s complement representation of (-23)10
c.      What is the first thing you must do in order to solve the subtraction problem 1110 – 410 using 2’s compliment.
d.      What is the general technique for subtracting binary numbers using 2’s compliment.
e.      Solve each of the following 5-bit subtraction problems using 2’s complement representation.
i.        001102 - 001012
ii.     011002 - 010102
iii.   001002 - 001012
iv.   010012 -010112
v.      000112 - 011002
f.       Solve each of the following 8-bit subtraction problems using 2’s complement representation:
i.        011111112 - 7810
ii.     001100102 - 12310
iii.   010010012 - 11110
iv.   000001112 - 3510
g.      Perform operation (3E91)16 – (1DEF)16 using 2’s complement arithmetic.
h.      Convert your answers from question (3) to decimal.
i.        Prove that 16-bit 2’s complement arithmetic cannot be used to add +18150 and +14618, while it can be sued to add -18150 and -14618