zoukankan      html  css  js  c++  java
  • 算法笔记_220:猜算式(Java)

    目录

    1 问题描述

    2 解决方案

     


    1 问题描述

    看下面的算式:

    □□ x □□ = □□ x □□□

    它表示:两个两位数相乘等于一个两位数乘以一个
    三位数。

    如果没有限定条件,这样的例子很多。

    但目前的限定是:这9个方块,表示1~9的9个数字
    ,不包含0。
    该算式中1至9的每个数字出现且只出现一次!

    比如:
    46 x 79 = 23 x 158
    54 x 69 = 27 x 138
    54 x 93 = 27 x 186
    .....

    请编程,输出所有可能的情况!

    注意:
    左边的两个乘数交换算同一方案,不要重复输出!
    不同方案的输出顺序不重要

     


    2 解决方案

     1 import java.util.ArrayList;
     2 
     3 public class Main {
     4     public static ArrayList<String> list = new ArrayList<String>();
     5     
     6     public void swap(int[] A, int i, int j) {
     7         int temp = A[i];
     8         A[i] = A[j];
     9         A[j] = temp;
    10     }
    11     
    12     public void check(int[] A) {
    13         int a = A[0] * 10 + A[1];
    14         int b = A[2] * 10 + A[3];
    15         int c = A[4] * 10 + A[5];
    16         int d = A[6] * 100 + A[7] * 10 + A[8];
    17         if(a > b) {
    18             int temp = a;
    19             a = b;
    20             b = temp;
    21         }
    22         if(a * b == c * d) {
    23             StringBuffer s = new StringBuffer("");
    24             s.append(a);
    25             s.append(" x ");
    26             s.append(b);
    27             s.append(" = ");
    28             s.append(c);
    29             s.append(" x ");
    30             s.append(d);
    31             if(!list.contains(s.toString()))
    32                 list.add(s.toString());
    33         }
    34     }
    35     
    36     public void dfs(int[] A, int step) {
    37         if(step == A.length) {
    38             check(A);
    39             return;
    40         } else {
    41             for(int i = step;i < A.length;i++) {
    42                 swap(A, i, step);
    43                 dfs(A, step + 1);
    44                 swap(A, i, step);
    45             }
    46         }
    47     }
    48     
    49     public static void main(String[] args) {
    50         Main test = new Main();
    51         int[] A = {1,2,3,4,5,6,7,8,9};
    52         test.dfs(A, 0);
    53         for(int i = 0;i < list.size();i++)
    54             System.out.println(list.get(i));
    55     }
    56 }

    运行结果:

    46 x 79 = 23 x 158
    54 x 69 = 27 x 138
    54 x 93 = 27 x 186
    58 x 67 = 29 x 134
    58 x 69 = 23 x 174
    58 x 73 = 29 x 146
    58 x 96 = 32 x 174
    63 x 74 = 18 x 259
    64 x 79 = 32 x 158
    73 x 96 = 12 x 584
    76 x 98 = 14 x 532
  • 相关阅读:
    python的with语句
    flask如何实现https以及自定义证书的制作
    flask及扩展源码解读
    加密的那些事
    SQLALchemy如何查询mysql某个区间内的数据
    集群设备之间的资源共享
    pycryptodom的源码安装
    github创建项目,并提交本地文件
    响应头里的"Last-Modified"值是怎么来的?
    SQL2005 数据库——查看索引
  • 原文地址:https://www.cnblogs.com/liuzhen1995/p/6892553.html
Copyright © 2011-2022 走看看