Tuesday, November 1, 2016

Data Structures-STACK (continued)

Hello! Today I am going to give complete pseudocode of the stack array implementation.And at the end of the the page,you can find the java implementation of the stack array.

Complete pseudocode of the stack array implementation

class Stack{
                fields{
                        top < - 1;
                        array S;
                       CAPACITY <- n ;
                }
                isEmpty(){
                                if(top==-1)
                                                return TRUE;
                                else
                                                return FALSE;
                }
                push(x){
                                if(CAPACITY > size()){
                                                top <-top+1;
                                                S[top] <- x;
                                }else{
                                                print("stack is overflow");
                                }
                }
                size(){
                                return top;
                }
                pop(){
                                if (isEmpty()){
                                                print ("Stack is underflow");
                                }
                                else{
                                                temp <- S[top];
                                                S[top] <- NULL;
                                                top <- top-1;
                                                return temp;
                                }
                }
                top(){
                                if isEmpty()
                                                print ("NULL");
                                else
                                                return S[top];
                }
}


Java Implementation of Stack Array 
Note:My advise is try to write your own code snippets.After your creations ,then you can compare that with my implementation.This will be more interesting than reading my code snippet. Sometimes your code may better than me.

public class Stack {

    int CAPACITY = 4;
    int s[] = new int[CAPACITY];
    int top = -1;

    boolean isEmpty() {
        if (top == -1) {
            return true;
        } else {
            return false;
        }
    }

    void push(int x) {
        if (CAPACITY > top) {
            top = top + 1;
            s[top] = x;
        } else {
            System.out.println("Stack is overflow");
        }
    }

    int size() {
        if (isEmpty() == true) {
            return 0;
        } else {
            return top + 1;
        }

    }

    String pop() {
        if (isEmpty() == true) {
            return "Stack is Underflow";
        } else {
            int temp = s[top];
            //s[top]=null;
            top = top - 1;
            return Integer.toString(temp);
        }

    }

    String top() {
        if (isEmpty() == true) {
            return "NULL";

        } else {
            int temp = s[top];

            return Integer.toString(top);

        }

    }
}
BUT HOW WE KNOW THIS IS WORKING OR NOT???

Here is the solution.

Below is the demo class which include comments,"how we are going to test the above stack array implementation".

package datastructures;

/**
 *
 * @author hasitha
 */
public class StackDemo {
    public static void main(String[] args) {

         //Create a empty stack
         Stack s=new Stack();

        //Since there are no elements at the biginning stage,then the stack is currently underflow
        System.out.println(s.pop());

        //Check the initial size of the array stack
        System.out.println("Initial size :"+s.size());

        //Add 4 elements to the array stack
        s.push(10);
        s.push(15);
        s.push(4);
        s.push(5);
        //Now stack size should be 4
        System.out.println("After insrting 4 elements, size :"+s.size());

        //Call pop() method sth times,will remove and return elements in LIFO manner
        System.out.println("1st call for method pop() :"+s.pop());
        System.out.println("2st call for method pop() :"+s.pop());
        System.out.println("3 st callfor method pop() :"+s.pop());
        System.out.println("4 st call for method pop() :"+s.pop());

//Now corrently stack is empty.Again call for pop() method.This should print"stack is underflow"
        System.out.println("5 st call for method pop() :"+s.pop());

        //Check current status of the stack(empty or not?)
        System.out.println("call for isEmpty() :"+s.isEmpty());
    }
   
}
If there is any amendments, please drop me an email or comment below.

Sunday, October 2, 2016

Data Structures


Before going to learn DS, that is mandatory to answer the following questions:
What are data structures and algorithms?
What good will it do me to know about them?
Why can't I just use arrays and for loops to handle my data?

In this section I am going to discuss about some frequently used data structures with their practical usage. For understanding and multi-language usage purpose, I thought to give a specified data structure in some different ways. Most of the cases I will discussed in following order.

·         What is and why?
  •       In here I will discuss about the some general practical usages of a particular data structure (DS) in the ‘Beginner’s Eye’.

·         How to represent a data structure without depending a programming language
  •       In here I present the data structure in more generic view. Hence you can grab the concept and you can implement this structure without worry about your preference language.

·         How to implement using Java (Only For JAVA Developers)
  •       This section is optional .I include this section mainly because my preferred programming language is java. 
      There are several ways to implement a specified DS. I implemented a particular data structure in one or two ways .You can use in your own way without worry about others.
              

·         Practical Activities (IMPORTANT)
  • In this section, I give some practical problems associated with that particular DS. You should try to implement that in your preferred programming language. I will only give java solution for that problem because my preferred language is java. If you have a trouble in your preferred language, please drop a comment or drop an email to me. I will help to solve that.\

STACKS and QUEUES

If we want to store 1 to 10 numbers, we can use array to this purpose. If we know the index, which want to access, then we can directly access it.BUT stacks and queues are not same as arrays. We give restricted access to the user. We cannot access data element in the middle of the stack. Only one item can be read or removed at a given time.

IN DEEPLY
Stacks, queues, and priority queues are more abstract entities than arrays. They are defined primarily by their interface. The underlying mechanism used to implement them is typically not visible to their user. For examples:
  •  A Stack can be implement using either using an array or Linked List.
  •   A Priority Queue can be implement using a array or heap.

STACK

      What is and why?
      A stack is “a pile of objects, typically one that is neatly arranged”.
     
     
   
     You can the real world examples of stacks. We can place or remove a card or plate from top of the stack only. I am not going to give deep details about general view point because you can find those details from the web. But I want to tell you how to construct a stack data structure in pro grammatically.
     
      The Stack Operations
           Push                    : pushing (storing) an element on the stack.
           Pop                      : get the top element from the stack and remove it from stack.
           Top/Peek             : get the top data element of the stack, without removing it.
           isEmpty              : check if stack is empty
           Size                     : return the size of the stack
    
      Stack Data Structure without Specifying a Programming Language
     
     Method 1: Stack interpretation using an array

Stack Class:
                fields{
                                top <- 0    //initially stack has no items. Then top returns 0
                                array s    //we use an array to stack implementation
                                capacity <- n   //since we use array implementation, we have to tell the array size in the initial stage
                         }
                methods{
                             push();
                             pop();
                             peek();
                             isEmpty();
                             size();
                        }


Now we need to know how to implement those methods. Let’s go”STEP by STEP” processes for that task.
Our initial array looks like:


“isEmpty” Method

In the initial stage we assign our variable ‘top’ to value ‘0’.When checking value of the ‘top’,we can make conclusion as the stack is empty or not.

isEmpty(){
        IF( top=0 )
              Return TRUE;
        ELSE
              Return FALSE;
}

size()” Method

The stack size is different from the “Capacity” variable. Capacity variable tells the size of the array which does not tell the size of the stack. It uses for array implementation because when we define a array, we need to tell exactly, what the array size before insert data items into it.

“Top” variable keeps the current pointer of the array. When we push(add) the first element to the array ‘S’, then  the ‘top’ becomes its value as 1.Which means stack has only one element.


Similarly, when we push 2nd element, then the value of ‘top’, becomes 2.


Therefore, if we return the value of the variable ‘top’, then that will be the exact value of the stack current size.

Size(){
     Return top;
}
push(x)” Method

Now we are going to insert a new data item to our stack  where ‘x’ is the data item and ‘S’ is the name of the stack.
Now you know, variable ’top’ point to the current last inserted element in the stack.Therefore you can easily point the next place to insert the data item by:

Push(x){
     top <- top+1
     S[top] <- x

}
Is that complete our work? What happens, if the stack is already filled?. Because this is array implementation. Therefore you may think, need one additional method called,”isFull()”.YES, you are correct. But we can do that requirement without bothering about additional methods. See the following implementation:

Push(x){
      IF (capacity>size()){
             top <-top+1
             S[top] <- x
       }ELSE
              Error “Stack Overflow”;
     }

pop()” Method

When you call the pop(),then it will returns the top most element of the stack and delete that element from the stack. But actually we do not going to delete the top most element from the stack. In order to show that, we use some tricky way. We change the variable ‘top’, location to :
top <- top-1
This means, if user request for top element later, then it seems to delete the old top. But if you prefer, you can set it to “NULL”.

Pop(){
        IF(isEmpty()){
             Error “Stack Underflow”
        }ELSE{
              temp <- S[top]
              S[top] <- NULL
              top <- top-1
              Return temp;
        }
    }

peek()” Method

Hope you can do this by yourself.
If you having problem, please put a comment or drop a email.

Friday, September 9, 2016

How TO done Sample uploaded to lms



Question 3:Consider the following SQL snipped used to create three tables.


a.       Write an SQL query to list all the courses.

b.      Write select * from coursesan SQL query to list all the students who are registered for a course with CourseId 4.

My Answer:


1)SELECT * FROM courses;
2)SELECT s.StudentId,s.FirstName,s.LastName FROM courses c INNER JOIN coursemembership cm ON c.CourseId=cm.CourseId INNER JOIN students s ON cm.StudentId=s.StudentId WHERE c.CourseId=4;



Question 4: Write a program with the following aspects: [30 marks]
a. Implement the following logic:
If the lighting level is dark, and power is off, turn the emergency lamp on.

If the lighting level is bright, or the power is on, the emergency lamp off.


public class LigtingLevel {

   public static String ligtingLevel = "Dark";
   public static   String mypower = "Off";
    public static void main(String[] args) {
         if (("Dark".equals(ligtingLevel))&&("Off".equals(mypower))) {
             System.out.println("Power ON");
            
         } else if(("Bright".equals(ligtingLevel))||("On".equals(mypower))) {
             System.out.println("Power Off");
         }
       
    }
  
  

}


b. Implement the following formula:
Root finding formula


public class RootFinder {

    public static void main(String[] args) {
        double a = 10;
        double b = -4;
        double c = 4;
        double delta = b * b - 4 * a * c;

        if (delta >= 0) {
            double rootDelta = Math.sqrt(delta);
            double root1 = (-b + rootDelta) / (2 * a);
            double root2 = (-b - rootDelta) / (2 * a);
            System.out.println("Root 1:" + root1);
            System.out.println("Root 2:" + root2);

        } else {
            double absDelta = Math.abs(delta);
            double rootDelta = Math.sqrt(absDelta);
            System.out.println("Real1:" + (-b) / (2 * a) + " Imeginary1:" + rootDelta / (2 * a) + "i");
            System.out.println("Real2:" + (-b) / (2 * a) + " Imeginary2:" + rootDelta / (2 * a) + "i");
        }

    }

}

c. Sum of the integers in an array. Assume that the length of the array is available.


public class SumArray {
    public static void main(String[] args) {
        int arr[]={1,2,3,4,5,6};
        int sum=0;
        for (int i = 0; i < arr.length; i++) {
           
            sum=sum+arr[i];
            
        }
        System.out.println(sum);
    }
   
}

d. Find the largest element in an array. You may not use a system sort function.


public class LargestElement {

    static int arr[] = {2, 51, 1, 7, 13, 9};
    public static int num1;
    public static int num2;
    public static int lager = 2;

    public static void main(String[] args) {

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

            if (lager < arr[i]) {
                lager = arr[i];
            }

        }
        System.out.println("larger :" + lager);
    }
}


d. Find the largest element in an array. You may not use a system sort function.

I used bubble sort to sort the integer array.


public class BubbleSort {

    public static void main(String[] args) {
        int arr[] = {6, 4, 3, 9, 7};
        int temp;
        for (int iteration = 0; iteration < arr.length - 1; iteration++) {
            for (int j = 0; j < arr.length - 1 - iteration; j++) {
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }

            }

        }
        for (int i : arr) {
            System.out.print(i + " ");
        }
        System.out.println("Largest:" + arr[arr.length - 1]);

    }

}

Question 5:
i. Create a class called Point with two doubles for the coordinate and
.
ii. Provide a constructor for this class.
iii. Add a method to print the point on console.
iv. Add a method to scale a point by a given factor.
v. Create a point in the main method and display.
vi. Create a class called ColoredPoint by inheriting from this. Add a constructor.
vii. “Print” the objects on console.


public class Point {
    double x;
    double y;

    public Point() {
        x = 2;
        y = 0;

    }
    public static void main(String[] args) {
        Point p = new Point();
        p.printPoint();
        p.scalePoint(5);

    }
    void printPoint() {
        System.out.println("X:" + x);
        System.out.println("Y:" + y);
    }

    void scalePoint(double scale) {
        System.out.println("X:" + x * scale);
        System.out.println("Y:" + y * scale);
    }

}

public class ColoredPoint extends Point {

    public ColoredPoint() {
    }
    public static void main(String[] args) {
        ColoredPoint c = new ColoredPoint();

        c.printPoint();
    }
}


spring-mvc-crud-demo-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx.xsd">

<!-- Add support for component scanning -->
<context:component-scan base-package="com.luv2code.springdemo" />

<!-- Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>

<!-- Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>

    <!-- Step 1: Define Database DataSource / connection pool -->
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false" />
        <property name="user" value="springstudent" />
        <property name="password" value="springstudent" /> 

        <!-- these are connection pool properties for C3P0 -->
        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
</bean>  
    <!-- Step 2: Setup Hibernate session factory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.luv2code.springdemo.entity" />
<property name="hibernateProperties">
  <props>
     <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
     <prop key="hibernate.show_sql">true</prop>
  </props>
</property>
   </bean>  

    <!-- Step 3: Setup Hibernate transaction manager -->
<bean id="myTransactionManager"
            class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    
    <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="myTransactionManager" />

</beans>




web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>spring-mvc-crud-demo</display-name>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/spring-mvc-crud-demo-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>



CustomerDAO
package com.luv2code.springdemo.dao;

import java.util.List;

import com.luv2code.springdemo.entity.Customer;

public interface CustomerDAO {

public List<Customer> getCustomers();
}

CustomerDAOImpl
package com.luv2code.springdemo.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.luv2code.springdemo.entity.Customer;

@Repository
public class CustomerDAOImpl implements CustomerDAO {

// need to inject the session factory
@Autowired
private SessionFactory sessionFactory;
@Override
@Transactional
public List<Customer> getCustomers() {
// get the current hibernate session
Session currentSession = sessionFactory.getCurrentSession();
// create a query
Query<Customer> theQuery = 
currentSession.createQuery("from Customer", Customer.class);
// execute query and get result list
List<Customer> customers = theQuery.getResultList();
// return the results
return customers;
}

}



Customer
package com.luv2code.springdemo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="customer")
public class Customer {

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
private int id;
@Column(name="first_name")
private String firstName;
@Column(name="last_name")
private String lastName;
@Column(name="email")
private String email;
public Customer() {
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

@Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}




CustomerController
package com.luv2code.springdemo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.luv2code.springdemo.dao.CustomerDAO;
import com.luv2code.springdemo.entity.Customer;

@Controller
@RequestMapping("/customer")
public class CustomerController {

// need to inject the customer dao
@Autowired
private CustomerDAO customerDAO;
@RequestMapping("/list")
public String listCustomers(Model theModel) {
// get customers from the dao
List<Customer> theCustomers = customerDAO.getCustomers();
// add the customers to the model
theModel.addAttribute("customers", theCustomers);
return "list-customers";
}
}


commons-logging-1.2
javax.servlet.jsp.jstl-1.2.1
javax.servlet.jsp.jstl-api-1.2.1
mysql-connector-java-5.1.39-bin