Thursday 25 August 2016

Dequeue in java

import java.util.*;

public class test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Deque<Integer> deque = new ArrayDeque<>();
        HashSet<Integer> set = new HashSet<>();
       
        int n = in.nextInt();
        int m = in.nextInt();
        int max = Integer.MIN_VALUE;

        for (int i = 0; i < n; i++) {
            int input = in.nextInt();
           
            deque.add(input);
            set.add(input);
           
            if (deque.size() == m) {
                if (set.size() > max) max = set.size();
                int first = deque.remove();
                if (!deque.contains(first)) set.remove(first);
            }
        }
       
        System.out.println(max);
    }
}
Sample Input
6 3
5 3 5 2 3 2
Sample Output
3

java sorting student name and CGPA

import java.util.*;

class Student implements Comparable{
    private int id;
    private String fname;
    private double cgpa;
    public Student(int id, String fname, double cgpa) {
        super();
        this.id = id;
        this.fname = fname;
        this.cgpa = cgpa;
    }
    public int getId() {
        return id;
    }
    public String getFname() {
        return fname;
    }
    public double getCgpa() {
        return cgpa;
    }
    public int compareTo(Object o){
        Student s=(Student)o;
        if(cgpa==s.cgpa){
            if(fname.equals(s.fname)){
                return id-s.id;
            }else{
                return fname.compareTo(s.fname);
            }
        }else{
            if(s.cgpa-cgpa>0)
                return 1;
            else
                return -1;
        }
    }

}


//Complete the code
public class Solution
{
   public static void main(String[] args){
      Scanner in = new Scanner(System.in);
      int testCases = Integer.parseInt(in.nextLine());

      List<Student> studentList = new ArrayList<Student>();
      while(testCases>0){
         int id = in.nextInt();
         String fname = in.next();
         double cgpa = in.nextDouble();

         Student st = new Student(id, fname, cgpa);
         studentList.add(st);

         testCases--;
      }
      Collections.sort(studentList);
         for(Student st: studentList){
         System.out.println(st.getFname());
      }
   }
}
Sample Input
5
33 Rumpa 3.68
85 Ashis 3.85
56 Samiha 3.75
19 Samara 3.75
22 Fahim 3.76
Sample Output
Ashis
Fahim
Samara
Samiha
Rumpa

Java program to accept the date and print the week name

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    String month = in.next();
    String day = in.next();
    String year = in.next();

    Calendar calendar = Calendar.getInstance();
    calendar.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));

    String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US);

    System.out.print(dayOfWeek.toUpperCase());

}
}
Sample Input
08 05 2015
Sample Output
WEDNESDAY

Java program to read N lines of input until you reach EOF

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
   static String s;
    static int a=1;
    // For loop
public static void main(String[] args) {
   Scanner scan = new Scanner(System.in);
   for(int i = 1; scan.hasNext()== true; i++){
       System.out.println(i + " " + scan.nextLine());
   }
}

}

Java program to rad elements in to an array and display in reverse order

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


public class Solution {

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in); // Scanner Input from the user
    int n = in.nextInt();   // SizeOfArray
    int[] arr = new int[n]; // initializing a variable(arr) for the array

    // get value from the user and load into the array[]
    for(int i=0; i < n; i++){  
        arr[i] = in.nextInt();
    }

    // declaring the reverse method for the "arr"
    reverse(arr);

    // for loop to print the values of array in reverse
    for(int i = 0; i < n; i++){
            System.out.printf("%d" + " ", arr[i]);
        }

 }//in.close(); /*I purposely hid this Scanner closing() to acquire the desired output, anyone have an idea to get the output without hiding the closing() plz assist me*/

    // the reverse method to swap the values inside the array

    public static void reverse(int[] arr){

        // this loop is necessary if you want to swap the values inside an array
        for(int i=0;i<arr.length/2;i++)
            {
                int temp=arr[i];
                arr[i]=arr[(arr.length-1)-i];
                arr[(arr.length-1)-i]=temp;
            }
    }
}

Tuesday 23 August 2016

Java program to find Mean Median Mode

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class Solution {
public static double findMean(double array[]){
double sum = 0;
double average=0;
double length=array.length;
for(int j = 0; j < length; j++){
sum += array[j];
average = sum / length;
}
return average;
}
public static double findMedian(double array[]) {
int length=array.length;
double[] sort = new double[length];
System.arraycopy(array, 0, sort, 0, sort.length);
Arrays.sort(sort);
if (length % 2 == 0) {
return (sort[(sort.length / 2) - 1] + sort[sort.length / 2]) / 2;
} else {
return sort[sort.length / 2];
}
}

public static double findMode(double array[]) {
int length=array.length;
double[] sort = new double[length];
System.arraycopy(array, 0, sort, 0, sort.length);
Arrays.sort(sort);
double min=sort[0];
return min;
    }
public static void main(String[] args)
{
Scanner nums = new Scanner(System.in);
    int n=nums.nextInt();
double[] num = new double[n];
for ( int i = 0; i <n ; i++) {
  num[i] = nums.nextDouble();
}
double mean=Solution.findMean(num);
System.out.println(+mean);
double median=Solution.findMedian(num);
System.out.println(+median);
double mode=Solution.findMode(num);
System.out.println(+(int)mode);
}
}

OUTPUT:-


Monday 22 August 2016

Class Vs Instance

Task
Write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. The constructor must assign initialAge to age after confirming the argument passed as initialAge is not negative; if a negative argument is passed as initialAge, the constructor should set age to 0 and print Age is not valid, setting age to 0. In addition, you must write the following instance methods:

yearPasses() should increases the age instance variable by 11.
amIOld() should perform the following conditional actions:
If age<13, print You are young.You are young.
If age≥13 and age<18, print You are a teenager.
Otherwise, print You are old.
To help you learn by example and complete this challenge, much of the code is provided for you, but you’ll be writing everything in the future. The code that creates each instance of your Person class is in the main method. Don’t worry if you don’t understand it all quite yet!

Note: Do not remove or alter the stub code in the editor.

Input Format

Input is handled for you by the stub code in the editor.

The first line contains an integer, T (the number of test cases), and the T subsequent lines each contain an integer denoting the age of a Person instance.

Constraints

1≤T≤4
−5≤age≤30
Output Format

Complete the method definitions provided in the editor so they meet the specifications outlined above; the code to test your work is already in the editor. If your methods are implemented correctly, each test case will print 2 or 3 lines (depending on whether or not a valid initialAge was passed to the constructor).

Sample Input

4
-1
10
16
18
Sample Output

Age is not valid, setting age to 0.
You are young.
You are young.

You are young.
You are a teenager.

You are a teenager.
You are old.

You are old.
You are old.
Explanation

Test Case 0: initialAge=−1
Because initialAge<0, our code must set age to 00 and print the “Age is not valid…” message followed by the young message. Three years pass and age=3, so we print the young message again.

Test Case 1: initialAge=10
Because initialAge<13, our code should print that the person is young. Three years pass and age=13, so we print that the person is now a teenager.

Test Case 2: initialAge=16
Because 13≤initialAge<18, our code should print that the person is a teenager. Three years pass and age=19, so we print that the person is old.

Test Case 3: initialAge=18
Because initialAge≥18, our code should print that the person is old. Three years pass and the person is still old at age=21, so we print the old message again.

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

public class Person {
private int age;

public Person(int initialAge) {
// Add some more code to run some checks on initialAge
if (initialAge <0) {
                     System.out.println("Age is not valid, setting age to 0.");
                     initialAge = 0;
               } else {
                      age = initialAge;
               }
}

public void amIOld() {
// Write code determining if this person’s age is old and print the correct statement:
if (age < 13) {
                     System.out.println("You are young.");
                 }
                else if (age >= 13 && age < 18) {
                         System.out.println("You are a teenager.");
                }
                else {
                         System.out.println("You are old.");
                }

}

public void yearPasses() {
// Increment this person’s age.
age++;
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for (int i = 0; i < T; i++) {
int age = sc.nextInt();
Person p = new Person(age);
p.amIOld();
for (int j = 0; j < 3; j++) {
p.yearPasses();
}
p.amIOld();
System.out.println();
        }
sc.close();
    }
}

Saturday 20 August 2016

Operators example-meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal’s total cost.

Task
Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent (the percentage of the meal price being added as tax) for a meal, find and print the meal’s total cost.

Note: Be sure to use precise values for your calculations, or you may end up with an incorrectly rounded result!

Input Format

There are 33 lines of numeric input:
The first line has a double, mealCost (the cost of the meal before tax and tip).
The second line has an integer, tipPercent (the percentage of mealCost being added as tip).
The third line has an integer, taxPercent (the percentage of mealCost being added as tax).

Output Format

Print The total meal cost is totalCost dollars.The total meal cost is totalCost dollars., where totalCost is the rounded integer result of the entire bill (mealCost with added tax and tip).

Sample Input

12.00
20
8

Sample Output

The total meal cost is 15 dollars.

Explanation

Given:
mealCost=12, tipPercent=20, taxPercent=8

Calculations:
tip=12×20100=2.4
tax=12×8100=0.96
totalCost=mealCost+tip+tax=12+2.4+0.96=15.36
round(totalCost)=15

We round totalCost to the nearest dollar (integer) and then print our result:

The total meal cost is 15 dollars.

SOLUTION:

    import java.io.*;
    import java.util.*;
    import java.text.*;
    import java.math.*;
    import java.util.regex.*;
    public class Arithmetic {
    public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    double mealCost = scan.nextDouble(); // original meal price
    int tipPercent = scan.nextInt(); // tip percentage
    int taxPercent = scan.nextInt(); // tax percentage
    scan.close();

    // Write your calculation code here.
    double tip = mealCost * ((double)tipPercent / 100);
    double tax = mealCost * ((double)taxPercent / 100);
    double tot = mealCost + tip + tax;
    // cast the result of the rounding operation to an int and save it as totalCost
    int totalCost = (int) Math.round(tot);

    // Print your result
    System.out.println(“The total meal cost is ” + totalCost + ” dollars.”);
    }
    }

Friday 19 August 2016

Print the sum of i plus your int variable on a new line. Print the sum of d plus your double variable to a scale of one decimal place on a new line. Concatenate s with the string you read as input and print the result on a new line

Task
Complete the code in the editor below. The variables i, d, and s are already declared and initialized for you. You must declare 3 variables: one of type int, one of type double, and one of type String. Then you must read 3 lines of input from stdin and initialize your 3 variables. Finally, you must use the ++ operator to perform the following operations:

Print the sum of i plus your int variable on a new line.
Print the sum of d plus your double variable to a scale of one decimal place on a new line.
Concatenate s with the string you read as input and print the result on a new line.
Note: If you are using a language that doesn’t support using ++ for string concatenation (e.g.: CC), you can just print one variable immediately following the other on the same line. The string provided in your editor must be printed first, immediately followed by the string you read as input.

Input Format

The first line contains an integer, i.
The second line contains a double, d.
The third line contains a string, s.

Output Format

Print the sum of both integers on the first line, the sum of both doubles on the second line, and then the two concatenated strings on the third line.

Sample Input

12
4.0
is the best place to learn and practice coding!
Sample Output

16
8.0
HackerRank is the best place to learn and practice coding!
SOLUTION:

import java.util.*;
public class Solution {
public static void main(String[] args) {
int i = 4;
double d = 4.0;
String s = “HackerRank “;

Scanner scan = new Scanner(System.in);
/* Declare second integer, double, and String variables. */
/* Read and save an integer, double, and String to your variables.*/
int i2 = scan.nextInt();
double d2 = scan.nextDouble();
scan.nextLine(); // read the rest of the line of input (newline character after the double token).
String s2 = scan.nextLine();

/* Print the sum of both integer variables on a new line. */
System.out.println(i + i2);

/* Print the sum of the double variables on a new line. */
System.out.println(d + d2);

/* Concatenate and print the String variables on a new line integer variables on a new line;
the ‘string` variable above should be printed first. */
System.out.println(s + s2);

scan.close();
}
}

Thursday 18 August 2016

Even Tree

 You are given a tree (a simple connected graph with no cycles).You have to remove as many edges from the tree as possible to obtain a forest with the condition that : Each connected component of the forest contains even number of vertices
Your task is to calculate the number of removed edges in such a forest.

Input:
The first line of input contains two integers N and M. N is the number of vertices and M is the number of edges. 2 <= N <= 100.
Next M lines contains two integers ui and vi which specifies an edge of the tree. (1-based index)

Output:
Print a single integer which is the answer
Sample Input 
10 9
2 1
3 1
4 3
5 2
6 1
7 2
8 6
9 8
10 8
 
Sample Output :
2
 
import java.util.*;
 public class Solution{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int M = in.nextInt();
        Integer[][] edges = new Integer[M][2];
        for(int i=0;i<M;i++){
            edges[i][0] = in.nextInt();
            edges[i][1] = in.nextInt();
            if(edges[i][0]>edges[i][1]){
                int tmp = edges[i][0];
                edges[i][0] = edges[i][1];
                edges[i][1] = tmp;
            }
        }
        Arrays.sort(edges,new Comparator<Integer[]>(){
            @Override
            public int compare(Integer[] int1, Integer[] int2){
                Integer v1 = int1[0];
                Integer v2 = int2[0];
                return v1.compareTo(v2);
            }
        });
        int[] count = new int[N];
        count[0] = N;
        for(int i=1;i<N;i++){
            ArrayList<Integer> a = new ArrayList<Integer>();
            a.add(i+1);
            int j = 0;
            while(j<a.size()){
                for(int m=j;m<M;m++){
                    if(edges[m][0]==a.get(j)){
                        if(!a.contains(edges[m][1])){
                            a.add(edges[m][1]);
                        }
                    }
                }
                j++;
            }
            count[i] = a.size();
        }
        int remove = 0;
        for(int c:count){
            if(c%2==0)
                remove++;
        }
        System.out.println(remove-1);                  
    }
}

Maximum Sub Array


Given an array of N elements, find the maximum possible sum of a 1. contiguous subarray 2. non-contiguous (not necessarily contiguous) subarray. Empty subarrays should not be considered.

Sample Run

input:
2
6
-1 -2 -3 -4 -5 -6
8
1 -16 15 23 -53 75 80 -24
output:
-1 -1
155 194

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
   
    //standard max function
    static int max(int x, int y) { return (y > x) ? y : x; }
   
    //modified version of Kadane's algorithm
    static int maxSubarrayContiguous(int[] arr, int indexMax) {
        //takes in first value just so it has _something_
        int maxSoFar = arr[0];
        int currMax = arr[0];
       
           for (int i = 1; i < indexMax; i++) {
                currMax = max(arr[i], currMax + arr[i]);
                maxSoFar = max(maxSoFar, currMax);
           }
           return maxSoFar;
        }
   
    static int maxSubarrayNonContiguous(int[] arr, int indexMax) {
        int sumMax = 0;
        int max = arr[0];
        boolean negArray = true;
        int res = 0;
        for (int i = 0; i < indexMax; i++) {
            //add all positive numbers
            if (arr[i] >= 0) {
                sumMax += arr[i];
                negArray = false;
            }
            //find the smallest negative number
            if (arr[i] >= max) { max = arr[i];}
        }
   
        if (negArray == false)
            res = sumMax;
        //if the array consists of all negative numbers
        //return the smallest number
        if (negArray)
            res = max;
       
        return res;
       
    }
   

    public static void main(String[] args) {
       
        Scanner in = new Scanner(System.in);
        //array to store continous solutions
        int[] testSolutionsC = new int[10];
        //array to store non-continuous
        int[] testSolutionsNC = new int[10];
        int resC;
        int resNC;
        int runs;
        runs = Integer.parseInt(in.nextLine());
       
        //go through the amount of solutions
        for (int i = 0; i < runs; i++) {
            String inputString;
            int[] arr = new int[100000];
            int indexMax = Integer.parseInt(in.nextLine());
           
            //tokenize input values;
            //all entries are separated by a space
            inputString = in.nextLine();
            int arrIndex=0;
            StringTokenizer st = new StringTokenizer(inputString);
            while(st.hasMoreTokens()) {
                arr[arrIndex] = Integer.parseInt(st.nextToken());
                arrIndex++;
            }
           
            //continuous solution
            resC = maxSubarrayContiguous(arr, indexMax);
            //non-continuous solution
            resNC = maxSubarrayNonContiguous(arr, indexMax);
           
            //add continuous solutions to array
            testSolutionsC[i] = resC;
            //add non-continuous solutions to array
            testSolutionsNC[i] = resNC;
           
        }
       
        //print out entries
        for(int i = 0; i < runs; i++) {
            System.out.print(testSolutionsC[i] + " ");
            System.out.print(testSolutionsNC[i]);
            System.out.println();
        }
       
    }
}

Fibonacci Modified

Problem Statement
A series is defined in the following manner:
Given the nth and (n+1)th terms, the (n+2)th can be computed by the following relation
Tn+2 = (Tn+1)2 + Tn

So, if the first two terms of the series are 0 and 1:
the third term = 12 + 0 = 1
fourth term = 12 + 1 = 2
fifth term = 22 + 1 = 5
… And so on.

Given three integers A, B and N, such that the first two terms of the series (1st and 2nd terms) are A and B respectively, compute the Nth term of the series.
Input Format
You are given three space separated integers A, B and N on one line.
Input Constraints
0 <= A,B <= 2
3 <= N <= 20

Output Format
One integer.
This integer is the Nth term of the given series when the first two terms are A and B respectively.
Note
    Some output may even exceed the range of 64 bit integer.
Sample Input
0 1 5 

Sample Output
5

Explanation
The first two terms of the series are 0 and 1. The fifth term is 5. How we arrive at the fifth term, is explained step by step in the introductory sections.
Solution
 
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        int i,n;
        BigInteger a,b;
        Scanner sc=new Scanner(System.in);
        a =  sc.nextBigInteger();
        b =  sc.nextBigInteger();
        n = sc.nextInt();
        BigInteger [] val = new BigInteger[n];
        val[0] = a;
        val[1] = b;
        for(i=2;i<n;i++){
            val[i]= (val[i-1].pow(2)).add(val[i-2]);
        }
        System.out.println(val[i-1]);
   
    }
}

Kaprekar number

A Kaprekar number is a positive whole number n with d digits, such that when we split its square into two pieces - a right hand piece r with d digits and a left hand piece l that contains the remaining d or d−1 digits, the sum of the pieces is equal to the original number (i.e. l + r = n). The Task You are given the two positive integers p and q, where p is lower than q. Write a program to determine how many Kaprekar numbers are there in the range between p and q (both inclusive) and display them all.
Input Format
There will be two lines of input: p, lowest value q, highest value

Constraints:
0<p<q<100000

Output Format
Output each Kaprekar number in the given range, space-separated on a single line. If no Kaprekar numbers exist in the given range, print INVALID RANGE.
22223
99999
In the above range the follwoing numbers should have been generated :-
77778 82656 95121 99999

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

public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner scan = new Scanner(System.in);
        int p = scan.nextInt();
        int q = scan.nextInt();
        boolean exist = false;
        if(q <= p){
            System.out.println("INVALID RANGE");
            return;
        }
        int m = 0,n = 0;
        long sqr = 0;
        String numb = "";
        String[] digits = new String[2];
        for(long i = p; i <= q; i++){
            if(i == 1)System.out.print(1 + " ");
            else{
            sqr = i*i;
            numb = String.valueOf(sqr);
            if(numb.length() % 2 == 0){
                digits[0] = numb.substring(0, numb.length()/2);
                digits[1] = numb.substring(numb.length()/2);
            }else{
                digits[0] = numb.substring(0, (numb.length() - 1)/2);
                digits[1] = numb.substring((numb.length() -1)/2);
            }
              if(digits[0] == "" )
                  m = 0;
              if(digits[1] == "")
                  n = 0;
              if(!digits[1].equals("") && !digits[0].equals("")){
              m = Integer.parseInt(digits[0]);
              n = Integer.parseInt(digits[1]);
              } 
            if(i == (m + n) ){
                System.out.print(i + " ");
                exist = true;
            }
        }
      }
        if(exist == false){
            System.out.println("INVALID RANGE");
        }
    }
}

Taum Bday White Gift and Black Gift Problem

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

public class TaumAndBday {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
       
        Scanner sc = new Scanner(System.in);
        int numCases = sc.nextInt();
     
        for(int i = 0;i<numCases;i++){
            // have to use long because of the contraints which will not fit in int
            long numBlackGifts = sc.nextLong();
            long  numWhiteGifts = sc.nextLong();
            long  costBlackGift = sc.nextLong();
            long  costWhiteGift = sc.nextLong();
            long  conversionCost = sc.nextLong();
            long price = 0;
            if((costWhiteGift+conversionCost)<costBlackGift){
                price = (costWhiteGift+conversionCost)*numBlackGifts + (numWhiteGifts*costWhiteGift);
            }else if ((costBlackGift+conversionCost) < costWhiteGift){
                price = ((costBlackGift + conversionCost) * numWhiteGifts) + (numBlackGifts*costBlackGift);
            }else{
                price = (costBlackGift * numBlackGifts) + (costWhiteGift * numWhiteGifts);
            }
            System.out.println(price);
        }
    }
}

hours and minutes in words

Given a time in numbers we can convert it into words. For example :
5 : 00 ——  five o’clock
5 : 10 ——  ten minutes past five
5 : 15 ——  quarter past five
5 : 30 ——  half past five
5 : 40 ——  twenty minutes to six
5 : 45 ——  quarter to six
5 : 47 ——  thirteen minutes to six
Write a program which first inputs two integers, the first between 1 and 12 (both inclusive) and second between 0 and 59 (both inclusive) and then prints out the time they represent, in words.
Your program should follow the format of the examples above.
SAMPLE DATA :

1. INPUT :
TIME : 3,0
OUTPUT : 3 : 00 Three o’ clock
2. INPUT :
TIME : 7,29
OUTPUT : 7 : 29 Twenty nine minutes past seven
3. INPUT :
TIME : 6,34
OUTPUT : 6 : 34 Twenty six minutes to seven
4. INPUT :
TIME : 12,1
OUTPUT : 12 : 01 One minute past Twelve
5. INPUT :
TIME : 12,45
OUTPUT : 12 : 45 Quarter to One
6. INPUT :
TIME : 10,59
OUTPUT : 10 : 59 One minute to Eleven
7. INPUT :
TIME : 14,60
OUTPUT : Incorrect Input
Test your program for the data values given in the examples above and some random data.

 PROGRAM:-
 import java.io.*;
public class TimeInWords

    public static void main(String args[])throws IOException
    { 
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       
        /* Inputting hours and minutes */
        System.out.print("Enter Hours : ");
        int h=Integer.parseInt(br.readLine());
        System.out.print("Enter Minutes : ");
        int m=Integer.parseInt(br.readLine());
       
        if((h>=1 && h<=12) && (m>=0 && m<=59)) // checking whether given input is legal or not.
        {
         /* creating an array containing numbers from 1-29 in words */

        String words[]={"", "One", "Two", "Three", "Four", "Five", "Six","Seven", "Eight", "Nine","Ten",
        "Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen",
        "Twenty","Twenty one", "Twenty two", "Twenty three", "Twenty four", "Twenty five",
        "Twenty six","Twenty seven","Twenty eight", "Twenty nine"};
        
         /* The below code is for finding whether to print the word 'minute' or 'minutes' */
         String plu, a;
         if(m == 1 || m == 59)
            plu = "Minute";
         else
            plu = "Minutes";
        
         /* When we have minutes from 31-59, we print the hour ahead of the given hour
          * like 6:55 will be 5 minutes to 7 and not 5 minutes to 6
          * when we print the hour ahead of the given hour, we face a problem at hour = 12
          * because if we print an hour ahead of 12, it will be thirteen, but we want 1
          * so the below code checks this & decides what hour to print in words when minutes is from 31-59
          */
         if(h==12)
            a = words[1]; //storing 'one' when hour is 12
         else
            a = words[h+1]; //if hour is not 12, then storing in words, an hour ahead of given hour
           
        /* The below code checks minutes and accordingly prints the time in words using array. */
         System.out.print("Output : "+h+":"+m+" ----- "); //printing the given time in numbers

         if(m==0)
            System.out.println(words[h]+" O' clock");
         else if(m==15)
            System.out.println("Quarter past "+words[h]);
         else if(m==30)
            System.out.println("Half past "+words[h]);
         else if(m==45)
            System.out.println("Quarter to "+a);
         else if(m<30) // condition for minutes between 1-29
            System.out.println(words[m]+" "+plu+" past "+words[h]);
         else // condition for minutes between 31-59
            System.out.println(words[60-m]+" "+plu+" to "+a);
        } //end of outer if

        else
            System.out.println("Invalid Input !"); //printing error message for illegal input
    }
}

Enter Hours : 7
Enter Minutes : 16
Output : 7:16 —– Sixteen Minutes past Seven

BigInteger factorial


Problem Statement
You are given an integer N. Print the factorial of this number.
N!=N×(N−1)×(N−2)×⋯×3×2×1

Note: Factorials of N>20 can't be stored even in a 64−bit long long variable. Big integers must be used for such calculations. Languages like Java, Python, Ruby etc. can handle big integers but we need to write additional code in C/C++ to handle such large values.
We recommend solving this challenge using BigIntegers.
Input Format
Input consists of a single integer N.

Output Format
Output the factorial of N.
Sample Input

25

Sample Output

15511210043330985984000000

 PROGRAM:-
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution
{
      public static void main(String[] args)
     {
           Scanner scn=new Scanner(System.in);
           int n=scn.nextInt();
           BigInteger factorial= BigInteger.ONE;  
           for (int i = 2; i <= n; i++)
           {
 
                 factorial = factorial.multiply(new BigInteger(String.valueOf(i)));

            }
            System.out.println(factorial);
    }
}

Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics. pick 2 people out of N people

ACM ICPC Team:-
Problem Statement
You are given a list of N people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics.
// pick 2 people out of N people

Input Format
The first line contains two integers N and M separated by a single space, where N represents the number of people, and M represents the number of topics. N lines follow.
Each line contains a binary string of length M. In this string, 1 indicates that the ith person knows a particular topic, and 0 indicates that the ith person does not know the topic.
//N people , M topic

Output Format
On the first line, print the maximum number of topics a 2-person team can know.
On the second line, print the number of 2-person teams that can know the maximum number of topics.
// condiser each topic's character array AS a binary or integer
// then screen all combination by taking "OR" operation and find a maximum number of "1" and the team
// to put the result , use a HashMap then put the team number and max count "Map<Integer,Integer>"
// key is to do "OR" operation in given array element.
//1. receive all necessary input parameters
//2. store to character array
//3. convert character array to integer array for "OR" operation
//4. screen all combination but there's no need to concern an order
//5. after 4, check number of "1" value and compare to previous max value if it exceeds or same
//6. iterate above
//7. print max and number of teams value - hashmap size

Constraints
2 ≤ N ≤ 500
1 ≤ M ≤ 500

Sample Input
4 5
10101
11100
11010
00101


Sample Output
5
2


Explanation
(1, 3) and (3, 4) know all the 5 topics. So the maximal topics a 2-person team knows is 5, and only 2 teams can achieve this.
Code


import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class ACMICPC {
    public static void main(String[] args) {
       
        Scanner in = new Scanner(System.in);
       
        //no of people
        int N = in.nextInt();
       
        //no of topic
        int M= in.nextInt();
       
        char[][] t = new char[N][M];
       

        //each pereons's topic data
        for(int i=0;i<N;i++){
            t[i]=in.next().toCharArray();
        }
       
        //convert to int type for "OR" operation
        int [][] p = new int[N][M];
       
        for(int i=0;i<N;i++){
            for(int j=0;j<M;j++){
            p[i][j]=(int)(t[i][j]-'0');
            }
        }
       
        //map for storing teams data
        Map<Integer,Integer> hmap = new HashMap<>();
       
        int count=0;
        int max=0;
       
       
        for(int i=0;i<N;i++){
         //first person
            int[] a=p[i];
            for(int j=i+1;j<N;j++){
             //second person
                int[] b=p[j];
                count=0;
                //"OR" operation and count total number of "1"
                for(int k=0;k<M;k++){
                    if((a[k]|b[k]) ==1)
                        count++;
                }
                //new MAX found , previous max and map data will be removed
                if(count>max){
                    max=count;
                    hmap.clear();
                    hmap.put(i,j);
                //same as max , count
                }else if(count==max){
                    hmap.put(i,j);
                }
            }           
        }
       
        //max number of "OR"
        System.out.println(max);
        //number of team who meet "max"
        System.out.println(hmap.size());
       
    }
}

Thursday 11 August 2016

Vector program in java

import java.io.*;
import java.util.*;
class VectorDemo1
{
public static void main(String args[]) throws IOException
{
Vector v = new Vector( );
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("1.Creation");
System.out.println("2.Insertion");
System.out.println("3.Deletion");
System.out.println("4.Display");
System.out.println("5.exit");
System.out.println("Enter Ur Choice:");
int n=Integer.parseInt(br.readLine());
switch(n)
{
    case 1:    
        System.out.println("Enter the Element:");
        v.addElement(new Integer(br.readLine()));
        break;
    case 2: System.out.println("Enter the position to be inserted:");
        int x=Integer.parseInt(br.readLine());
        System.out.println("Enter the Element:");
        int y=Integer.parseInt(br.readLine());
        v.insertElementAt(y,x);
        break;
    case 3:System.out.println("Enter the position to be deleted:");
        int z=Integer.parseInt(br.readLine());
        v.removeElementAt(z-1);
        break;
    case 4: System.out.println("Elements are:");
        for(int i=0;i<v.size();i++)
        System.out.println(v.get(i)+" ");       
        break;
    case 5:System.exit(0);
}
}
}
}

Illegal Argument Exception throw catch exception in java

class MyClock
{
int hours ,minutes, seconds;
 MyClock(int hours, int minutes, int seconds)
{
if (hours < 1 || hours > 12)
{
throw new IllegalArgumentException("Hours must be between 1 and 12");
}
if (minutes < 0 || minutes > 59)
{
throw new IllegalArgumentException("Minutes must be between 0 and 59");
}
if (seconds < 0 || seconds > 59)
{
throw new IllegalArgumentException("Seconds must be between 0 and 59");
}
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
System.out.println(hours+"hrs:"+minutes+"mins:"+seconds+"sec;");
}
public MyClock(int hours, int minutes)
{
this(hours, minutes, 0);
}
public MyClock(int hours)
{
this(hours, 0, 0);
}
}
public class ThrowTest
{
public static void main( String args [])
{
try
{
MyClock clock = new MyClock(1, 10,20);
MyClock c=new MyClock(1);
MyClock a=new MyClock(2,50,80);
}
catch( IllegalArgumentException e)
{
System.out.println("IllegalArgumentException is caught...."+e.getMessage());
}
}
}

Applet program example in java

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
//<applet code="textinput" width=500 height=300></applet>
public class textinput extends Applet implements ActionListener
{
    Font f=new Font("TimesRoman",Font.BOLD,30);
    TextField t1,t2;
    Button b1;
    Label l1;
    public void init()
    {
        setBackground(Color.pink);
        setForeground(Color.blue);
        t1=new TextField(8);
        t2=new TextField(8);
        b1=new Button("Ok");
        setFont(f);
        l1=new Label("Enter a Number");
        add(l1);
        add(t1);
        add(t2);
        add(b1);
        b1.addActionListener(this);
    }
    public void actionPerformed(ActionEvent ae)
    {
        if(ae.getSource()==b1)
        {
            int n, r,rev=0;
            String s1;
           
            s1=t1.getText();
            n=Integer.parseInt(s1);
            while(n!=0)
            {
                r=n%10;
                rev=rev*10+r;
                n=n/10;
            }
                       
            String x=String.valueOf(rev);
            t2.setText(x);
        }
    }
}

Threads Syncronization in java

class SynchronizeDemo2
{
    public static void main(String args[])
    {
        Shared shared = new Shared();
        CustomThread thread1 = new CustomThread(shared, "one");
        CustomThread thread2 = new CustomThread(shared, "two");
        CustomThread thread3 = new CustomThread(shared, "three");
        CustomThread thread4 = new CustomThread(shared, "four");
        try
        {
            thread1.join();
            thread2.join();
            thread3.join();
            thread4.join();
        }
        catch(InterruptedException e) {}
    }
}

class CustomThread extends Thread
{
    Shared shared;
    public CustomThread(Shared shared, String string)
    {
        super(string);
        this.shared = shared;
        start();
    }
    public void run()
    {
        shared.doWork(Thread.currentThread().getName());
    }
}

class Shared
{
     synchronized void doWork(String string)
    {
        System.out.println("Starting " + string);
        try
        {
            Thread.sleep(1000);
        }
        catch (InterruptedException e) {}
        System.out.println("Ending " + string);
    }
}

Stack operation in java

import java.io.*;
class stack
{
final int max=3;
int a[]=new int[max];
int top=-1;
void push(int x)
{
if(top>=max-1)
System.out.println("Stack over flow");
else
{
top++;
a[top]=x;
}
}
void pop()
{
if(top<0)
System.out.println("Stack under flow");
else
{
System.out.println("deleted item is.."+a[top]);
top--;
}
}
void display()
{
if(top<0)
System.out.println("no elemnets in the stack to display");
else
{
System.out.println("The elements in the stack are..\n");
for(int i=top;i>=0;i--)
{
System.out.println(a[i]);
}
}
}
}
class stackop
{
public static void main(String args[])throws IOException
{
int ch;int x;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
stack st=new stack();
while(true)
{
System.out.println("\n1. Push");
System.out.println("2. POP");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.println("Enter your choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1: System.out.println("Enter the element to be inserted");
    x=Integer.parseInt(br.readLine());
    st.push(x);
    break;
case 2:    st.pop();
    break;
case 3: st.display();
    break;
case 4:System.exit(0);
}
}
}
}

stack using linked list in java

import java.io.*;
class stlin
{
int item;
stlin next;
}
class stack
{
    int i=1;
    stlin start,curr;
    void push(int x)
    {
        curr=new stlin();
        curr.item=x;
        curr.next=start;
        start=curr;
        i++;
       
    }
    void pop()
    {
        if(i==1)
        {
            System.out.println("Stack is empty");
        }
        else
        {
            i--;
            curr=start;
            System.out.println("Deleted Element is:"+curr.item);
            start=start.next;
            curr=null;
        }
               
    }
    void display()
    {
        if(i==1) System.out.println("no elements");
        curr=start;
        while(curr!=null)
        {
            System.out.println(curr.item);
            curr=curr.next;
        }
        System.out.println();
    }
}
class stacklin
{
public static void main(String []args) throws IOException
{
    stack sl=new stack();
    int ch,x;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    while(true)
    {
        System.out.println("1.PUSH");
        System.out.println("2.POP");
        System.out.println("3.SHOW");
        System.out.println("4.EXIT");
        System.out.println("Enter Ur Choice:");
        ch=Integer.parseInt(br.readLine());
        switch(ch)
        {
            case 1: System.out.println("Enter a Number:");               
                x=Integer.parseInt(br.readLine());
                sl.push(x);
                break;
            case 2: sl.pop();
                break;
            case 3: sl.display();
                break;
            case 4: System.exit(0);
        }
    }
}
}

selection sort in java

import java.io.*;
class selectionsort
{
    public static void main(String args[])
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
        int n=0,i,j,t;
        int a[] = new int[10];
        System.out.println("Enter size of the array:");
        try
        {
              n= Integer.parseInt(br.readLine());
        }
        catch(Exception e) { }
        System.out.println("Enter elements into the array:");
        try
        {
             for(i=0;i<n;i++)
                   a[i] = Integer.parseInt(br.readLine());
        }
              catch(Exception e) { }
        i=0;
        while(i<n-1)
        {
        int key=i;
        for(j=i+1;j<n;j++)
        {
            if(a[j]<a[key])
            {
                key=j;
            }
        }
        t=a[key];
        a[key]=a[i];
        a[i]=t;
        i++;
        }
        System.out.println("The sorted array is :");
             for(i=0;i<n;i++)
        System.out.println(a[i]);
         }
}

queue operation in java

import java.io.*;
class queue
{
final int max=3;
int a[]=new int[max];
int F=-1,R=-1;

void insert(int x)
{
if(R==max-1)
System.out.println("insertion is not possible");
else
{
a[R+1]=x;
R++;
}
}

void delete()
{
if(F==R)
System.out.println("deletion is not Possible because Queue Is empty");
else
{
F=F+1;
System.out.println("delete item is .."+a[F]);
}
}

void display()
{
if(F==R)
System.out.println("queue is empty");
else
{
for(int i=F+1;i<=R;i++)
System.out.println(a[i]+"\n");
}
}
}

class queueop
{
public static void main(String args[])throws IOException
{
int ch;int x;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
queue q=new queue();
while(true)
{
System.out.println("\n1. Insertion");
System.out.println("2. Deletion");
System.out.println("3. Display");
System.out.println("4. Exit");
System.out.println("Enter your choice");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1: System.out.println("Enter the element to be inserted");
    x=Integer.parseInt(br.readLine());
    q.insert(x);
    break;
case 2:    q.delete();
    break;
case 3: q.display();
    break;
case 4:System.exit(0);
}
}
}
}

queue using linked list in java

import java.io.*;
class qlin
{
int item;
qlin next;
}
class queue
{
    int i=0;
    qlin first,prev,curr;
    void insert(int x)
    {
        i++;
        if(i==1)
        {
            first=new qlin();
            first.item=x;
            first.next=null;
            prev=first;
        }
        else
        {
            curr=new qlin();
            curr.item=x;
            curr.next=null;
            prev.next=curr;
            prev=curr;

        }
    }
    void delete()
    {
        if(i==0)
        {
            System.out.println("queue is empty");
        }
        else
        {
            i--;
            curr=first;
            System.out.println("Deleted Element="+curr.item);
            first=first.next;
            curr=null;
        }
        System.out.println();
               
    }
    void display()
    {
        curr=first;
        while(curr!=null)
        {
            System.out.println(curr.item);
            curr=curr.next;
        }
        System.out.println();
    }
}
class queuelin
{
public static void main(String []args) throws IOException
{
    queue ql=new queue();
    int ch,x;
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    while(true)
    {
        System.out.println("1.Insert");
        System.out.println("2.Delete");
        System.out.println("3.SHOW");
        System.out.println("4.EXIT");
        System.out.println("Enter Ur Choice:");
        ch=Integer.parseInt(br.readLine());
        switch(ch)
        {
            case 1: System.out.println("Enter a Number:");               
                x=Integer.parseInt(br.readLine());
                ql.insert(x);
                break;
            case 2: ql.delete();
                break;
            case 3: ql.display();
                break;
            case 4: System.exit(0);
        }
    }
}
}

Threads program in java

class y
{
  synchronized void doWork(String string)
{
        System.out.println("Starting " + string);
        try {
            Thread.sleep(1000);
        }
        catch (InterruptedException e) {}
        System.out.println("Ending " + string);
}
}

class X extends Thread
{
y p;
String string2;
public X(y string1,String string2)
{
super(string2);
p=string1;
this.string2=string2;
}
public void run()
{
p.doWork(Thread.currentThread().getName());
}
}

class process
{
public static void main(String args[])
{
y p=new y();
X t1=new X(p,"one");
X t2=new X(p,"two");
X t3 =new X(p,"three");
X t4=new X(p,"four");
X t5=new X(p,"five");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}