Showing posts with label Java Programming QA. Show all posts
Showing posts with label Java Programming QA. Show all posts

Tuesday, June 26, 2007

Q11: number composition

Q: How many three digit numbers can you generate with 1, 2, 3, 4. The numbers are not duplicated and each number doesn't have duplicate digits.

A:

===========================================
import java.util.Vector;

public class NumberComposition {
private static Vector nums = new Vector();

public static void generateNumbers(){
int num;

for(int i=1; i <= 4; i++){
num =0;
for(int j=1; j <= 4; j++){
for(int k=1; k <= 4; k++){
if((i!=j) && (i!=k) && (j!=k)){
num = i* 100 + j*10 + k;
nums.add(num);
}else continue;
}
}
}
}

public static int getNumberCounter(){
return nums.size();
}

public static void printNumbers(){
for(int i=0; i < nums.size(); i++){
System.out.print(nums.get(i) + " ");
}
}

public static void main(String[] args) {
generateNumbers();
System.out.println("Total number: " + getNumberCounter());
printNumbers();
}
}
==========================================

result:
Total number: 24
123 124 132 134 142 143 213 214 231 234 241 243 312 314 321 324 341 342 412 413 421 423 431 432

Wednesday, June 13, 2007

Q10: Bouncing Ball

Q: a ball is dropped from 100 meters and bounce back to half of previous height. How many meters does it pass when it hits the ground at 10th time, and the height of it 10th bounce back?

A:


public class BallBounce {
/**
* Because the height is half of the previous one each bounce back,
* the height is divided by 2 each time.
* @param initHeight the initial height
* @param times the number of bounce back
* @return the height of bounce
*/
public static float getHeight(float initHeight, int times){
for(int i=0; i< times; i++){
initHeight /= 2;
}
return initHeight;
}

/**
* When ball hits ground n times, it bounces back n-1 time.
* Therefore, it passes initHeight plus the multiplication of 2 and height of each bounce.
* @param initHeight the initial height
* @param times the number that ball hits the ground
* @return the meters of the ball passed
*/
public static float getBallPass(float initHeight, int hitTimes){
float p = initHeight;
for(int i=0; i<(hitTimes-1); i++){
p += getHeight(initHeight, i+1)*2;
}
return p;
}

public static void main(String[] args) {
int times = 5;
System.out.println("When the ball hits 10th ground, it passes " + getBallPass(100, times) + " meters, and it bounces back " + getHeight(100, times));
}
}

result:
When the ball hits 10th ground, it passes 299.60938 meters, and it bounces back 0.09765625.

Monday, June 11, 2007

Q9: Perfect Number

Q: find out all perfect numbers that are less than 1,000.

a perfect number is defined as an integer which is the sum of its proper positive divisors, that is, the sum of the positive divisors not including the number. For example, the first perfect number is 6, because 1, 2 and 3 are its proper positive divisors and 1 + 2 + 3 = 6. Definition is from wikipedia.org

A:
import java.util.Vector;

public class PerfectNumber {
private static Vector v ;

private static void getAllFactors(int n){
v = new Vector();
if(n <= 2) return;
v.add(1);
int sqrt = (int)Math.pow(n, 0.5)+1;
for(int i=2; i < sqrt; i++){
if((n%i) == 0){
v.add(i);
v.add(n/i);
}
}
}

private static boolean isPerfectNumber(int num){
getAllFactors(num);
int sum = 0;
for(int i=0; i < v.size(); i++){
sum += v.get(i);
}
// System.out.println(num + " sum: " + sum);
if(sum == num) return true;
return false;
}

public static void printPerfectNumber(int range){
for(int i=1; i < range; i++){
if(isPerfectNumber(i)){
System.out.print(i + ", ");
}
}
}
public static void main(String[] args) {
System.out.println("Perfect numbers between 0 and 1000: ");
PerfectNumber.printPerfectNumber(1000);
}
}

Result:
Perfect numbers between 0 and 1000:
6, 28, 496,

Thursday, June 7, 2007

Q8: sum calculation

Q: calculate the sum of s in s = a + aa + a...a. a is a number. The last number is a a digits number. For example, a is 5, then the formula is s = 5 + 55 + 555 + 5555 + 55555.

A:

public class Sum {
private static int getNumber(int a, int len){
int num =0;
for(int i=1; i<=len; i++){
num = num * 10 + a;
}
System.out.println("num " + len +": " + num);
return num;
}

public static int getSum(int a){
int sum =0;
for(int i=1; i<=a; i++){
sum += getNumber(a, i);
}
return sum;
}
public static void main(String[] args) {
System.out.println("Sum for 5: " + Sum.getSum(5));
}
}

result:
num 1: 5
num 2: 55
num 3: 555
num 4: 5555
num 5: 55555
Sum for 5: 61725

Wednesday, June 6, 2007

Q7: Input statistics

Q: Counting the quantity of letters, numbers, space, and others in a input line.

A:

import java.util.Scanner;

public class InputCounting {
public static int countLetters(String is){
byte b[] = is.getBytes();
int cnt = 0;
for(int i=0; i < b.length; i++){
if(Character.isLetter(b[i])) cnt++;
}
return cnt;
}

public static int countNumbers(String is){
byte b[] = is.getBytes();
int cnt = 0;
for(int i=0; i < b.length; i++){
if(Character.isDigit(b[i])) cnt++;
}
return cnt;
}

public static int countSpaces(String is){
byte b[] = is.getBytes();
int cnt = 0;
for(int i=0; i < b.length; i++){
if(Character.isSpaceChar(b[i])) cnt++;
}
return cnt;
}

public static int countOthers(String is){
byte b[] = is.getBytes();
int cnt = 0;
for(int i=0; i < b.length; i++){
if(!(Character.isSpaceChar(b[i]) ||
Character.isDigit(b[i]) ||
Character.isLetter(b[i])))
cnt++;
}
}
return cnt;
}

public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String input;
while(true){
System.out.print("Please input the counted String: ");
input = s.nextLine();
if(input.equalsIgnoreCase("Quit")) break;
System.out.println("Letter quantity: " + InputCounting.countLetters(input));
System.out.println("Number quantity: " + InputCounting.countNumbers(input));
System.out.println("Space quantity: " + InputCounting.countSpaces(input));
System.out.println("Others quantity: " + InputCounting.countOthers(input));
}
}
}

result:
Please input the counted String: What are the counters for "123456"?
Letter quantity: 21
Number quantity: 6
Space quantity: 5
Others quantity: 3
Please input the counted String: Quit

Tuesday, June 5, 2007

Q6: Lowest common denominator and Greatest common divisor

Q: find the Lowest Common Denominator(LCD) and the Greatest Common Divisor(GCD) for two given integers.

The lowest common denominator or least common denominator (abbreviated LCD) is the least common multiple of the denominators of a set of vulgar fractions.

The greatest common divisor (gcd), sometimes known as the greatest common factor (gcf) or highest common factor (hcf), of two non-zero integers, is the largest positive integer that divides both numbers without remainder.

The definitions are from Wikipedia.org

A:

public class GcdAndLcm {
// This is using Euclidean algorithm.
public static int getGreatestCommonDivisor(int a, int b){
// make sure that a is greater than b
if(b > a){
int c = a; a = b; b = c;
}

if((a % b) == 0) return b;
else if( (a % b) == 1) return 1;
else return getGreatestCommonDivisor(b, (a%b));
}

public static int getLeastCommonMultiple(int a, int b){
return (a * b / getGreatestCommonDivisor(a, b));
}

public static void main(String[] args) {
System.out.println("Greatest Common Divisor for 84 and 18 is " + GcdAndLcm.getGreatestCommonDivisor(84, 18));
System.out.println("Least Common Multiple for 84 and 18 is " + GcdAndLcm.getLeastCommonMultiple(84, 18));
}
}

result:
Greatest Common Divisor for 84 and 18 is 6
Least Common Multiple for 84 and 18 is 252

Monday, June 4, 2007

Q5: Mark Rank

Q: Ranking a mark:
1. Greater than or equal to 90, it is A;
2. Between 60 and 89, it is B;
3. Less than 60, it is C.


A:

public class MarkRank {
public static char rankMark(int mark){
if(mark >= 90) return 'A';
else if((mark <=89) && (mark >=60)) return 'B';
else return 'C';
}

public static void main(String[] args) {
System.out.println("Mark 95: " + MarkRank.rankMark(95));
System.out.println("Mark 78: " + MarkRank.rankMark(78));
System.out.println("Mark 59: " + MarkRank.rankMark(59));
}
}

Sunday, June 3, 2007

Q4: Integer factorization.

Q: factorize a given integer. For example: 90 = 2*3*3*5;

A:
Assuming a number n to be factorized. following steps:
1. from 1 to n, find the smallest prime number a by which n is divided;
2. if a equal to n, then exit;
3. if n is divided by a, then performs the division continuously, and the result is assigned to n;
4. if n is not divided by a, try the next number a = a + 1, and repeat 2 to 4;


public class IntegerFactoring {
private static int getFactor(int num, int startpoint){
if(num <= 1) return 1;
for(int i=startpoint+1; i<=num; i++){
if((num % i) == 0) return i;
}
return 1;
}

public static void printFactoring(int n){
int f = 1;
f=getFactor(n, f);
System.out.print(n + "=" + f);
n = n/f;
f--;
while((f=getFactor(n, f)) !=1){
while(n%f ==0){
n = n/f;
System.out.print("*" + f);
}
}
}

public static void main(String[] args) {
IntegerFactoring.printFactoring(90);
}
}

result:
90=2*3*3*5

Saturday, June 2, 2007

Q3: Armstrong Number(Narcissistic number)

Q: Print out all Narcissistic numbers between 100 and 999.

In number theory, a narcissistic number or pluperfect digital invariant (PPDI) or Armstrong number is a number that in a given base is the sum of its own digits to the power of the number of digits.

For example, the decimal (Base 10) number 153 is an Armstrong number, because:

1³ + 5³ + 3³ = 153
A:
public class Armstrong {
private static boolean isArmstrong(int n){
int base = n;
int size = Integer.toString(n).length();
int sum = 0, d=0;

for(int i=0; i < size; i++){
d = base %10;
base /=10;
sum += Math.pow(d, size);
}
if(sum == n) return true;
else return false;
}

public static int getArmstrongQuantity(int root, int floor){
int cnt =0;
for(int i=root; i < floor; i++){
if(isArmstrong(i)){
System.out.print(i + ", ");
cnt++;
}
}
System.out.println();
return cnt;
}

public static void main(String[] args) {
System.out.println("There are " +
Armstrong.getArmstrongQuantity(100, 999) +
" armstrong numbers between 100 and 999.");
}
}

result:
153, 370, 371, 407,
There are 4 armstrong numbers between 100 and 999.

Q2: Prime numbers between 100 and 200

Q: How many prime numbers are there between 100 and 200?

A:

public class PrimeNumber {
private static boolean isPrimeNumber(int num){
int e = (int)Math.pow(num, 0.5) + 1;
for(int i = 2; i< e; i++){
/* detect if the number is divided by a integer */
if( (num%i) == 0)
return false;
}
return true;
}
}

public static int getPrimeNumberQuantity(int root, int floor){
if(floor < 2) return 0;

int q = 0;
for(int i=root; i < floor; i++){
if(isPrimeNumber(i)){
q++;
System.out.print(i + ", ");
}
}
System.out.println();
return q;

}

public static void main(String[] args) {

int m = PrimeNumber.getPrimeNumberQuantity(100, 200);
System.out.println("There are " + m + " prime numbers between 100 and 200.");
}
}


Result:

101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199,
There are 21 prime numbers between 100 and 200.

Thursday, May 31, 2007

Q1: multiplying rabbits

Question: A newly born rabbit is capable of reproducing at one month old (when it matures). Suppose the rabbit never dies, and it continues reproducing one new rabbit every month. So, when the rabbit is born, it has one member in its own family. After a month, it matures, and by the second month it adds a new born member to its family. In the third month, the rabbit produces another offspring; its first child also matures and will be ready to have an offspring in the next month. How many pairs of rabbits can be produced in a year from a single pair?

Answer: Let us write down the sequence of the rabbit number: 1, 1, 2, 3, 5, 8, 13 ... . It is a Fibonacci numbers.

The following code is the implementation in Java.

public class Fibonacci {
public static int getFibonacci(int n){
if(n < 0) return 0;
if((n == 0) || (n == 1)) return 1;
return getFibonacci(n-1) + getFibonacci(n-2);
}

public static void main(String[] args) {
for(int n=-1; n < 13; n++)
System.out.println(n + ": \t" + Fibonacci.getFibonacci(n));
}
}
}

The result:
-1: 0
0: 1
1: 1
2: 2
3: 3
4: 5
5: 8
6: 13
7: 21
8: 34
9: 55
10: 89
11: 144
12: 233