面向对象程序设计JAVA学习记录(9)

String Task

Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:

  • deletes all the vowels,
  • inserts a character "." before each consonant,
  • replaces all uppercase consonants with corresponding lowercase ones.

Vowels are letters "A", "O", "Y", "E", "U", "I", and the rest are consonants. The program's input is exactly one string, it should return the output as a single string, resulting after the program's processing the initial string.

Help Petya cope with this easy task.

Input

The first line represents input string of Petya's program. This string only consists of uppercase and lowercase Latin letters and its length is from 1 to 100, inclusive.

Output

Print the resulting string. It is guaranteed that this string is not empty.

Sample test(s)

input

tour

output

.t.r

input

Codeforces

output

.c.d.f.r.c.s

input

aBAcAba

output

.b.c.b

先改大小写然后替换

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        String str = s.nextLine();
        int len = str.length();
        char[] arr = str.toCharArray();
        for(int i = 0; i < len; i++) if(arr[i] < 97) arr[i] += 32;
        for(int i = 0; i < len; i++){
            if(arr[i]=='a'||arr[i]=='e'||arr[i]=='i'||arr[i]=='o'||arr[i]=='u'||arr[i]=='y') continue;
            else System.out.print("." + arr[i]);
        }
        System.out.print("\n");
        s.close();
    }
}

Present from Lena

Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handkerchief pattern should look like that:

          0
        0 1 0
      0 1 2 1 0
    0 1 2 3 2 1 0
  0 1 2 3 4 3 2 1 0
0 1 2 3 4 5 4 3 2 1 0
  0 1 2 3 4 3 2 1 0
    0 1 2 3 2 1 0
      0 1 2 1 0
        0 1 0
          0

Your task is to determine the way the handkerchief will look like by the given n.

Input

The first line contains the single integer n (2 ≤ n ≤ 9).

Output

Print a picture for the given n. You should strictly observe the number of spaces before the first digit on each line. Every two adjacent digits in the same line should be separated by exactly one space. There should be no spaces after the last digit at the end of each line.

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        for(int i = 0; i <= n; i ++){
            for(int j = (n-i)*2; j > 0; j--) System.out.print(" ");
            System.out.print("0");
            for(int j = 1; j <= i; j++) System.out.print(" " + j);
            for(int j = i-1; j >= 0; j--) System.out.print( " " + j);
            System.out.print("\n");
        }
        for(int i = n - 1; i >= 0; i--){
            for(int j = (n-i)*2; j > 0; j--) System.out.print(" ");
            System.out.print("0");
            for(int j = 1; j <= i; j++) System.out.print(" " + j);
            for(int j = i-1; j >= 0; j--) System.out.print( " " + j);
            System.out.print("\n");
        }
        s.close();
    }
}

Chocolate(Optional)

Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with equal speed). When the player consumes a chocolate bar, he immediately starts with another. It is not allowed to eat two chocolate bars at the same time, to leave the bar unfinished and to make pauses. If both players start to eat the same bar simultaneously, Bob leaves it to Alice as a true gentleman.

How many bars each of the players will consume?

Input

The first line contains one integer n (1 ≤ n ≤ 105) — the amount of bars on the table. The second line contains a sequencet1, t2, ..., tn (1 ≤ ti ≤ 1000), where ti is the time (in seconds) needed to consume the i-th bar (in the order from left to right).

Output

Print two numbers a and b, where a is the amount of bars consumed by Alice, and b is the amount of bars consumed by Bob.

Sample test(s)

input

5
2 9 8 2 7

output

2 3

分别用数组统计即可

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        int[] arr = new int[n];
        for(int i = 0; i < n; i++) arr[i] = s.nextInt();
        int a = arr[0];
        int b = arr[n-1];
        int counta = 1;
        int countb = 1;
        if(n == 1) countb = 0;
        int left = n-2;
        while(left > 0){
            if(a > b){
                b += arr[n-1-countb];
                countb++;
                left--;
            }
            else if(b > a){
                a += arr[counta];
                counta++;
                left--;
            }
            else if(a == b){
                if(left == 1){
                    counta++;
                    break;
                }
                else if(left > 1){
                    b += arr[n-1-countb];
                    a += arr[counta];
                    counta++;
                    countb++;
                    left -= 2;
                }
            }
        }
        System.out.println(counta + " " + countb);
        s.close();
    }
}

Chess Board

A famous Berland's painter Kalevitch likes to shock the public. One of his last obsessions is chess. For more than a thousand years people have been playing this old game on uninteresting, monotonous boards. Kalevitch decided to put an end to this tradition and to introduce a new attitude to chessboards.

As before, the chessboard is a square-checkered board with the squares arranged in a 8 × 8 grid, each square is painted black or white. Kalevitch suggests that chessboards should be painted in the following manner: there should be chosen a horizontal or a vertical line of 8 squares (i.e. a row or a column), and painted black. Initially the whole chessboard is white, and it can be painted in the above described way one or more times. It is allowed to paint a square many times, but after the first time it does not change its colour any more and remains black. Kalevitch paints chessboards neatly, and it is impossible to judge by an individual square if it was painted with a vertical or a horizontal stroke.

Kalevitch hopes that such chessboards will gain popularity, and he will be commissioned to paint chessboards, which will help him ensure a comfortable old age. The clients will inform him what chessboard they want to have, and the painter will paint a white chessboard meeting the client's requirements.

It goes without saying that in such business one should economize on everything — for each commission he wants to know the minimum amount of strokes that he has to paint to fulfill the client's needs. You are asked to help Kalevitch with this task.

Input

The input file contains 8 lines, each of the lines contains 8 characters. The given matrix describes the client's requirements, W character stands for a white square, and B character — for a square painted black.

It is guaranteed that client's requirments can be fulfilled with a sequence of allowed strokes (vertical/column or horizontal/row).

Output

Output the only number — the minimum amount of rows and columns that Kalevitch has to paint on the white chessboard to meet the client's requirements.

Sample test(s)

input

WWWBWWBW
BBBBBBBB
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW
WWWBWWBW

output

3

input

WWWWWWWW
BBBBBBBB
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW
WWWWWWWW

output

1
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        String[] arr = new String[8];
        for(int i = 0; i < 8; i++) arr[i] = s.nextLine();
        int count = 0;
        for(int i = 0; i < 8; i++){
            int flag = 0;
            for(int j = 0; j < 8; j++){
                if(arr[i].charAt(j) != 'B'){
                    flag = 1;
                    break;
                }
            }
            if(flag == 0) count++;
        }
        for(int i = 0; i < 8; i++){
            int flag = 0;
            for(int j = 0; j < 8; j++){
                if(arr[j].charAt(i) != 'B'){
                    flag = 1;
                    break;
                }
            }
            if(flag == 0) count++;
        }
        if(count == 16) count = 8;
        System.out.println(count); 
        s.close();
    }
}

Jumping Jack

Jack is working on his jumping skills recently. Currently he's located at point zero of the number line. He would like to get to the point x. In order to train, he has decided that he'll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or right with each jump. He wonders how many jumps he needs to reach x.

Input

The first line contains a single integer T tells that there are T case in the problem. Then there are T lines of integer x ( - 109 ≤ x ≤ 109).

Output

For each test case, output a line of the minimal number of jumps that Jack requires to reach x.

Sample test(s)

input

1
2

output

3

input

1
6

output

3

input

1
0

output

0
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        long[] arr = new long[n];
        for(int i = 0; i < n; i++) arr[i] = s.nextLong();
        for(int i = 0; i < n; i++){
            int step = 0;
            arr[i] = Math.abs(arr[i]);
            for(int j = 1; j <= arr[i]; j++) {
                int num = (1 + j) * j / 2;
                if(num >= arr[i]) {
                    step = j;
                    if((num - arr[i]) % 2 != 0) {
                        if((j + 1) % 2 == 1) {
                            step++;
                        } else {
                            step += 2;
                        }
                    }
                    break;
                }
            }
            System.out.println(step);
        }
        s.close();
    }
}

Increasing Sequence

A sequence a0, a1, ..., at - 1 is called increasing if ai - 1 < ai for each i: 0 < i < t.

You are given a sequence b0, b1, ..., bn - 1 and a positive integer d. In each move you may choose one element of the given sequence and add d to it. What is the least number of moves required to make the given sequence increasing?

Input

The first line of the input contains two integer numbers n and d (2 ≤ n ≤ 2000, 1 ≤ d ≤ 106). The second line contains space separated sequence b0, b1, ..., bn - 1 (1 ≤ bi ≤ 106).

Output

Output the minimal number of moves needed to make the sequence increasing.

Sample test(s)

input

4 2
1 3 3 2

output

3
import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();
        long d = s.nextInt();
        long[] arr = new long[n];
        long step = 0;
        for(int i = 0; i < n; i++) arr[i] = s.nextLong();
        for(int i = 0; i < n-1; i++){
            if(arr[i] >= arr[i+1]){
                long num = ((arr[i] - arr[i+1])/d) + 1;
                step += num;
                arr[i+1] += d*num;
            }
        }
        System.out.println(step);
        s.close();
    }
}

How Many Squares?

You are given a 0-1 rectangular matrix. What is the number of squares in it? A square is a solid square frame (border) with linewidth equal to 1. A square should be at least 2 × 2. We are only interested in two types of squares:

  1. squares with each side parallel to a side of the matrix;
  2. squares with each side parallel to a diagonal of the matrix.

For example the following matrix contains only one square of the first type: 
0000000 
0111100 
0100100 
0100100 
0111100

The following matrix contains only one square of the second type:
0000000
0010000
0101000
0010000
0000000

Regardless of type, a square must contain at least one 1 and can't touch (by side or corner) any foreign 1. Of course, the lengths of the sides of each square should be equal.

How many squares are in the given matrix?

Input

The first line contains integer t (1 ≤ t ≤ 10000), where t is the number of test cases in the input. Then test cases follow. Each case starts with a line containing integers n and m (2 ≤ n, m ≤ 250), where n is the number of rows and m is the number of columns. The following n lines contain m characters each (0 or 1).

The total number of characters in all test cases doesn't exceed 106 for any input file.

Output

You should output exactly t lines, with the answer to the i-th test case on the i-th line.

Sample test(s)

input

2
8 8
00010001
00101000
01000100
10000010
01000100
00101000
11010011
11000011
10 10
1111111000
1000001000
1011001000
1011001010
1000001101
1001001010
1010101000
1001001000
1000001000
1111111000

output

1
2

分情况统计边

import java.util.*;
public class Main{
    static int dirx[] = { 0,1,0,-1, 1,1,-1,-1}; 
    static int diry[] = {1, 0,-1,0,-1,1,-1,1};
    static int a[][]=new int[255][255];
    static int n;
    static int m;
    static int cnt;
    public static void main(String []args){
        Scanner s=new Scanner(System.in);
        int T=s.nextInt();
        while(T-->0){
            n=s.nextInt();
            m=s.nextInt();
            for(int i = 1;i <= n;i++){
                String mk=s.next();
                for(int j = 1;j <= m;j++){
                    a[i][j]=mk.charAt(j-1)-'0';
                }
            }
            int ans = 0;
            for(int i = 1;i <= n;i++){
                for(int j = 1;j <= m;j++){
                    if(a[i][j] == 1){
                        cnt = 0;
                        dfs(i,j);
                        if(cnt == 0 || (cnt % 4 != 0) || cnt / 4 > Math.min(n,m)) continue;
                        if(judge(i,j,0,1,cnt / 4) && judge(i + cnt / 4,j + cnt / 4,2,3,cnt / 4)) {
                            ans++;
                        }
                        if(judge(i,j,4,5,cnt / 4) && judge(i + cnt / 2,j,6,7,cnt / 4)) { 
                            ans++;
                        }
                    }
                }
            }
            System.out.println(ans);
            }
        }
    static void dfs(int x,int y){
        a[x][y] = -1;
        cnt++;
        for(int d = 0;d < 8;d++){
            int dx = x + dirx[d];
            int dy = y + diry[d];
        if(dx <= 0 || dx > n || dy <= 0 || dy > m || a[dx][dy] != 1){
            continue;
        }
        dfs(dx,dy);
        }
    }
    static boolean judge(int i,int j,int d1,int d2,int len){
        if(a[i][j] != -1) return false;
        for(int d = d1;d <= d2;d++){
            int x = i,y = j;
            for(int num = 1;num <= len + 1;num++) {
                if(x <= 0 || x > n || y <= 0 || y > m || a[x][y] != -1){
                return false;
                }
                x += dirx[d];y += diry[d];
            }
        }
        return true;
    }
}

Super Agent

There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage, he penetrated into the Potatoland territory and reached the secret base.

Now he is standing at the entrance, but to get inside he need to pass combination lock. Minute ago one of the workers entered the password on the terminal and opened the door. The terminal is a square digital keyboard 3 × 3 with digits from 1 to 9.

Pearlo knows that the password consists from distinct digits and is probably symmetric with respect to the central button of the terminal. He has heat sensor which allowed him to detect the digits which the worker pressed. Now he wants to check whether the password entered by the worker is symmetric with respect to the central button of the terminal. This fact can Help Pearlo to reduce the number of different possible password combinations.

Input

Input contains the matrix of three rows of three symbols each. Symbol «X» means that the corresponding button was pressed, and «.» means that is was not pressed. The matrix may contain no «X», also it may contain no «.».

Output

Print YES if the password is symmetric with respect to the central button of the terminal and NO otherwise.

Sample test(s)

input

XX.
...
.XX

output

YES

input

X.X
X..
...

output

NO

枚举即可

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        String a1 = s.nextLine();
        String a2 = s.nextLine();
        String a3 = s.nextLine();
        int flag = 0;
        if(a1.charAt(0) != a3.charAt(2)) flag = 1;
        if(a1.charAt(1) != a3.charAt(1)) flag = 1;
        if(a1.charAt(2) != a3.charAt(0)) flag = 1;
        if(a2.charAt(0) != a2.charAt(2)) flag = 1;
        if(flag == 0) System.out.println("YES");
        else System.out.println("NO");
        s.close();
    }
}

Numbered Lines

Objective

Just like what you've done in the exercise of "What have you got?", this time you need to read from a named file and output your result to another named file. You will create a program to read text from a file named "input.in" and write it to a file named "output.out" with each line prefixed with a line-number.

Note, this time the input and output are both from/to file. You need to take care of it. The input.in and output.out are in the same directory as your program (that's, the current directory.). You can not assume the directory in which you program runs.

Besides, you can not assume how many lines there are in the input file.

Hints

  1. Declare a variable that holds a File object that is initialized from the file names as specified.

  2. Within a try-catch block, create a buffered, input stream reader based on the input file.

  3. Also, create a print file writer based on the output File variable.

  4. Write the while loop that reads each line from the file input stream and prints the line out to the file. Each line should be prepended with the count of the line number.

  5. Make sure to close the I/O streams.

Input: A line of string, until the end of the file is reached!  Example:
This is the first line.
This is the second line.
...
This is the end.

Output: What you get from the file with line number as prefix.
1 This is the first line.
2 This is the second line.
  ...
xx This is the end.

这里是文件的操作

import java.io.*;
import java.util.ArrayList;
public class Main{
public static void main(String[] args) throws IOException {
        BufferedReader r = new BufferedReader(new FileReader("input.in"));
        BufferedWriter w = new BufferedWriter(new FileWriter("output.out"));
        ArrayList<String> arr = new ArrayList<>();
        String str; 
        while ((str = r.readLine()) != null) {
            arr.add(str); 
        }
        r.close();
        for (int i = 0; i <= arr.size() - 1; i++) {
            w.write((i+1)+" "+arr.get(i));
            w.newLine();
        }
        w.close();
    }
}

猜你喜欢

转载自blog.csdn.net/lijj0304/article/details/127973206