# Common algorithm ideas

## 1 exhaustive algorithm

Exhaustive attack method is the simplest algorithm. It depends on the power of computer
Calculation ability, to exhaust every possible situation, so as to achieve the purpose of solving the problem. The efficiency of exhaustive algorithm is not high, but it is suitable for some cases where there is no obvious law to follow.

• The basic idea of exhaustive algorithm
The basic idea of exhaustive algorithm is to search for the correct answer from all possible situations. The steps are as follows:
1. For a possible case, calculate the result.
2. Determine whether the results meet the requirements. If not, perform step 1 to search for the next possible situation. If the requirements are met, it means finding a correct answer.

When using the exhaustive algorithm, we need to know the range of the answer to the problem, so that we can search the answer within the specified range. After specifying the scope, you can use circular statements and conditional statements to gradually verify the correctness of the candidate answers, so as to get the correct answers

```import java.util.Scanner;

// Solving the problem of chicken and rabbit in the same cage by exhaustive method
public class ChickenAndRabbit {
static int chicken, rabbit;
public static boolean methodOfExhaustion(int head, int foot) {
boolean result = false;

int i, j;
for (i = 0; i <= head; i++) {
if (i * 2 + j * 4 == foot) {
result = true;
chicken = i;
rabbit = j;
}
}

return result;
}

public static void main(String[] args) {
System.out.println("Solving the problem of chicken and rabbit in the same cage by exhaustive method...");

Scanner input = new Scanner(System.in);
System.out.print("Please enter the number of feet:");
int foot = input.nextInt();

System.out.println("chicken " + chicken + " Only rabbit " + rabbit + " Only.");
else
System.out.println("No solution.");
}
}
``` ## 2 recurrence method

Recursive algorithm is a very common algorithm idea, which has a wide range of applications in mathematical calculation. The recurrence algorithm is suitable for the situation with obvious formula law.

• Basic idea of recursive algorithm

Recursive algorithm is the representative of a rational thinking mode, which is based on the existing data and relations, and gradually derived the results. The execution process of recursive algorithm is as follows:

1. According to the known results and relations, the intermediate results are solved.
2. Determine whether the requirements are met, if not, continue to solve the intermediate results according to the known results and relations; if the requirements are met, it means to find a correct answer.

Recursive algorithms often need users to know the logical relationship between the answer and the question. In many mathematical problems, there are clear calculation formulas that can be followed, so the recurrence method can often be used to achieve. ```import java.util.Scanner;

public class RabbitLitter {
static int fibonacci(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}

public static void main(String[] args) {
System.out.println("Recursive algorithm for rabbit litter...");

Scanner scanner = new Scanner(System.in);
int month = scanner.nextInt();
System.out.printf("after %d Month, CO breeding %d For rabbits\n", month, fibonacci(month));
}
}

```
```Recursive algorithm for rabbit litter
After 12 months, 144 pairs of rabbits can be bred

Process finished with exit code 0
```

## 3 recursive algorithm

```import java.util.Scanner;

public class RecursiveAlgorithm {
static long fact(int n) {
if (n <= 1)
return 1;
else
return n * fact(n - 1);
}

public static void main(String[] args) {
System.out.println("Recursive algorithm for factorials...");

Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.printf("%d The factorial is %d.\n", n, fact(n));
}
}

```
```Recursive algorithm solving factorials
The factorial of 12 is 479001600

Process finished with exit code 0

```

## 4 divide and conquer algorithm  ```import java.util.Scanner;

public class DivideAndConquerAlgorithm {
static final int MAXCOINNUM = 30;

static int falseCoin(int[] coin, int low, int high) {
int sum1, sum2;
sum1 = sum2 = 0;

// Recursive export
if (low + 1 == high) {
if (coin[low] < coin[high]) {
return low + 1;// The coin number is 1 larger than the subscript
} else {
return high + 1;
}
}

// Decomposition problem
if ((high - low + 1) % 2 == 0) {// When the number of coins is even
for (int j = low; j <= low + (high - low) / 2; j++) {
sum1 += coin[j];        // The weight of the first half of the coin
}
for (int j = low + (high - low) / 2 + 1; j <= high; j++) {
sum2 += coin[j];        // The weight of the second half of the coin
}
if (sum1 > sum2)            // Counterfeit money in the second half, continue to search in the second half
return falseCoin(coin, low + (high - low) / 2 + 1, high);
else                        // Counterfeit money in the first half, continue to search in the first half
return falseCoin(coin, low, low + (high - low) / 2);
} else {                        // When the number of coins is odd
for (int j = low; j <= low + (high - low) / 2 - 1; j++) {
sum1 += coin[j];        // The weight of the first half of the coin
}
for (int j = low + (high - low) / 2 + 1; j <= high; j++) {
sum2 += coin[j];        // The weight of the second half of the coin
}
if (sum1 > sum2) {          // Counterfeit money in the second half, continue to search in the second half
return falseCoin(coin, low + (high - low) / 2 + 1, high);
} else if (sum1 < sum2) {   // Counterfeit money in the first half, continue to search in the first half
return falseCoin(coin, low, low + (high - low) / 2 - 1);
} else {                    // The counterfeit is the middle coin
return low + (high - low) / 2 + 1;
}
}
}

public static void main(String[] args) {
System.out.println("The problem of solving counterfeit money by divide and conquer algorithm...");

int[] coin = new int[MAXCOINNUM];
System.out.print("Please enter the total number of coins:");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
System.out.println("Please input the weight of coins one by one (only one counterfeit)...");
for (int i = 0; i < n; i++) {
coin[i] = scanner.nextInt();
}
System.out.printf("%d Of the coins, No %d Coins are counterfeit.\n", n, falseCoin(coin, 0, n - 1));
}
}

```
```Divide and conquer algorithm for counterfeit money
Please input the total number of coins: 13
Please input the weight of coins one by one (only one counterfeit coin is allowed)
1 5 5 5 5 5 5 5 5 5 5 5 5
The first of the 13 coins is counterfeit.

Process finished with exit code 0

```

## 5 probability algorithm  ```import java.util.Scanner;

public class ProbabilityAlgorithm {
static double MonteCarloPI(int n) {
double PI, x, y;
int sum = 0;
for (int i = 0; i < n; i++) {
x = Math.random(); // Generate a random number between 0 and 1
y = Math.random();
// Point falls in shadow area
if (x * x + y * y <= 1)
sum++;
}

// π = 4 * probability
PI = 4.0 * sum / n;
return PI;
}

public static void main(String[] args) {
System.out.println("Monte Carlo algorithm π ...");

Scanner scanner = new Scanner(System.in);
System.out.print("Please enter the number of points (the larger the number,π The more accurate the value of):");
int n = scanner.nextInt();
double PI = MonteCarloPI(n);
System.out.println("π = " + PI);
}
}

```
```Monte Carlo algorithm for π
Please enter the number of points (the larger the number, the more accurate the value of π): 100000000
π = 3.14146396

Process finished with exit code 0
```  46 original articles published, 34 praised, 10000 visitors+

Tags: Java

Posted on Wed, 05 Feb 2020 08:34:20 -0500 by Divine Winds