Sunday, February 10, 2019

Get 3rd, 4th , 3rd, 4th element from an array


Get elements from an given array based on some index sequence. like in this get 3rd element then 4th, then 3rd then 4th on so on...

public class TeampClass {

public static void main(String[] args) {

char[] A = {'1','2','3','7','4','d','a','w','q','4','2','d','a','w','q','4','2'};
char[] b = new char[A.length];

boolean flag  = false;
int count = 0;
for(int i=0;i<A.length;i++){

if(i==0){
flag = true;
if(i+2 <=A.length){
b[count] = A[i+2];
i +=1;
}
}
else{
if(flag == false){
if(i+2 <A.length){
b[count] = A[i+3];
i +=2;
flag = true;
}
}else{

if(i+4 <A.length){
b[count] = A[i+4];
i +=3;
flag = false;
}
}
}
count++;
}

System.out.println(Arrays.toString(A));
System.out.println(Arrays.toString(b));

}


}


output

[1, 2, 3, 7, 4, d, a, w, q, 4, 2, d, a, w, q, 4, 2]
[3, a, 4, w, 2, ]

Saturday, February 2, 2019

Join Two table data using order by in MYSQL

I have two tables user_detail, department so i want to get the sum of amount from user_detail table base on the department.
Both tables having did column. totalam is the new column for the total amount that will come after adding the amount based on did on user detail.

select  department.department, sum(user_detail.amount) as totalam from user_detail inner join department on department.did=user_detail.did group by department.did,department.department;







Saturday, January 5, 2019

Read Data From A file and Write To Another File Using FileWriter And BufferedWriter In Java

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;





public class FileWriterImpl {

public static void main(String[] args) throws IOException {

File f = new File("readfile.txt");
FileReader reader = new FileReader(f);

File fwr = new File("writefile.txt");
FileWriter fw = new FileWriter(fwr);
BufferedWriter bw = new BufferedWriter(fw);
int ch;
while((ch = reader.read()) != -1) {
bw.write((char)ch);

}
bw.close();
}

}

Friday, December 14, 2018

Rotate String





import java.util.Scanner;

public class RotateString {
    public static void main(String args[] ) throws Exception {
     
        Scanner scn = new Scanner(System.in);
        String s = scn.nextLine();
        String[] strArray = getFilterString(s);
        String[] rotatedString = rotateString(strArray);
        for(int i = 0 ;i<rotatedString.length;i++){
            System.out.println(rotatedString[i]);
        }
    }

    private static String[] getFilterString(String str){
        String [] strTemp = str.split(" ");
        String [] strArr = new String[strTemp.length];

        for(int i = 0;i<strTemp.length;i++){
            String s = strTemp[i];
            boolean flag = false;
            for(int j = 0;j<s.length();j++){
                if(s.charAt(j) == 't'){
                    flag = true;
                }

            }
            if(flag == false){
                strArr[i] = "None";
            }else{
                strArr[i] = s;
            }
        }
        return strArr;
    }

    private static String[] rotateString(String [] str){

        for(int i=0;i<str.length;i++){
            if(!str[i].equals("None")){
                char[] s = str[i].toCharArray();
                int n=2;
                while(n>0){
                char temp = s[0];
                    for(int j=0;j<s.length;j++){
                        if(j>0 && j<s.length){
                            s[j-1]=s[j];
                        }if(j == s.length-1){
                             s[j] = temp;
                        }
                        //System.out.print(s[j]+" ");
                    }
                    n--;
                }
               // System.out.println();
                String charString = new String(s);
                str[i] = charString;
            }
        }


        return str;
    }
}

Saturday, July 28, 2018

LinearSearch In java

public class LinearSearch {

public static void main(String[] args) {

int[] ar = {3,2,45,6,5,4,3,2,3456,5432};

System.out.println(searchN(ar, 5432));
}

static boolean searchN(int[] arr, int n){
boolean result = false;
for(int i = 0;i<arr.length;i++){
if(arr[i] == n){
result = true;
break;
}
}
return result;
}

}

Friday, July 13, 2018

Caesar Cipher

Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar's cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c.

Original alphabet:      abcdefghijklmnopqrstuvwxyz
Alphabet rotated +3:    defghijklmnopqrstuvwxyzabc
Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted.

Input Format

The first line contains the integer, , the length of the unencrypted string.
The second line contains the unencrypted string, .
The third line contains , the number of letters to rotate the alphabet by.

Constraints



 is a valid ASCII string without any spaces.

Output Format

For each test case, print the encoded string.

Sample Input

11
middle-Outz
2
Sample Output

okffng-Qwvb
Explanation

Original alphabet:      abcdefghijklmnopqrstuvwxyz
Alphabet rotated +2:    cdefghijklmnopqrstuvwxyzab

m -> o
i -> k
d -> f
d -> f
l -> n
e -> g
-    -
O -> Q
u -> w
t -> v
z -> b


public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        String s = in.next();
        int k = in.nextInt();
        int m=0;
        int k1=0;
        String s1="";
        if(n>=1 && n<=100)m=n;
        if(s.length()<=n)s1=s;
        if(k>=0 && k<=100)k1=k;
       
        System.out.println(encrypt(s1,k1));
    }
    public static String encrypt(String s, int k){
        String str="";
        char c;
        int size=0;
        for(int i=0;i<s.length();i++){
            size=s.charAt(i);
            k = k%26;
            if(size>=97 && size<=122){
                size += k;
                if(size > 122){
                    size = size%122;
                    size += 96;
                }
                str+=(char)size;
            }else if(size>=65 && size<=90){
                size += k;
                if(size > 90){
                    size = size%90;
                    size += 64;
                }
                str+=(char)size;
            }else{
                str+=s.charAt(i);
            }
            //System.out.println(size+"-"+(char)size);
        }
        return str;
    }
}

Bon Appétit

Anna and Brian are sharing a meal at a restuarant and they agree to split the bill equally. Brian wants to order something that Anna is allergic to though, and they agree that Anna won't pay for that item. Brian gets the check and calculates Anna's portion. You must determine if his calculation is correct.

For example, assume the bill has the following prices: . Anna declines to eat item  which costs . If Brian calculates the bill correctly, Anna will pay . If he includes the cost of , he will calculate . In the second case, he should refund  to Anna.

You are given an array of prices, , the cost of each of the  items, , the item Anna doesn't eat, and , the total amount of money that Brian charged Anna for her portion of the bill. If the bill is fairly split, print Bon Appetit. Otherwise, print the integer amount of money that Brian must refund to Anna.

Input Format

The first line contains two space-separated integers  and , the number of items ordered and the -based index of the item that Anna did not eat.
The second line contains  space-separated integers  where .
The third line contains an integer, , the amount of money that Brian charged Anna for her share of the bill.

Constraints

Output Format

If Brian did not overcharge Anna, print Bon Appetit on a new line; otherwise, print the difference (i.e., ) that Brian must refund to Anna. This will always be an integer.

Sample Input 0

4 1
3 10 2 9
12
Sample Output 0

5
Explanation 0
Anna didn't eat item , but she shared the rest of the items with Brian. The total cost of the shared items is  and, split in half, the cost per person is . Brian charged her  for her portion of the bill. We print the amount Anna was overcharged, , on a new line.

Sample Input 1

4 1
3 10 2 9
7
Sample Output 1

Bon Appetit
Explanation 1
Anna didn't eat item , but she shared the rest of the items with Brian. The total cost of the shared items is  and, split in half, the cost per person is . Because , we print Bon Appetit on a new line.

public class Solution {
    public static void main(String args[] ) throws Exception {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */
        Scanner scn = new Scanner(System.in);
        int totalItems = scn.nextInt();
        int notEaten = scn.nextInt();
        int [] totalItemsArr = new int[totalItems];
       
        for(int i=0;i<totalItems;i++){
            totalItemsArr[i]=scn.nextInt();
        }
        int chargerBill = scn.nextInt();
        int sum = 0;
        int finalSum=0;
       
        for(int i=0;i<totalItems;i++){
            if(i != notEaten){
                sum+=totalItemsArr[i];
            }
        }
        finalSum = sum/2;
       
        if(chargerBill == finalSum){
            System.out.println("Bon Appetit");
        }else{
            System.out.println(chargerBill-finalSum);
        }
       
    }
}

Divisible Sum Pairs

You are given an array of  integers, , and a positive integer, . Find and print the number of  pairs where  and  +  is divisible by .

Input Format

The first line contains  space-separated integers,  and .
The second line contains  space-separated integers describing the values of .

Constraints

Output Format

Print the number of  pairs where  and  +  is evenly divisible by .

Sample Input

6 3
1 3 2 6 1 2
Sample Output

 5
Explanation

Here are the  valid pairs when :


public class Solution {

    static int divisibleSumPairs(int n, int k, int[] ar) {
        int result=0;
        for(int i=0;i<ar.length;i++){
            for(int j=i+1;j<ar.length;j++){
                int sum=ar[i]+ar[j];
                //System.out.println("ar[i]+ar[j] "+ar[i]+"  "+ar[j]+" sum " +sum+" "+ "k- "+k);
                
                if(sum%k==0){
                   // System.out.println("sum%k "+sum%k);
                    result++;
                }
            }
        }return result;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int k = in.nextInt();
        int[] ar = new int[n];
        for(int ar_i = 0; ar_i < n; ar_i++){
            ar[ar_i] = in.nextInt();
        }
        int result = divisibleSumPairs(n, k, ar);
        System.out.println(result);
    }
}

Birthday Chocolate

Lily has a chocolate bar that she wants to share it with Ron for his birthday. Each of the squares has an integer on it. She decides to share a contiguous segment of the bar selected such that the length of the segment matches Ron's birth month and the sum of the integers on the squares is equal to his birth day. You must determine how many ways she can divide the chocolate.

Consider the chocolate bar as an array of squares, . She wants to find segments summing to Ron's birth day,  with a length equalling his birth month, . In this case, there are two segments meeting her criteria: .

Input Format

The first line contains an integer , the number of squares in the chocolate bar.
The second line contains  space-separated integers , the numbers on the chocolate squares where .
The third line contains two space-separated integers,  and , Ron's birth day and his birth month.

Constraints

, where ()
Output Format

Print an integer denoting the total number of ways that Lily can portion her chocolate bar to share with Ron.

Sample Input 0

5
1 2 1 3 2
3 2
Sample Output 0

2
Explanation 0

Lily wants to give Ron  squares summing to . The following two segments meet the criteria:

image

Sample Input 1

6
1 1 1 1 1 1
3 2
Sample Output 1

0
Explanation 1

Lily only wants to give Ron  consecutive squares of chocolate whose integers sum to . There are no possible pieces satisfying these constraints:

image

Thus, we print  as our answer.

Sample Input 2

1
4
4 1
Sample Output 2

1
Explanation 2

Lily only wants to give Ron  square of chocolate with an integer value of . Because the only square of chocolate in the bar satisfies this constraint, we print  as our answer.

public class Solution {

    static int solve(int n, int[] s, int d, int m){
        int result = 0;
        int sum=0;
        for(int i=0;i<s.length-(m-1);i++){
            for(int j=i;j<i+(m);j++){
                sum+=s[j];
               // System.out.println("Sum -"+sum+" m-"+m+" j-"+j +" i+(m-1)- "+(i+(m)));
            }
            if(sum==d ){
                result++;
            }
            sum=0;
           
        }
        return result;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] s = new int[n];
        for(int s_i=0; s_i < n; s_i++){
            s[s_i] = in.nextInt();
        }
        int d = in.nextInt();
        int m = in.nextInt();
        int result = solve(n, s, d, m);
        System.out.println(result);
    }
}

Breaking the Records

Maria plays college basketball and wants to go pro. Each season she maintains a record of her play. She tabulates the number of times she breaks her season record for most points and least points in a game. Points scored in the first game establish her record for the season, and she begins counting from there.

For example, assume her scores for the season are represented in the array . Scores are in the same order as the games played. She would tabulate her results as follows:

                                 Count
Game  Score  Minimum  Maximum   Min Max
 0      12     12       12       0   0
 1      24     12       24       0   1
 2      10     10       24       1   1
 3      24     10       24       1   1
Given Maria's array of  for a season of  games, find and print the number of times she breaks her records for most and least points scored during the season.

Input Format

The first line contains an integer , the number of games.
The second line contains  space-separated integers describing the respective values of .

Constraints

Output Format

Print two space-seperated integers describing the respective numbers of times her best (highest) score increased and her worst (lowest) score decreased.

Sample Input 0

9
10 5 20 20 4 5 2 25 1
Sample Output 0

2 4
Explanation 0

The diagram below depicts the number of times Maria broke her best and worst records throughout the season:

image

She broke her best record twice (after games  and ) and her worst record four times (after games , , , and ), so we print 2 4 as our answer. Note that she did not break her record for best score during game , as her score during that game was not strictly greater than her best record at the time.

Sample Input 1

10
3 4 21 36 10 28 35 5 24 42
Sample Output 1

4 0
Explanation 1

The diagram below depicts the number of times Maria broke her best and worst records throughout the season:

image

She broke her best record four times (after games , , , and ) and her worst record zero times (no score during the season was lower than the one she earned during her first game), so we print 4 0 as our answer.

public class Solution {

    /*
     * Complete the breakingRecords function below.
     */
    static int[] breakingRecords(int[] score) {
       
        int max=score[0];
        int min = score[0];
        int maxCount = 0;
        int minCount = 0;
        int[] finalScore=new int[2];
        for(int i=0;i<score.length;i++){
            if(score[i]>max){
                max=score[i];
                maxCount++;
            }else if(score[i]<min ){
                min=score[i];
                minCount++;
               
            }
            //System.out.println("score- "+score[i] +" min- "+min+" max- "+max+" minCount- "+minCount+" maxCount- "+maxCount);
        }
        finalScore[0]=maxCount;
        finalScore[1]=minCount;
        return finalScore;

    }

    private static final Scanner scan = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int n = Integer.parseInt(scan.nextLine().trim());

        int[] score = new int[n];

        String[] scoreItems = scan.nextLine().split(" ");

        for (int scoreItr = 0; scoreItr < n; scoreItr++) {
            int scoreItem = Integer.parseInt(scoreItems[scoreItr].trim());
            score[scoreItr] = scoreItem;
        }

        int[] result = breakingRecords(score);

        for (int resultItr = 0; resultItr < result.length; resultItr++) {
            bw.write(String.valueOf(result[resultItr]));

            if (resultItr != result.length - 1) {
                bw.write(" ");
            }
        }

        bw.newLine();

        bw.close();
    }
}