【问题标题】:randomly find a combination from an array with duplicate elements and it's sum equal n从具有重复元素的数组中随机找到一个组合,它的总和等于 n
【发布时间】:2022-03-05 10:43:11
【问题描述】:

我如何从 array 中随机找到具有重复元素的组合,并且总和等于 n

示例

  • array[1, 2, 2, 3]n3
  • 答案是1+21+23
  • 如果randomSubsetSum(array, n) 是解决方案,那么randomSubsetSum([1,2,2,3], 3) 将返回1+21+23 之一。注意:1+2 的出现频率是3 的两倍
  • 真实场景:从题库中随机选择考试题

我发现了一些类似的问题和解决方案:

  1. 问:Finding all possible combinations of numbers to reach a given sum

    答:solution Asolution B

  2. 问:Rank and unrank integer partition with k parts

    答:solution C

缺陷

solution Asolution B 无法随机找到组合。 solution C 不允许重复元素。

我的 Java 解决方案

public List<Integer> randomSubsetSum(List<Integer> list, Integer n) {
    list.removeIf(e -> e > n);
    int maxSum = list.stream().reduce(0, Integer::sum);
    if (maxSum < n) {
        throw new RuntimeException("maxSum of list lower than n!");
    }
    if (maxSum == n) {
        return list;
    }
    final SecureRandom random = new SecureRandom();
    // maybe helpful, not important
    final Map<Integer, List<Integer>> map = list.stream().collect(Collectors.groupingBy(Function.identity()));
    final List<Integer> keys = new ArrayList<>(map.keySet());
    final List<Integer> answers = new ArrayList<>();
    int sum = 0;
    while (true) {
        int keyIndex = random.nextInt(keys.size());
        Integer key = keys.get(keyIndex);
        sum += key;

        // sum equal n
        if (sum == n) {
            List<Integer> elements = map.get(key);
            answers.add(elements.get(random.nextInt(elements.size())));
            break;
        }

        // sum below n
        if (sum < n) {
            List<Integer> elements = map.get(key);
            answers.add(elements.remove(random.nextInt(elements.size())));
            if (elements.isEmpty()) {
                map.remove(key);
                keys.remove(keyIndex);
            }
            continue;
        }

        // sum over n: exists (below  = n - sum + key) in keys
        int below = n - sum + key;
        if (CollectionUtils.isNotEmpty(map.get(below))) {
            List<Integer> elements = map.get(below);
            answers.add(elements.get(random.nextInt(elements.size())));
            break;
        }

        // sum over n: exists (over  = sum - n) in answers
        int over = sum - n;
        int answerIndex =
                IntStream.range(0, answers.size())
                        .filter(index -> answers.get(index) == over)
                        .findFirst().orElse(-1);
        if (answerIndex != -1) {
            List<Integer> elements = map.get(key);
            answers.set(answerIndex, elements.get(random.nextInt(elements.size())));
            break;
        }

        // Point A. BUG: may occur infinite loop

        // sum over n: rollback sum
        sum -= key;
        // sum over n: remove min element in answer
        Integer minIndex =
                IntStream.range(0, answers.size())
                        .boxed()
                        .min(Comparator.comparing(answers::get))
                        // never occurred
                        .orElseThrow(RuntimeException::new);
        Integer element = answers.remove((int) minIndex);
        sum -= element;
        if (keys.contains(element)) {
            map.get(element).add(element);
        } else {
            keys.add(element);
            map.put(element, new ArrayList<>(Collections.singleton(element)));
        }
    }
    return answers;
}

Point A,可能会发生无限循环(例如randomSubsetSum([3,4,8],13))或使用大量时间。如何修复此错误或有其他解决方案?

【问题讨论】:

  • 为什么在您的第一个示例中不允许使用[1 1 1]?数组的最大大小是多少?
  • a的所有元素都是非负数吗?
  • @CarySwoveland 我希望这是一个支持负数的解决方案。
  • @Damien 如果array[1,1,1] and n` 是3,那么数组本身就是唯一的答案。数组长度可能在数百甚至上千。
  • 我建议1+1+1 作为答案,而不是作为输入。抱歉,如果不清楚。

标签: java algorithm search subset subset-sum


【解决方案1】:

这是从解决方案 A 轻微改编而来的解决方案。

from random import random

def random_subset_sum(array, target):
    sign = 1
    array = sorted(array)
    if target < 0:
        array = reversed(array)
        sign = -1
    # Checkpoint A

    last_index = {0: [[-1,1]]}
    for i in range(len(array)):
        for s in list(last_index.keys()):
            new_s = s + array[i]
            total = 0
            for index, count in last_index[s]:
                total += count
            if 0 < (new_s - target) * sign:
                pass # Cannot lead to target
            elif new_s in last_index:
                last_index[new_s].append([i,total])
            else:
                last_index[new_s] = [[i, total]]
    # Checkpoint B

    answer_indexes = []
    last_choice = len(array)
    while -1 < last_choice:
        choice = None
        total = 0
        for i, count in last_index[target]:
            if last_choice <= i:
                break
            total += count
            if random() <= count / total:
                choice = i
        target -= array[choice]
        last_choice = choice
        if -1 < choice:
            answer_indexes.append(choice)

    return [array[i] for i in reversed(answer_indexes)]

【讨论】:

    猜你喜欢
    • 2016-07-03
    • 1970-01-01
    • 2013-01-12
    • 2013-02-24
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多