Thứ Bảy, 27 tháng 9, 2014

Thread Demo

question:

There are three threads in a process. The first thread prints 1 1 1 …, the second one prints 2 2
2 …, and the third one prints 3 3 3 … endlessly. How do you schedule these three threads in order to print 1 2 3 1 2 3 …?

solution:

package com.shashi;

class ThreadDemo1 extends Thread
{
   
private int val;
public ThreadDemo1(int val)
{
    this.val=val;
    start();
}
public void run()
{
    while(true)
    {
        synchronized(this)
        {
        try
        {
            wait();
        }
        catch(Exception e)
            {System.out.print(e.getLocalizedMessage());}
            System.out.print(val+" ");
        }
    }
}
   
}

public class ThreadDemo
{
    public static void main(String []args)
    {
        ThreadDemo1 arr[]=new ThreadDemo1[3];
        for(int i=0;i<3;i++)
        {
            arr[i]=new ThreadDemo1(i+1);
        }
        int index=0;
        while(true)
        {
            synchronized(arr[index])
            {
                arr[index].notify();
            }
            try
            {
                Thread.sleep(1000);
            }
            catch(Exception e){System.out.print(e.getLocalizedMessage());}
            index=(++index)%3;
        }
    }
}



output:

------------------------------
1 2 3 1 2 3 1 2 3 1 2 3 .................so on!!!!!
------------------------------


Explanation:

1.first create three threads ,here i created array of three threads.
2.now in order to print format like 1 2 3 1 2 3 ...........,you have to create locks .Here i created locks by using synchronized block.

logic:

if(any thread is avilable)
call wait();
repeat above step;
//next step is to wake up your thread
call notify();

 


Thứ Tư, 17 tháng 9, 2014

Programming Problem



You are given an unsorted array of n^2 arbitrary numbers, and we must output an n x n matrix of all the inputs such that all the rows and columns are sorted. For example, suppose n=3, n^2=9, and the 9 numbers are just the integers {1,2,...,9}
Possible ouput include:

1 4 7       


2 5 8      


3 6 9       


Am giving solution for this problem ...
Note:
to use this program in your machine you need to add my com.shashi.jcore package.you can download that by clicking link:download


program:

=============================================================

import java.util.Arrays;
 

import com.shashi.jcore.Matrix;
import com.shashi.jcore.SException;
public class ArrayClass {
 
 
public static void main(String []args) throws SException
 
{
int arr[]={2,1,4,3,6,5,8,7,9};
Arrays.sort(arr);
passArray(arr);
 
}
public static void passArray(int a[]) throws SException
 
{
int len=(int)Math.ceil(Math.sqrt(a.length));
int index=-1,row=0,col;
int arr[][]=new int[len][len];
for(;;)
 
{
for(col=0;col<len;col++)
 
{
arr[row][col]=a[++index];
 
}
row++;
if(row==len)
break;
 
}
//trnspose matrix now/*
Matrix m=new Matrix();
m.printMatTranspose(arr);
 
}
}
============================================
output:

1 4 7

2 5 8

3 6 9
 

Chủ Nhật, 14 tháng 9, 2014

C program with out main

Can You Write a C program with out main ????


If any one asks you this question from now say yes!!!!!Of course you can create a Cprogram and run it with out giving any main() function.

see below code snippet ..written by me


#include<stdio.h>
#include<conio.h>
#define code(s,h,a,v,r,c,e)e##v##s##c
#define decode code(i,h,u,a,r,n,m)
int decode()
{
clrscr();
printf("hello shashi kumar");
return 0;
}


output :

hello shashi kumar

------------------------------------------------
You might have confused by seeing above code .But it works fine(copy the code and run it on your own machine).

note:we are not calling main() in our  program but internally it calls.

How does the  above code works???

Its simple. We all know that C preprocessors  were compiled before actual program starts compiling, so I created two simple preprocessors here, namely

#define code(s,h,a,v,r,c,e)e##v##s##c ,#define decode code(i,h,u,a,r,n,m).

First one have arguments(),followed by e##v##s##c.Here #(pond[hash])  appends each character with its previous characters so whole statements treated as evsc .

The character e in evsc presented at 7th position of argument list of code(.....e),v presented at 4th position ,s presented at 1st position ,c presented at 6th position .

Next second preprocessor with a name decode  is calling code() of arguments i'e the positions of each character of code is substituted by positions of evsc.
i'e  e substituted by m
       v substituted by a
       s substituted by i
       c substituted by n










 

Thứ Sáu, 12 tháng 9, 2014

Problem:

Given a string , find if it is a palindrome or not. This string can contain special characters like comma hypen colon space semicolon etc. The program should ignore these special characters and find if the rest of the string is palindrome or not. Examples: 1. If the input string is "zapqa", the program should return "Not a Palindrome" 2. If the input string is "a,b-c;b^a ", the program should return "Palindrome" as it would ignore the special characters and the rest of the string abcba is a palindrome. The list of special characters that the program should ignore are `~!@#$%^&*()-_+={[}],<>?


solution:




package com.shashi;


import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Scanner;
class stack1
{
private char mystack[],temp[];
private int length;
stack1(int length)
{
this.length=length;
mystack=new char[length];
}
private int top=-1;
void push(char ele)throws Exception
{
if(top==mystack.length-1)
{
  
temp=new char[mystack.length*2];
for(int i:mystack)
temp[i]=mystack[i];
mystack=temp;
mystack[++top]=ele;
}
else
mystack[++top]=ele;
}
public char pop()throws Exception
{

  if(top==-1)
  return ' ';
  else
  
return mystack[top--];
}
}

public class Polyndrome {

public static void main(String []args)throws Exception
{
boolean ispoly=false;
char che;
System.out.print("Enter your string:");
Scanner sc=new Scanner(System.in);
String data=sc.next();
ArrayList<Character>list=new ArrayList<Character>();
stack1 st=new stack1(data.length());
for(int i=0;i<data.length();i++)
{
if(isChar(data.charAt(i)))

list.add(data.charAt(i));

}
//copy all data from list to stack1
Iterator<Character > ite=list.iterator();
while(ite.hasNext())
{
st.push(ite.next());
}


for(int i=0;i<list.size();i++)
{
   che=list.get(i);
if(che==st.pop())
ispoly=true;
else
ispoly=false;
}

if(ispoly)
System.out.println("String is polyndrom");
else
System.out.print("String is not a palindrome");
}

public static boolean isChar(char c)
{
if((c>='a'&& c<='z') || (c>='A' && c<='Z'))
return true;
else
return false;

}

}

output:1

Enter your string:a,b-c;b^a
String is polyndrom

output 2:
Enter your string:shashi
String is not a palindrome

output:3
Enter your string:zapqa
String is not a palindrome


Thứ Năm, 11 tháng 9, 2014

Creating Stored Procedures in MYSQL.

A Stored procedure is a set of SQL statements are executed with a single call.(Something like similar to your c program calls).

Syntax:

CREATE PROCEDURE  your_procedure_name(parameters list...)

parameters list were those you specify while calling your procedure.Mysql procedure accept three type of parameters IN,OUT,INOUT.

IN-means your procedure accepting an input parameter.
OUT-means your procedure sends a value as a parameter to the calling one.
INOUT-means combination of in,out.

example:

First I will create a table called country to demonstrate procedures.

MySQL>create table country(name varchar(100),id int(40));

now insert some values in the above table.

MySQL>insert into country values('INDIA',1);
 
MySQL>insert into country values('USA',2);
 
MySQL>insert into country values('AUS',3);
 
MySQL>insert into country values('PAK',1);
 
MySQL>insert into country values('UK',1);
 
MySQL>insert into country values('BAN',1);  

lets create a  procedure for retrieving names of country with id 1 by crating procedure.

MySQL>delimiter //
MySQL>

CREATE PROCEDURE  country_procedure(IN cid  int(10))
BEGIN
             select name from country where id=cid;
END  //
MySQL>delimiter ;
Now call the procedure....
MySQL>call country_procedure(1);
****************
    INDIA                  
    PAK                     
    UK                       
    BAN                     
*****************


 

Thứ Bảy, 6 tháng 9, 2014

Write a recursive method to get the multiplication of two numbers such that there are minimum number of addition operations.....

Solution..


package com.shashikumar.com;

public class multiplication {
    public static void main(String []args)
    {
       
       
multiplication t=new multiplication();
        int a=10,b=88;//should give 880 when we multiply.
        System.out.print(t.multiply(a,b));
       
       
    }
    public  int multiply(int x,int y)
    {
        if(y==1)
            return x;
        else
            return (sumNumbers(x,y));
       
    }
    public  int sumNumbers(int m,int n)
    {
   
        if(n==1)
            return m;
        else
           
            return m+sumNumbers(m,n-1);
           
    }

}

output:
---------------------------
880

Thứ Sáu, 5 tháng 9, 2014

Creating custom tags in jsp.

custom tag means user defined tags.JSP allows you to define your own tags .

To create your own tags You have to create three things
1.A java class
2..tld file
3.a simple jsp file to access information

I will Crate a simple jsp tag that give simple information like who created that tag.
note:
In order to create custom tags definition in java class you have to extend or implement some interfaces/classes of javax.servlet.jsp.tagext.* package.

1.customTag.java

This class will implement SimpleTagSupport class of  javax.servlet.jsp.tagext.* package

package com.shashikumar;
import java.io.IOException;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
public class customTag extends SimpleTagSupport {

   
    public void doTag() throws JspException, IOException {
        JspWriter writer=getJspContext().getOut();
        writer.print("This is a custom tag defined by shashikumar .l");
    }


}


In above doTag() is a overloaded method of SimpleTagSupport class.







2.Message.tlb



<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>My first custom tag</short-name>
<tag>
<name>MyMsg</name>
<tag-class>com.shashikumar.customTag</tag-class>>
<body-content>empty</body-content>
</tag>

</taglib>

3.custom.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@taglib prefix="my" uri="WEB-INF/Message.tld" %>
   
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hi custom tag</title>
</head>
<body>
<my:MyMsg/>


</body>
</html>


output: