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

生成小学加减口算题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 make() {
        Random r = new Random();
        Boolean[] methods = new Boolean[numberNum - 1];
        int[] nums = new int[numberNum];

        List 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


你可能感兴趣的:(Android,JAVA)