package cn.com.qmth.examcloud.core.questions.base;

import java.util.ArrayList;
import java.util.List;

public class CombinationUtils {

    private static List<String> combineList = new ArrayList<>();

    public static List<Integer> combiantion(List<Integer> numbers, int needNum, int needNestNum) {
        List<Integer> returnList = new ArrayList<>();
        if (numbers == null || numbers.size() == 0) {
            return returnList;
        }

        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= numbers.size(); i++) {
            combine(numbers, 0, i, list);
        }

        for (String str : combineList) {
            returnList = sum(str, needNum, needNestNum);
            if (returnList.size() > 0) {
                break;
            }
        }

        return returnList;
    }

    // 从字符数组中第begin个字符开始挑选number个字符加入list中
    private static void combine(List<Integer> cs, int begin, int number, List<Integer> list) {
        if (number == 0) {
            combineList.add(list.toString());
            return;
        }
        if (begin == cs.size()) {
            return;
        }
        list.add(cs.get(begin));
        combine(cs, begin + 1, number - 1, list);
        list.remove(cs.get(begin));
        combine(cs, begin + 1, number, list);
    }

    private static List<Integer> sum(String str, int needNum, int needNestNum) {
        List<Integer> list = new ArrayList<>();
        List<Integer> tempList = new ArrayList<>();
        String[] strs = str.replaceAll("\\[", "").replaceAll("\\]", "").split(",");
        Integer sum = 0;
        if (strs.length == needNestNum) {
            for (String intStr : strs) {
                Integer val = Integer.parseInt(intStr.trim());

                sum += val;

                tempList.add(val);
            }
            if (sum <= needNum) {
                list.addAll(tempList);
            }
        }

        return list;
    }

}