Sunday, December 15, 2013

Programming Challenges Question 4

Programming Challenges Question 

Write a program to calculate the distance travelled by a car at different time intervals. The initial velocity of the car is 36 km/hr and the constant acceleration is 5 m/s2. 
The formula to calculate distance is:
Distance Travelled = u*t+((a*t*t)/2) 
where,
u = initial velocity of the car (36 km/hr)
a = acceleration of the car (5 m/s2)

t = time duration in seconds

The program should accept 2 time intervals as the input (one time interval per line) and print the distance traveled in meters by the car (one output per line). Definitions:
1 kilometer = 1000 meters
1 hour = 3600 seconds

Let us suppose following are the inputs supplied to the program
10
8
Then the output of the program will be
350
240

/*************************Code in JAVA**********************************/
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {

int firstValue;
int secondValue;
   Scanner in = new Scanner(System.in);
    firstValue = in.nextInt();
 secondValue = in.nextInt();
 calculateDistance(firstValue,secondValue);
 }
    public static void calculateDistance(int t1,int t2){
int u = 10; // in m/s
int a = 5; // in m/s2
int distanceTravel1 = u*t1+((a*t1*t1)/2);
int distanceTravel2 = u*t2+((a*t2*t2)/2);
System.err.println(distanceTravel1);
System.err.println(distanceTravel2);
}
}

Programming Challenges Question 5

Programming Challenges Question 

Gen is an event organizer. He has received data regarding the participation of employees in two different events. 
Some employees have participated in only one event and others have participated in both events. Gen now needs to count the number of employees who have taken part in both events. The records received by Gen consist of employee ids, which are unique. 

Write a program that accepts the employee ids participating in each event (the first line relates to the first event and the second line relates to the second event). The program should print the number of common employee ids in both the events.

Suppose the following input is given to the program, where each line represents a different event:
1001,1002,1003,1004,1005
1106,1008,1005,1003,1016,1017,1112

Now the common employee ids are 1003 and 1005, so the program should give the output as:
2

/************************************************Code in JAVA********************************************************/
import java.io.*;
public class Main {
    public static void main(String[] args) {
    try{
       String data[]= new String[2];
       InputStreamReader sr= new InputStreamReader(System.in);
       BufferedReader br= new BufferedReader(sr);
       for(int i=0;i<2;i++)
       {
         data[i]=br.readLine();
       }

         String EventOneIds[]=data[0].split(",");
         String EventTwoIds[]=data[1].split(",");
         int totalCommonIds=0;
         for(int i=0;i<EventOneIds.length;i++)
         {
             for(int j=0;j<EventTwoIds.length;j++)
             {
                 if(EventOneIds[i].equals(EventTwoIds[j]))
                     totalCommonIds++;
             }
         }

         System.out.println( totalCommonIds);
        
        }
    catch(Exception ex)
    {
        System.out.println(ex.toString());
    }

 }

}




Programming Challenges Question 6

Programming Challenges Question 

Write a program which will take the year (yyyy) and the numeric sequence of the month (0-11) as its input. 
The program will return the day on which the 28th of that particular month and year falls. The input can consist of two year-month combinations, one combination per line.

The numeric sequence of months is as follows:
0 – Jan
1 – Feb
2 – March
and so on......

The format for supplying the input is:
1999-5
Where 1999 is the year and 5 is the numeric sequence of the month (corresponding to June). The program should display the day on which June 28, 1999 fell, and in this case the output will be MONDAY. 

The output should be displayed in uppercase letters.
Suppose the following INPUT sequence is given to the program:
1999-5
1998-6
Then the output should be:
MONDAY
TUESDAY

/****************************Code in JAVA*************************************/
import java.io.*;
import java.text.DateFormatSymbols;
import java.util.*;

public class Main {
    public static void main(String[] args) {
    try{
       String data[]= new String[2];
       InputStreamReader sr= new InputStreamReader(System.in);
       BufferedReader br= new BufferedReader(sr);
       for(int i=0;i<2;i++)
       {
         data[i]=br.readLine();
         Calendar cal=Calendar.getInstance();
         cal.set(Integer.parseInt(data[i].split("-")[0]), Integer.parseInt(data[i].split("-")[1]), 28);
         String dayName = new DateFormatSymbols().getWeekdays()[cal.get(Calendar.DAY_OF_WEEK)];
         System.out.println(dayName.toUpperCase());
        }
        }
    catch(Exception ex)
    {
        System.out.println(ex.toString());
    }

 }
}




Programming Challenges Question 7

Programming Challenges Question 
Write a program that accepts 10 student records (roll number and score) and prints them in decreasing order of scores. In case there are multiple records pertaining to the same student, the program should choose a single record containing the highest score. The program should be capable of accepting a multi-line input. Each subsequent line of input will contain a student record, that is, a roll number and a score (separated by a hyphen). The output should consist of the combination of roll number and corresponding score in decreasing order of score.

INPUT to program

1001-40
1002-50
1003-60
1002-80
1005-35
1005-55
1007-68
1009-99
1009-10
1004-89

OUTPUT from program

1009-99
1004-89
1002-80
1007-68
1003-60
1005-55
1001-40

Solution

//******************************Code in JAVA*************************************//
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) {
       String Data[]= new String[10];
       int splitData[][]= new int[10][2];

       InputStreamReader sr= new InputStreamReader(System.in);
       BufferedReader br= new BufferedReader(sr) ;
       try{
          for(int i=0;i<10;i++)
          {
           Data[i]=br.readLine();
           String str[]= Data[i].split("-");
           splitData[i][0]=Integer.parseInt(str[1]);
           splitData[i][1]=Integer.parseInt(str[0]);
          }

     Arrays.sort(splitData, new Comparator<int[]>() {
            public int compare(int[] o1, int[] o2) {
            return o2[0] - o1[0];
        }
    });

         Byte flag=0;  
          for(int i=0;i<10;i++)
          {
            flag=0;
            for(int j=i-1;j>=0;j--)
            {
                if(splitData[i][1]==splitData[j][1])
                {
                  flag=1;
                   break;
                }
            }
            if(flag==1)
                continue;
            else
                System.out.println(splitData[i][1]+"-"+splitData[i][0]);
}
      }
      catch(Exception ex)
      {
          System.out.println(ex.toString());
      }
     
      }

}


Thursday, September 26, 2013

MultiThreaded Chat Server in java

Chat Server with GUI
we can chat with in a network , public and private chat, also can transfer file on network.
run server file first , after that Client file.
change IP Address before use.



you can download source code , freely mail or comment any help.



Saturday, December 15, 2012

Socket Programming in JAVA


Whats a socket?

Every computer on a network has an IP address. This address is   like your house address, something that identifies your   computer uniquely, allowing others  to communicate with your  computer. I wont go much into IP addresses, but let me  just tell you that  an IP 
address looks something like this - 64.104.137.158  a set of  numbers separated with dots.

However, some computers with rich owners will also choose to  have a domain name in addition to this sick looking number, so  that people can easily identify them. 

A domain name looks far more sane - like www.yahoo.com.There  are some special computer  on the Internet, whose sole purpose  in life is to translate the domain name to IP address and vice  versa

 An IP address = uniquely identifies a computer on the network.
 A port number = uniquely identifies a program running on a computer.
 An IP address + A port number = SOCKET

a socket is a combination of an IP address and a port. A socket address lets other computers on the network locate a  certain program running on a certain computer. You may represent a socket address  like 64.104.137.58:80, where 64.104.137.58 is the IP address and 80 is the port number.

Setps For Program

1: One Java program will try to connect to another Java program. 
   Lets call the  first program   
                   as Client, 
   and the second 
                   as   Server.
 
2: Once connected, the client program is going to accept whatever you type,  and send it 
    dutifully to the server program.
 
3: The server is going to send back the same text to the client, just to show  that it is least 
    interested in doing such an uninteresting thing.
 
 Create 2 fresh Java programs and call them Server.java and Client.java. 

Server.java
import java.net.*;
import java.io.*; 
public class Server
public static void main(String[] ar) 
 int port = 6666; // just a random port.  
 try 
   ServerSocket ss = new ServerSocket(port); // create a server socket and bind 
   System.out.println("Waiting for a client..."); 
   Socket socket = ss.accept(); // make the server listen for a connection     
   System.out.println("Client Recived."); 
   System.out.println();  /* Get the input and output streams of the socket, so that you can receive and send data to the client.*/ 
 
   InputStream sin = socket.getInputStream();
   OutputStream sout = socket.getOutputStream();  /*Just converting them to different streams, so that string handling becomes   easier.*/  
   DataInputStream in = new DataInputStream(sin); 
   DataOutputStream out = new DataOutputStream(sout);
   String line = null; 
   while(true)
   { 
    line = in.readUTF(); // wait for the client to send a line of text.
    System.out.println("Data from Client: " + line);
    System.out.println("I'm sending it back...");
    out.writeUTF(line); // send the same line back to the client. 
    out.flush(); //flush the stream .  
    System.out.println("Waiting for the next line..."); 
    System.out.println(); 
   }
  } 
  catch(Exception x)
  { 
  x.printStackTrace(); 
   }
 }
} 

Client.java
  
import java.net.*;
import java.io.*;
public class Client 
{
public static void main(String[] ar)
 {
 int serverPort = 6666; // make sure you give the port number on which the server is listening.
 String address = "127.0.0.1"; // this is the IP address of the server program's computer. 
 try 
{
 InetAddress ipAddress = InetAddress.getByName(address); // create an object that represents the above IP address.
 System.out.println("a socket with IP address " + address + " and port " + serverPort + "?");
 Socket socket = new Socket(ipAddress, serverPort); // create a socket with the server's IP address and server's port.
 System.out.println("----Connect-----");
 /* Get the input and output streams of the socket, so that you can receive and send data to the client*/
 InputStream sin = socket.getInputStream();
 OutputStream sout = socket.getOutputStream();
 // Just converting them to different streams, so that string handling becomes easier.
 DataInputStream in = new DataInputStream(sin);
 DataOutputStream out = new DataOutputStream(sout);
 // Create a stream to read from the keyboard.
 BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
 String line = null;
 System.out.println("Type in something and press enter. ");
 System.out.println();
 while(true)
 {
 line = keyboard.readLine(); // wait for the user to type in something and press enter.
 System.out.println("Sending this line to the server...");
 out.writeUTF(line); // send the above line to the server.
 out.flush(); // flush the stream to ensure that the data reaches the other end.
 line = in.readUTF(); // wait for the server to send a line of text.
 System.out.println("The server was very polite. It sent me this : " + line);
 System.out.println("Looks like the server is pleased with us. Go ahead and enter more lines.");
 System.out.println();
 }
 } catch(Exception x) {
 x.printStackTrace();
 }
 }
 }
 Compile it with 
  javac Server.java Client.java
  
Open two command windows (DOS prompts). In one of those, enter
                java Server
and in the other,
                java Client