生成四个整数,经四则运算得到二十四

来源:互联网 发布:淘宝应用开发 编辑:程序博客网 时间:2024/06/05 14:15

生成四个整数,经四则运算得到二十四

eg : 5 , 2 ,6 ,2
           24 = (5 - 2) * (6 + 2)
具体实现:
package com.cumt;import java.util.ArrayList;import java.util.List;import java.util.Random;public class ErShiSi {public static void main(String[] args) {Random random = new Random();int a = random.nextInt(10) + 1;List<Integer> list1 = new ArrayList<Integer>();list1 = getResult(a, 24);int b = random.nextInt(10) + 1;for (int i = 0; i < list1.size(); i++) {List<Integer> list2 = new ArrayList<Integer>();list2 = getResult(b, list1.get(i));//System.out.println(b + "" + list2);for (int j = 0; j < list2.size(); j++) {List<Integer> list3 = new ArrayList<Integer>();list3 = fenJie(list2.get(j));int len = list3.size();if(len > 0){int c = random.nextInt(len/2) + 1;//System.out.println("c=" + c);System.out.println("结果为:" + a + "," + b+ "," + list3.get(0) + "," + list3.get(2*c-1));}}}}public static List<Integer> getResult(int num, int number) {List<Integer> list = new ArrayList<Integer>();int before = num;int after = number;//将传入的参数将小的放在前面,大的放在后面if (num > number) {before = number;after = num;}//小的数通过加减乘除得到大的数过程的中间数int[] result = new int[4];result[0] = add(before, after);result[1] = sub(before, after);result[2] = plus(before, after);result[3] = chu(before, after);//将满足条件的数加入到list中for (int i = 0; i < result.length; i++) {if (result[i] != -1 && result[i] <= 100) {list.add(result[i]);}}return list;}public static int add(int add1, int add2) {if ((add2 - add1) > 0) {return add2 - add1;} else {return -1;}}public static int sub(int add1, int add2) {return add2 + add1;}public static int plus(int add1, int add2) {if (add2 % add1 == 0) {return add2 / add1;} else {return -1;}}public static int chu(int add1, int add2) {return add2 * add1;}public static List<Integer> fenJie(int num){List<Integer> list = new ArrayList<Integer>();Random random = new Random();int a = random.nextInt(10) + 1;if((num - a) <= 10 && (num - a) > 0){list.add(a);list.add(num-a);}if((num + a) <= 10 && (num + a) > 0){list.add(a);list.add(num+a);}if((num % a) == 0 && (num / a) <= 10){list.add(a);list.add(num/a);}if((num * a) <= 10){list.add(a);list.add(num*a);}//System.out.println(list);return list;}}


0 0