All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.luues.util.number.Sum Maven / Gradle / Ivy

There is a newer version: 1.3.0.5.RELEASE
Show newest version
package com.luues.util.number;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Sum {

    /**
     * 快速找出keys里面的数字相加的和等于kill的值的组合方式
     * @param keys 数值数组
     * @param kill 和
     * @return
     */
    public static List getNum(List keys, double kill) {
        int n = keys.size();
        int nbit = 1 << n;
        double in;
        List list = new ArrayList();
        for (int i = 0; i < nbit; i++) {
            in = 0;
            list.clear();
            for (int j = 0; j < n; j++) {
                int tmp = 1 << j; // 由0到n右移位
                if ((tmp & i) != 0) { // 与运算,同为1时才会是1
                    in += keys.get(j);
                    list.add(keys.get(j));
                }
            }
            if (in == kill)
                return list;
        }
        return list;
    }

    public static List> getNums(List> keys, double kill) {
        int n = keys.size();
        int nbit = 1 << n;
        double in;
        List> list = new ArrayList>();
        for (int i = 0; i < nbit; i++) {
            in = 0;
            list.clear();
            for (int j = 0; j < n; j++) {
                int tmp = 1 << j; // 由0到n右移位
                if ((tmp & i) != 0) { // 与运算,同为1时才会是1
                    Map map = keys.get(j);
                    for(Integer key : map.keySet()){
                        in += map.get(key);
                    }
                    list.add(keys.get(j));
                }
            }
            if (in == kill)
                return list;
        }
        return new ArrayList>();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy