Commonly used algorithms thought

1 exhaustive algorithm

Exhaustive algorithm (Exhaustive Attack method) is the simplest algorithm. It depends on powerful computer
calculation ability to describe every possible situation, so as to achieve the purpose of solving the problem. Exhaustive algorithm efficiency is not high, but not suitable for some occasions obvious rules to follow.

  • The basic idea of the algorithm exhaustive
    exhaustive basic idea of the algorithm is to search for the correct answer from all possible cases, which performs the following steps:
  1. For a possible case, the result is calculated.
  2. Determine whether the results meet the requirements, if not under Step 1 to search for a likely scenario is executed; if they meet the requirements, then to find a correct answer.

When using the exhaustive algorithm that takes a clear answer to the question of scope, so that it can search for answers within a specified range. After the specified range, and the loop can be used to gradually conditional statement to verify the correctness of the candidate answer, the correct answer to give

import java.util.Scanner;

// 穷举法求解鸡兔同笼问题
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++) {
            j = 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("穷举法求解鸡兔同笼问题...");

        System.out.print("请输入头数:");
        Scanner input = new Scanner(System.in);
        int head = input.nextInt();
        System.out.print("请输入脚数:");
        int foot = input.nextInt();

        if (methodOfExhaustion(head, foot))
            System.out.println("鸡 " + chicken + " 只,兔 " + rabbit + " 只。");
        else
            System.out.println("无解。");
    }
}

Here Insert Picture Description

2 recursive algorithm

Recursive algorithm is commonly used algorithms thinking, it has been widely used in mathematical calculations and so on. Recursive algorithm where there is a clear formula for the law.

  • The basic idea of ​​recursive algorithm

Recursive algorithm represents a mode of thinking is rational, which is obtained based on the results of already existing data and relationships, and gradually derivation. Recursive algorithm implementation process is as follows:

  1. The known results and relationships, solving intermediate results.
  2. Determine whether the requirements, if not met, will continue to solve the intermediate results based on known results and relationships; if they meet the requirements, then to find a correct answer.

Recursive algorithm often requires the user to know the logical relationship between answers and questions. In many mathematical problems, with the explicit calculation formula can be followed, it is often possible using recursive algorithm.
Here Insert Picture Description

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("递推算法求解兔子产仔...");

        System.out.print("请输入时间:");
        Scanner scanner = new Scanner(System.in);
        int month = scanner.nextInt();
        System.out.printf("经过 %d 月,共能繁殖 %d 对兔子\n", month, fibonacci(month));
    }
}

递推算法求解兔子产仔...
请输入时间:12
经过 12 月,共能繁殖 144 对兔子

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("递归算法求解阶乘...");

        System.out.print("请输入一个整数:");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        System.out.printf("%d 的阶乘为 %d.\n", n, fact(n));
    }
}

递归算法求解阶乘...
请输入一个整数:12
12 的阶乘为 479001600.

Process finished with exit code 0

4 Divide and Conquer Algorithm

Here Insert Picture Description
Here Insert Picture Description

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;

        // 递归出口
        if (low + 1 == high) {
            if (coin[low] < coin[high]) {
                return low + 1;// 硬币序号比下标大 1
            } else {
                return high + 1;
            }
        }

        // 分解问题
        if ((high - low + 1) % 2 == 0) {// 当硬币个数为偶数
            for (int j = low; j <= low + (high - low) / 2; j++) {
                sum1 += coin[j];        // 前一半硬币的重量
            }
            for (int j = low + (high - low) / 2 + 1; j <= high; j++) {
                sum2 += coin[j];        // 后一半硬币的重量
            }
            if (sum1 > sum2)            // 假币在后一半中,在后一半中继续查找
                return falseCoin(coin, low + (high - low) / 2 + 1, high);
            else                        // 假币在前一半中,在前一半中继续查找
                return falseCoin(coin, low, low + (high - low) / 2);
        } else {                        // 当硬币个数为奇数
            for (int j = low; j <= low + (high - low) / 2 - 1; j++) {
                sum1 += coin[j];        // 前一半硬币的重量
            }
            for (int j = low + (high - low) / 2 + 1; j <= high; j++) {
                sum2 += coin[j];        // 后一半硬币的重量
            }
            if (sum1 > sum2) {          // 假币在后一半中,在后一半中继续查找
                return falseCoin(coin, low + (high - low) / 2 + 1, high);
            } else if (sum1 < sum2) {   // 假币在前一半中,在前一半中继续查找
                return falseCoin(coin, low, low + (high - low) / 2 - 1);
            } else {                    // 假币为中间那个硬币
                return low + (high - low) / 2 + 1;
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("分治算法求假币问题...");

        int[] coin = new int[MAXCOINNUM];
        System.out.print("请输入硬币总个数:");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        System.out.println("请逐个输入硬币重量(只能有一枚假币)...");
        for (int i = 0; i < n; i++) {
            coin[i] = scanner.nextInt();
        }
        System.out.printf("%d 个硬币中,第 %d 个硬币为假币。\n", n, falseCoin(coin, 0, n - 1));
    }
}

分治算法求假币问题...
请输入硬币总个数:13
请逐个输入硬币重量(只能有一枚假币)...
1 5 5 5 5 5 5 5 5 5 5 5 5
13 个硬币中,第 1 个硬币为假币。

Process finished with exit code 0

5 probabilistic algorithms

Here Insert Picture Description
Here Insert Picture Description

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(); // 产生 0~1 之间的一个随机数
            y = Math.random();
            // 点落在阴影区域
            if (x * x + y * y <= 1)
                sum++;
        }
        
        // π = 4 * 概率
        PI = 4.0 * sum / n;
        return PI;
    }

    public static void main(String[] args) {
        System.out.println("蒙特卡罗算法求 π ...");

        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入点的数量(数量越大,π 的值越精确):");
        int n = scanner.nextInt();
        double PI = MonteCarloPI(n);
        System.out.println("π = " + PI);
    }
}

蒙特卡罗算法求 π ...
请输入点的数量(数量越大,π 的值越精确):100000000
π = 3.14146396

Process finished with exit code 0
Published 50 original articles · won praise 38 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_42250302/article/details/104184784