java程序设计编程作业题总结(二)

44.Ellipse Coverage

An ellipse is a figure on a plane where the sum of the distances from any point on its perimeter to two fixed points is constant. The two fixed points are called foci (plural of focus). In this problem we are interested in the number of points with integral coordinates that lie strictly inside of the given ellipse.

The foci are (x1y1) and (x2y2), and the fixed sum of distances is d.

Constraints
x1 , y1, x2, y2 will be between -100 and 100, inclusive.
d will be between 1 and 200, inclusive.  
The arguments will define a valid ellipse with positive area.

Input

The first line contains a single integer T tells that there are T cases in the problem. Then for each case, there are 5 integers, x1, y1, x2, y2 and d in order.

Output

The number of points with integral coordinates that lie strictly inside of the given ellipse.

Sample Input

2
0 0 0 0 4
-3 0 3 0 10

Sample Output

9
59

代码如下:

import java.util.*;
public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    while (n-->0) {
      int x1 = input.nextInt();int y1 = input.nextInt();
      int x2 = input.nextInt();int y2 = input.nextInt();
      int d = input.nextInt();
      int ox = (x1+x2)/2;int oy = (y1+y2)/2;int num = 0;
      for(int x = ox-d/2 ;x <=ox+d/2 ;x++){
        for(int y = oy-d/2;y <= oy+d/2;y++){
          if(Math.sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1))+Math.sqrt((x-x2)*(x-x2)+(y-y2)*(y-y2)) < d){
            num ++;}
        }
      }System.out.println(num);
    }input.close();
  }
}

45.Thimbles

Thimbles is a hazard game with the following rules. The dealer puts three identical thimbles on the table, with a small ball underneath the first one. Then, he repeatedly selects a pair of thimbles and swaps their positions. Finally, he asks you "Where is the ball?". You win if you point to the right thimble and lose otherwise.

You are writing the computer version of this game, and in this problem, you are to write a program that determines the position of the ball after all the thimble swaps have been done.

You will be given a series of swaps which describes the swaps made, in order. Each element of swaps will be in the format "X-Y" (quotes for clarity), which means that the thimble in position X was swapped with the thimble in position Y. The positions are 1, 2 or 3. Your method should return the position of the thimble with the ball after all the swaps.

swaps will contain between 1 and 50 elements, inclusive.
Each element of swaps will be in the format "X-Y" (quotes for clarity) where X and Y are distinct digits between 1 and 3, inclusive.

Input

The first line contains a single integer T tells that there are T case in the problem. Then for each case, there is a line tell you all the operations. The first integer of the line is the number of swap operations, following a series of X-Y swap operations.

Output

the position of the ball after all the thimble swaps have been done.

Sample Input

2
2 1-2 3-1
4 3-1 2-3 3-1 3-2

Sample Output

2
3

代码如下:

import java.util.*;
public class Main{
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n = input.nextInt();
    while(n-->0){
      int m = input.nextInt();int [] array ={1,2,3};
      for(int j = 0;j < m;j++){
      String str = input.next();
      char a = str.charAt(0);char b = str.charAt(2);
      int t = array[a-49];array[a-49] = array[b-49];array[b-49] = t;}
      for(int k = 0;k < array.length;k++){
        if(array[k] == 1){
          System.out.println(k+1);}
      }
    }
  }
}

46.The Telephone Dictionary

Businesses like to have memorable telephone numbers. One way to make a telephone number memorable is to have it spell a memorable word or phrase. For example, you can call the University of Waterloo by dialing the memorable TUT-GLOP. Sometimes only part of the number is used to spell a word. When you get back to your hotel tonight you can order a pizza from Gino's by dialing 310-GINO. Another way to make a telephone number memorable is to group the digits in a memorable way. You could order your pizza from Pizza Hut by calling their ``three tens'' number 3-10-10-10.

The standard form of a telephone number is seven decimal digits with a hyphen between the third and fourth digits (e.g. 888-1200). The keypad of a phone supplies the mapping of letters to numbers, as follows:

A, B, and C map to 2
D, E, and F map to 3
G, H, and I map to 4
J, K, and L map to 5
M, N, and O map to 6
P, R, and S map to 7
T, U, and V map to 8
W, X, and Y map to 9

There is no mapping for Q or Z. Hyphens are not dialed, and can be added and removed as necessary. The standard form of TUT-GLOP is 888-4567, the standard form of 310-GINO is 310-4466, and the standard form of 3-10-10-10 is 310-1010.

Two telephone numbers are equivalent if they have the same standard form. (They dial the same number.)

Your company is compiling a directory of telephone numbers from local businesses. As part of the quality control process you want to check that no two (or more) businesses in the directory have the same telephone number.

Input

The input will consist of one case. The first line of the input specifies the number of telephone numbers in the directory (up to 100,000) as a positive integer alone on the line. The remaining lines list the telephone numbers in the directory, with each number alone on a line. Each telephone number consists of a string composed of decimal digits, uppercase letters (excluding Q and Z) and hyphens. Exactly seven of the characters in the string will be digits or letters.

Output

Generate a line of output for those telephone number that appears more than once in any form. The line should give the telephone number in standard form, followed by a space, followed by the number of times the telephone number appears in the directory. Arrange the output lines by telephone number in ascending lexicographical order. 

Sample Input

12
4873279
ITS-EASY
888-4567
3-10-10-10
888-GLOP
TUT-GLOP
967-11-11
310-GINO
F101010
888-1200
-4-8-7-3-2-7-9-
487-3279

Sample Output

310-1010 2
487-3279 4
888-4567 3

代码如下:

import java.util.*;
import java.io.*;
public class Main {
  public static void main(String[] args) throws IOException {
    InputStreamReader r = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(r);
    int n = Integer.valueOf(br.readLine());
    String str1, str2,key,value = "";
    TreeMap map = new TreeMap();
    char[] ch = new char[7];
    for (int i = 0; i < n; i++) {
      str1 = br.readLine().replace("-", "");
      ch = str1.toCharArray();
      for (int j = 0; j < 7; j++) {
        if (ch[j] == 'A' || ch[j] == 'B' || ch[j] == 'C') {ch[j] = '2';} 
        else if (ch[j] == 'D' || ch[j] == 'E' || ch[j] == 'F') {ch[j] = '3';} 
        else if (ch[j] == 'G' || ch[j] == 'H' || ch[j] == 'I') {ch[j] = '4';} 
        else if (ch[j] == 'J' || ch[j] == 'K' || ch[j] == 'L') {ch[j] = '5';} 
        else if (ch[j] == 'M' || ch[j] == 'N' || ch[j] == 'O') {ch[j] = '6';} 
        else if (ch[j] == 'P' || ch[j] == 'R' || ch[j] == 'S') {ch[j] = '7';} 
        else if (ch[j] == 'T' || ch[j] == 'U' || ch[j] == 'V') {ch[j] = '8';} 
        else if (ch[j] == 'W' || ch[j] == 'X' || ch[j] == 'Y') {ch[j] = '9';}
      }
      str1 = "";
      for (int j = 0; j < 7; j++) {
        str1 += ch[j];
        if (j == 2) {
          str1 += "-";
        }
      }
      if (!map.containsKey(str1)) {
        map.put(str1, "1");
      } else {
        str2 = (String) map.get(str1);
        str2 = String.valueOf(Integer.valueOf(str2) + 1);
        map.put(str1, str2);
      }
    }br.close();r.close();
    Set keySet = map.keySet();
    Iterator it = keySet.iterator();
    while (it.hasNext()) {
      key = (String) it.next();
      value = (String) map.get(key);
      int va = Integer.valueOf(value);
      if (va >= 2) {
        System.out.println(key + " " + value);
      }
    }
  }
}

47.SMS Language

SMS messages are short messages sent between mobile phones. The maximum length of a single message is 160 characters, so it is often necessary to abbreviate words.

You are given a String text, and your task is to translate it to SMS language according to the following rules:

  1. Remove all punctuation symbols ('.', ',', '?' and '!').
  2. Replace all uppercase letters with their lowercase equivalents.
  3. Replace all occurrences of "and" with '&'.
  4. Replace all occurrences of "ate" with '8'.
  5. Replace all occurrences of "at" with '@'.
  6. Replace all occurrences of "you" with 'U'.

All quotes are for clarity only. The rules must be applied in the order they appear in the list. For example, "I HATE rats, and you?" will be translated to "i h8 r@s & U".

Hint: you are encouraged to use StringBuffer class for String manipunations. Of course, you can also use other methods you like.

Input

The first line contains a single integer T tells that there are T case in the problem. Then there are T lines of strings.

Output

The resulting translation as a String.

Sample Input

2
I HATE rats, and you?
What is the weather like today?

Sample Output

i h8 r@s & U
wh@ is the we@her like today

代码如下:

import java.util.*;
public class Main{
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n = Integer.parseInt(input.nextLine());
    while (n-->0) {
    String str = input.nextLine();
    String fina =str.replaceAll("[\\pP‘’“”]","").toLowerCase().replace("and", "&").replace("ate", "8").replace("at", "@").replace("at", "@").replace("you","U");
    System.out.println(fina);
    }
  }
}

48.Use the Singleton Design Pattern

Objective

In this exercise you will modify the Bank class to implement the Singleton design pattern.

Directions

Start by changing your working directory to exercise1 on your computer(or anywahere else you like). Copy your all of the Java files from previous exercise of the "Class Design" module into the banking.domain package directory.

Note: at this stage the Banking Project has need for a more complex package hierarchy because we will be creating a CustomerReport class which belongs in the banking.reports package. Therefore, the "domain" classes need to be placed in the banking/domain directory. Also, you will need to change the package declaration for each of these files.

Modify the Bank Class to Implement the Singleton Design Pattern

java程序设计编程作业题总结(二)_第1张图片

  1. Modify the Bank class to create a public static method, called getBank, that returns an instance of the Bank class.

  2. The single instance should be a static attribute and should be private. Likewise, make the Bank constructor private.

Modify the CustomerReport Class

In the previous Banking Project exercise, the "customer report" was embedded in the main method of the Main program. In this exercise, this code has been pulled out into the CustomerReport class in the banking.reports package. Your task will be to modify this class to use the Singleton bank object. The contents of the class is as follows:

package banking.reports;

import banking.domain.*;
import java.text.NumberFormat;

public class CustomerReport {

public void generateReport() {
NumberFormat currency_format = NumberFormat.getCurrencyInstance();

Bank bank = /*** STEP 1: RETRIEVE BANK SINGLETON OBJECT HERE ***/

Customer customer;

System.out.println("CUSTOMERS REPORT");
System.out.println("================");

for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
customer = bank.getCustomer(cust_idx);

System.out.println();
System.out.println("Customer: "
+ customer.getLastName() + ", "
+ customer.getFirstName());

for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
Account account = customer.getAccount(acct_idx);
String account_type = "";

// Determine the account type
if ( account instanceof SavingsAccount ) {
account_type = "Savings Account";
} else if ( account instanceof CheckingAccount ) {
account_type = "Checking Account";
} else {
account_type = "Unknown Account Type";
}

// Print the current balance of the account
System.out.println(" " + account_type + ": current balance is "
+ currency_format.format(account.getBalance()));
}
}
}

}

Compile and Run the Main Program. And then submit your code as before.

Note: This time you DON'T need to submit all your code, the Main class is preset. So you need to submit your other classes only. Don't forget to comment out the package statements and put all the classes in the same file.

 代码如下:

/* PRESET CODE BEGIN - NEVER TOUCH CODE BELOW */
import java.text.NumberFormat;
import java.util.*;
class Main {
	public static void main(String[] args) {
		Bank bank = Bank.getBank();
		Customer customer;
		int curCustomer = 0;
		Scanner s = new Scanner(System.in);
		int t = s.nextInt();
		s.nextLine();
		// Create several customers and their accounts according to data
		while (t-- > 0) {
			String f = s.next();
			String l = s.next();
			s.nextLine();
			bank.addCustomer(f, l);
			customer = bank.getCustomer(curCustomer++);
			int numAccount = s.nextInt();
			s.nextLine();
			while (numAccount-- > 0) {
				String[] type = s.nextLine().split(" ");
				double balance;
				double interesOrProtect;
				char op = type[0].charAt(0);
				if (op == 'C' || op == 'c') {
					balance = Double.parseDouble(type[1]);
					if (type.length == 3) {
						interesOrProtect = Double.parseDouble(type[2]);
						customer.addAccount(new CheckingAccount(balance,
								interesOrProtect));
					} else {
						customer.addAccount(new CheckingAccount(balance));
					}
				} else if (op == 'S' || op == 's') {
					balance = Double.parseDouble(type[1]);
					interesOrProtect = Double.parseDouble(type[2]);
					customer.addAccount(new SavingsAccount(balance,
							interesOrProtect));
				} else if (op == 'A' || op == 'a') {
					int cIndex = Integer.parseInt(type[1]);
					int aIndex = Integer.parseInt(type[2]);
					customer.addAccount(bank.getCustomer(cIndex).getAccount(
							aIndex));
				}
			}
		}
		
		CustomerReport cr = new CustomerReport();
		cr.generateReport();
	}
}
/* PRESET CODE END - NEVER TOUCH CODE ABOVE */
class Account {
  protected double balance;
  public Account(double init_balance) {
    balance = init_balance;
  }
  public double getBalance() {
    return balance;
  }
  public boolean deposit(double amt) {
    balance += amt;
    return true;
  }
  public boolean withdraw(double amt) {
    if (balance >= amt) {
      balance -= amt;
      return true;
    } else
      return false;
  }
}
class SavingsAccount extends Account {
  private double interestRate;
  public SavingsAccount(double balance, double interest_rate) {
    super(balance);
    interestRate = interest_rate;
    this.balance = balance;
  }
}
class CheckingAccount extends Account {
  private Account protectedBy ;
  public CheckingAccount(double init_balance) {
    super(init_balance);
  }
  public CheckingAccount(double init_balance,double interesOrProtect) {
    super(init_balance);
  }
  public boolean withdraw(double amt) {
    // 余额足够
    if (balance >= amt) {
      balance -= amt;
    } else {
      if (protectedBy != null && protectedBy.getBalance() >= (amt - balance)) {
        protectedBy.withdraw(amt - balance);
        balance = 0;
      } else {
        return false;
      }
    }
    return true;
  }
}
class Bank {
  private Customer[] customers = new Customer[15];
  private int numberOfCustomers;
  private static Bank bank = new Bank();
  public Bank() {
  }
  public static Bank getBank() {
    return bank;
  }
  public void addCustomer(String f, String l) {
    customers[numberOfCustomers] = new Customer(f, l);
    numberOfCustomers++;
  }
  public int getNumOfCustomers() {
    return numberOfCustomers;
  }
  public Customer getCustomer(int index) {
    return customers[index];
  }
}
class Customer {
  private String firstName;
  private String lastName;
  private Account[] accounts;
  private int numberOfAccounts;
  private Account savingsAccount = null;
  private Account checkingAccount = null;
  public Customer(String f, String l) {
    firstName = f;
    lastName = l;
    accounts = new Account[2];
  }
  public String getFirstName() {
    return firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public Account getAccount(int index) {
    return accounts[index];
  }
  public int getNumOfAccounts() {
    return numberOfAccounts;
  }
  public void addAccount(Account account) {
    accounts[numberOfAccounts++] = account;
  }
  public Account getSavings() {
    return savingsAccount;
  }
  public void setSavings(Account savingsAccount) {
    this.savingsAccount = savingsAccount;
  }
  public Account getChecking() {
    return checkingAccount;
  }
  public void setChecking(Account checkingAccount) {
    this.checkingAccount = checkingAccount;
  }
}
class CustomerReport {
  public void generateReport() {
  NumberFormat currency_format = NumberFormat.getCurrencyInstance();
  
  Bank bank = Bank.getBank();/*** STEP 1: RETRIEVE BANK SINGLETON OBJECT HERE ***/
  
  Customer customer = null;
  
  System.out.println("CUSTOMERS REPORT");
  System.out.println("================");
  
  for ( int cust_idx = 0; cust_idx < bank.getNumOfCustomers(); cust_idx++ ) {
  customer = bank.getCustomer(cust_idx);
  
  System.out.println();
  System.out.println("Customer: "+ customer.getLastName() + ", "+ customer.getFirstName());
  
  for ( int acct_idx = 0; acct_idx < customer.getNumOfAccounts(); acct_idx++ ) {
  Account account = customer.getAccount(acct_idx);
  String account_type = "";
  
  // Determine the account type
  if ( account instanceof SavingsAccount ) {
  account_type = "Savings Account";
  } else if ( account instanceof CheckingAccount ) {
  account_type = "Checking Account";
  } else {
  account_type = "Unknown Account Type";
  }
  
  // Print the current balance of the account
  System.out.println("    " + account_type + ": current balance is "
  + currency_format.format(account.getBalance()));
  }
  }
  }
}

49.Nearly Lucky Number

Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.

Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number n is a nearly lucky number.

Input

There are T test cases for each test, with the first line containing a integer T and following T lines of ingteger.  Each line contains an integer n (1 ≤ n ≤ 1018).

Output

For each test, print T lines of "YES" or "NO". Print "YES" if n is a nearly lucky number. Otherwise, print "NO" (without the quotes).

Sample test(s)

input

1
40047

output

NO

input

1
7747774

output

YES

input

1
1000000000000000000

output

NO

Note

In the first sample there are 3 lucky digits (first one and last two), so the answer is "NO".

In the second sample there are 7 lucky digits, 7 is lucky number, so the answer is "YES".

In the third sample there are no lucky digits, so the answer is "NO".

代码如下:

import java.util.*;
public class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int n = Integer.parseInt(input.nextLine());
    while (n-- > 0) {
      String lu

你可能感兴趣的:(java,java,算法)