您的位置:首页 > 编程语言 > Java开发

生成小学加减口算题JAVA算法

2016-06-21 06:19 786 查看
生成小学加减口算题JAVA算法

package com.jianchi.fsp.generationchildrenarithmetic;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
* Created by fsp on 16-6-20.
*/
public class GenHelper implements Serializable {
//每道题的数字数,比如 2 , 3 ,4
public int numberNum;
//生成题的数量
public int createCount;
//运算类型
public String calculationMethod;
//数值范围
public int resultRange;

public List<String> make() {
Random r = new Random();
Boolean[] methods = new Boolean[numberNum - 1];
int[] nums = new int[numberNum];

List<String> l = new ArrayList<>();
for (int count = 0; count < createCount; count++) {
for (int i = 0; i < methods.length; i++) {
if (calculationMethod.equals("混合"))
methods[i] = r.nextInt(2) == 0;//生成 0 , 1, 0 为 true 为 加法
else if (calculationMethod.equals("加法"))
methods[i] = true;//生成 0 , 1
else if (calculationMethod.equals("减法"))
methods[i] = false;//生成 0 , 1
}
while (true) {
for (int i = 0; i < nums.length; i++) {
nums[i] = r.nextInt(resultRange + 1);
}
if (test(methods, nums)) {
l.add(String.valueOf(count + 1) + ". " + create(methods, nums));
break;
}
}
}
return l;
}

String create(Boolean[] methods, int[] nums) {
StringBuilder sb = new StringBuilder();
sb.append(nums[0]);
for (int i = 0; i < methods.length; i++) {
sb.append(" ").append(methods[i] ? "+" : "-").append(" ").append(nums[i + 1]);
}
sb.append(" ").append("=");
return sb.toString();
}

boolean test(Boolean[] methods, int[] nums) {
int d = nums[0];
for (int i = 0; i < methods.length; i++) {
d = methods[i] ? d + nums[i + 1] : d - nums[i + 1];
if (d < 0 || d > resultRange)
return false;
}
return true;
}

}


项目源码地址 https://code.csdn.net/do168/generationchildrenarithmetic
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息