搜索算法Java - Elevator递归函数 - 与基本案例的斗争

时间:2018-01-17 15:21:13

标签: java search recursion

升力通常在空间(人)和载荷(kgs)方面都有限。想象一下,我们有 一个小型电梯,最多可以运送6人,最大负载为 500公斤。假设13个人正在等待以下权重:10,30,40,41,80,90,50,55, 92,66,82,62和70kg。编写一个递归程序,找到一组没有的人 超过最大容量,但具有最大可能负载(kg)。 (提示:有效 解决方案超过470公斤)

public static void main (String[] Args)
{

     ArrayList<Integer> s = new ArrayList<Integer>(); //List of unexplored
     int[] weight0 = { 10, 30, 40, 41, 80, 90, 50, 55, 92, 66, 82, 62,70}; //Initial state
     int target = 500; //Goal state
     System.out.println(liftGroup(weight0,0,target, s) + " way(s)"); //Recursive function

}

static int liftGroup (int[] weight,int c,int target, ArrayList<Integer> s){

    assert weight != null : "array should be initialized";
    assert c >= 0 && c <= weight.length;
    assert s != null : "ArrayList should be initialized";
    int sumOfUntried = 0;

    if (c > 6) {
        showSoulution(s);
        return 1;
    }
    else if (target < 0) {
        return 0;
    }
    else if (c >= weight.length) {  //that's okay? 
        return 0;
    }

    int min = weight[c];
    for (int i = c; i < weight.length; i++) {
        sumOfUntried += weight[i];
        if(weight[i]<min)
            min=weight[i];
    }

    if(min>target) // If you find one BIG fatty 
    {
        return 0;
    }
    if (sumOfUntried > target) { //Correct
        return 0;
    }
    else {
        s.add(weight[c]);
        int with = liftGroup(weight, c + 1, target - weight[c], s);
        s.remove(s.size() - 1);
        int without = liftGroup(weight, c + 1, target, s);
        return with + without;
    }
}

/*
* Prints the ArrayList with the solution
*/
private static void showSoulution(ArrayList<Integer> s) 
{

    assert s != null : "ArrayList should be initialized";
    System.out.println("Solution: " + s);

}}

我的问题是理解并使用基本情况:

  • 当人数不超过最大限度时。你有一个解决方案。
  • 但我如何遵守这两个目标呢?

1 个答案:

答案 0 :(得分:0)

这是一个混乱的解决方案*,我将其与来自hereherehere的信用卡一起投放。

基本上,对于每次迭代,将组合及其总和添加到HashMap

然后按值对HashMap进行排序。

最后,循环浏览HashMap并找到与目标最接近的值。

static Map<String, Integer> myMap = new HashMap<>();

static void combinationUtil(int arr[], int data[], int start,
        int end, int index, int r) {
    int sum = 0;
    StringBuilder sb = new StringBuilder();
    if (index == r) {
        for (int j = 0; j < r; j++) {

            sb.append(data[j]).append(",");
            sum += data[j];

            System.out.print(data[j] + " ");
        }
        myMap.put(sb.toString(), sum);
        sum = 0;
        sb = new StringBuilder();
        System.out.println("");
        return;
    }
    for (int i = start; i <= end && end - i + 1 >= r - index; i++) {
        data[index] = arr[i];
        combinationUtil(arr, data, i + 1, end, index + 1, r);
    }
}

static void printCombination(int arr[], int n, int r) {
    int data[] = new int[r];
    combinationUtil(arr, data, 0, n - 1, 0, r);
}

public static void main(String[] args) {
    int arr[] = {10, 30, 40, 41, 80, 90, 50, 55, 92, 66, 82, 62, 70};
    int r = 6; //as you have 6 people
    int n = arr.length;
    printCombination(arr, n, r);
    myMap = sortByValue(myMap);
    System.out.println(searchClosest(myMap, 500)); //500 is the target
}

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    return map.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByValue(/*Collections.reverseOrder()*/))
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (e1, e2) -> e1,
                    LinkedHashMap::new
            ));
}

public static String searchClosest(Map<String, Integer> map, int value) {
    double minDistance = Double.MAX_VALUE;
    String bestString = null;

    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        double distance = Math.abs(entry.getValue() - value);
        if (distance < minDistance) {
            minDistance = distance;
            bestString = entry.getKey();
        }
    }
    return bestString;
}

这里有一个online示例int arr[] = {1,2,3,4,5,6,7,8};,排列设置为3,目标为14。

*这只是通过一次或两次小修改复制/粘贴,但更像是如何获得解决方案