有没有一个有效的方法来生成n个随机整数的范围内有一个给定的总和或平均数?

4xy9mtcn  于 2021-06-30  发布在  Java
关注(0)|答案(4)|浏览(377)

有没有一种有效的方法来生成n个整数的随机组合-
每个整数都在区间内[ min , max ],
整数的和为 sum ,
整数可以以任何顺序出现(例如,随机顺序),并且
从满足其他要求的所有组合中随机均匀地选择组合?
对于整数必须按其值排序(而不是按任何顺序)的随机组合,是否有类似的算法?
(选择适当的组合,平均值为 mean 是特例,如果 sum = N * mean . 这个问题等价于生成一个均匀的随机分区 sum 分成n个部分,每个部分在间隔中[ min , max ]并按任意顺序或按其值排序(视情况而定)
我知道,对于以随机顺序出现的组合,这个问题可以通过以下方式解决(编辑[4月27日]:算法修改):
如果 N * max < sum 或者 N * min > sum ,没有解决方案。
如果 N * max == sum ,只有一个解决方案,其中 N 数字等于 max . 如果 N * min == sum ,只有一个解决方案,其中 N 数字等于 min .
使用smith和tromble中给出的算法(“从单位单纯形采样”,2004年)生成n个随机非负整数和 sum - N * min .
添加 min 以这种方式生成的每个数字。
如果任何数字大于 max ,转至步骤3。
但是,如果 max 远小于 sum . 例如,根据我的测试(带有一个实现上面涉及的特例) mean ),算法平均拒绝-
约1.6个样品,如果 N = 7, min = 3, max = 10, sum = 42 ,但是
约30.6个样品,如果 N = 20, min = 3, max = 10, sum = 120 .
有没有一种方法可以在满足上述要求的情况下,对这个算法进行修改,使其对大n有效?
编辑:
作为评论中建议的另一种选择,产生有效随机组合(满足除最后一个要求外的所有要求)的有效方法是:
计算 X ,可能给定的有效组合数 sum , min ,和 max .
选择 Y ,中的均匀随机整数 [0, X) .
转换(“取消银行”) Y 一个有效的组合。
但是,是否有一个公式来计算有效组合(或置换)的数量,是否有一种方法可以将整数转换为有效组合[编辑(4月28日):相同的排列而不是组合]。
编辑(4月27日):
在阅读了devroye的非均匀随机变量生成(1986)之后,我可以确认这是一个生成随机分区的问题。此外,第661页的练习2(特别是e部分)也与这个问题有关。
编辑(4月28日):
结果证明,我给出的算法是一致的,其中所涉及的整数是按随机顺序给出的,而不是按值排序。由于这两个问题都是大家普遍关心的问题,我修改了这个问题,以寻求这两个问题的规范答案。
下面的ruby代码可用于验证一致性的潜在解决方案(其中 algorithm(...) 是候选算法):

combos={}
permus={}
mn=0
mx=6
sum=12
for x in mn..mx
  for y in mn..mx
    for z in mn..mx
      if x+y+z==sum
        permus[[x,y,z]]=0
      end
      if x+y+z==sum and x<=y and y<=z
        combos[[x,y,z]]=0
      end
    end
  end
end

3000.times {|x|
 f=algorithm(3,sum,mn,mx)
 combos[f.sort]+=1
 permus[f]+=1
}
p combos
p permus

编辑(4月29日):重新添加了当前实现的ruby代码。
下面的代码示例是用ruby给出的,但我的问题与编程语言无关:

def posintwithsum(n, total)
    raise if n <= 0 or total <=0
    ls = [0]
    ret = []
    while ls.length < n
      c = 1+rand(total-1)
      found = false
      for j in 1...ls.length
        if ls[j] == c
          found = true
          break
        end
      end
      if found == false;ls.push(c);end
    end
    ls.sort!
    ls.push(total)
    for i in 1...ls.length
       ret.push(ls[i] - ls[i - 1])
    end
    return ret
end

def integersWithSum(n, total)
 raise if n <= 0 or total <=0
 ret = posintwithsum(n, total + n)
 for i in 0...ret.length
    ret[i] = ret[i] - 1
 end
 return ret
end

# Generate 100 valid samples

mn=3
mx=10
sum=42
n=7
100.times {
 while true
    pp=integersWithSum(n,sum-n*mn).map{|x| x+mn }
    if !pp.find{|x| x>mx }
      p pp; break # Output the sample and break
    end
 end
}
fiei3ece

fiei3ece1#

正如op所指出的,有效地拆借的能力非常强大。如果我们能够做到这一点,那么生成分区的统一分布可以分为三个步骤(重申op在问题中的布局):
计算长度为n的分区的总数m sum 使零件在范围内[ min , max ].
生成整数的均匀分布 [1, M] .
将步骤2中的每个整数解列到其各自的分区中。
下面,我们只关注生成第n个分区,因为在给定范围内生成整数的均匀分布有大量的信息。这里有一个简单的例子 C++ 解题算法,应该很容易翻译成其他语言(注意,我还没有弄清楚如何解题的组成情况(即顺序问题))。

std::vector<int> unRank(int n, int m, int myMax, int nth) {

    std::vector<int> z(m, 0);
    int count = 0;
    int j = 0;

    for (int i = 0; i < z.size(); ++i) {
        int temp = pCount(n - 1, m - 1, myMax);

        for (int r = n - m, k = myMax - 1;
             (count + temp) < nth && r > 0 && k; r -= m, --k) {

            count += temp;
            n = r;
            myMax = k;
            ++j;
            temp = pCount(n - 1, m - 1, myMax);
        }

        --m;
        --n;
        z[i] = j;
    }

    return z;
}

主力军 pCount 函数由下式给出:

int pCount(int n, int m, int myMax) {

    if (myMax * m < n) return 0;
    if (myMax * m == n) return 1;

    if (m < 2) return m;
    if (n < m) return 0;
    if (n <= m + 1) return 1;

    int niter = n / m;
    int count = 0;

    for (; niter--; n -= m, --myMax) {
        count += pCount(n - 1, m - 1, myMax);
    }

    return count;
}

这个函数是基于一个很好的答案:有没有一个有效的算法,整数分割与限制

ohfgkhjo

ohfgkhjo2#

我还没有测试过这个,所以这不是一个真正的答案,只是一些尝试,这是太长了,不能纳入一个评论。从一个满足前两个条件的数组开始玩,这样它仍然满足前两个条件,但随机性要大得多。
如果均值是整数,那么初始数组可以是[4,4,4。。。4] 或者[3,4,5,3,4,5。。。5,8,0]或者类似的简单的东西。如果平均值为4.5,请尝试[4,5,4,5。。。4, 5].
接下来选一对数字, num1 以及 num2 ,在数组中。可能第一个数字应该按顺序取,就像fisher-yates洗牌一样,第二个数字应该随机选取。将第一个数字按顺序排列可以确保每个数字至少拾取一次。
现在计算 max-num1 以及 num2-min . 这是从两个数字到另一个数字的距离 max 以及 min 边界。套 limit 两个距离中的较小者。这是允许的最大变化,不会使一个或另一个数字超出允许的限制。如果 limit 如果为零,则跳过这一对。
选取[1]范围内的随机整数, limit ]:叫它 change . 我从可选取范围中省略了0,因为它没有效果。测试可能会显示,你得到更好的随机性,包括它;我不确定。
现在开始 num1 <- num1 + change 以及 num2 <- num2 - change . 这不会影响平均值,并且数组的所有元素仍在所需边界内。
您需要至少遍历整个阵列一次。测试应该显示您是否需要多次运行它以获得足够的随机性。
eta:包含伪码

// Set up the array.
resultAry <- new array size N
for (i <- 0 to N-1)
  // More complex initial setup schemes are possible here.
  resultAry[i] <- mean
rof

// Munge the array entries.
for (ix1 <- 0 to N-1)  // ix1 steps through the array in order.

  // Pick second entry different from first.
  repeat
    ix2 <- random(0, N-1)
  until (ix2 != ix1)

  // Calculate size of allowed change.
  hiLimit <- max - resultAry[ix1]
  loLimit <- resultAry[ix2] - min
  limit <- minimum(hiLimit, loLimit)
  if (limit == 0)
    // No change possible so skip.
    continue loop with next ix1
  fi

  // Change the two entries keeping same mean.
  change <- random(1, limit)  // Or (0, limit) possibly.
  resultAry[ix1] <- resultAry[ix1] + change
  resultAry[ix2] <- resultAry[ix2] - change

rof

// Check array has been sufficiently munged.
if (resultAry not random enough)
  munge the array again
fi
flvtvl50

flvtvl503#

这是我的java解决方案。它功能齐全,包含两个发电机: PermutationPartitionGenerator 对于未排序的分区和 CombinationPartitionGenerator 对于已排序的分区。生成器也在类中实现 SmithTromblePartitionGenerator 作为比较。班级 SequentialEnumerator 按顺序枚举所有可能的分区(未排序或已排序,取决于参数)。我已经为所有这些生成器添加了全面的测试(包括您的测试用例)。实现在很大程度上是可以自我解释的。如果你有任何问题,我会在几天内回答。

import java.util.Random;
import java.util.function.Supplier;

public abstract class PartitionGenerator implements Supplier<int[]>{
    public static final Random rand = new Random();
    protected final int numberCount;
    protected final int min;
    protected final int range;
    protected final int sum; // shifted sum
    protected final boolean sorted;

    protected PartitionGenerator(int numberCount, int min, int max, int sum, boolean sorted) {
        if (numberCount <= 0)
            throw new IllegalArgumentException("Number count should be positive");
        this.numberCount = numberCount;
        this.min = min;
        range = max - min;
        if (range < 0)
            throw new IllegalArgumentException("min > max");
        sum -= numberCount * min;
        if (sum < 0)
            throw new IllegalArgumentException("Sum is too small");
        if (numberCount * range < sum)
            throw new IllegalArgumentException("Sum is too large");
        this.sum = sum;
        this.sorted = sorted;
    }

    // Whether this generator returns sorted arrays (i.e. combinations)
    public final boolean isSorted() {
        return sorted;
    }

    public interface GeneratorFactory {
        PartitionGenerator create(int numberCount, int min, int max, int sum);
    }
}

import java.math.BigInteger;

// Permutations with repetition (i.e. unsorted vectors) with given sum
public class PermutationPartitionGenerator extends PartitionGenerator {
    private final double[][] distributionTable;

    public PermutationPartitionGenerator(int numberCount, int min, int max, int sum) {
        super(numberCount, min, max, sum, false);
        distributionTable = calculateSolutionCountTable();
    }

    private double[][] calculateSolutionCountTable() {
        double[][] table = new double[numberCount + 1][sum + 1];
        BigInteger[] a = new BigInteger[sum + 1];
        BigInteger[] b = new BigInteger[sum + 1];
        for (int i = 1; i <= sum; i++)
            a[i] = BigInteger.ZERO;
        a[0] = BigInteger.ONE;
        table[0][0] = 1.0;
        for (int n = 1; n <= numberCount; n++) {
            double[] t = table[n];
            for (int s = 0; s <= sum; s++) {
                BigInteger z = BigInteger.ZERO;
                for (int i = Math.max(0, s - range); i <= s; i++)
                    z = z.add(a[i]);
                b[s] = z;
                t[s] = z.doubleValue();
            }
            // swap a and b
            BigInteger[] c = b;
            b = a;
            a = c;
        }
        return table;
    }

    @Override
    public int[] get() {
        int[] p = new int[numberCount];
        int s = sum; // current sum
        for (int i = numberCount - 1; i >= 0; i--) {
            double t = rand.nextDouble() * distributionTable[i + 1][s];
            double[] tableRow = distributionTable[i];
            int oldSum = s;
            // lowerBound is introduced only for safety, it shouldn't be crossed 
            int lowerBound = s - range;
            if (lowerBound < 0)
                lowerBound = 0;
            s++;
            do
                t -= tableRow[--s];
            // s can be equal to lowerBound here with t > 0 only due to imprecise subtraction
            while (t > 0 && s > lowerBound);
            p[i] = min + (oldSum - s);
        }
        assert s == 0;
        return p;
    }

    public static final GeneratorFactory factory = (numberCount, min, max,sum) ->
        new PermutationPartitionGenerator(numberCount, min, max, sum);
}

import java.math.BigInteger;

// Combinations with repetition (i.e. sorted vectors) with given sum 
public class CombinationPartitionGenerator extends PartitionGenerator {
    private final double[][][] distributionTable;

    public CombinationPartitionGenerator(int numberCount, int min, int max, int sum) {
        super(numberCount, min, max, sum, true);
        distributionTable = calculateSolutionCountTable();
    }

    private double[][][] calculateSolutionCountTable() {
        double[][][] table = new double[numberCount + 1][range + 1][sum + 1];
        BigInteger[][] a = new BigInteger[range + 1][sum + 1];
        BigInteger[][] b = new BigInteger[range + 1][sum + 1];
        double[][] t = table[0];
        for (int m = 0; m <= range; m++) {
            a[m][0] = BigInteger.ONE;
            t[m][0] = 1.0;
            for (int s = 1; s <= sum; s++) {
                a[m][s] = BigInteger.ZERO;
                t[m][s] = 0.0;
            }
        }
        for (int n = 1; n <= numberCount; n++) {
            t = table[n];
            for (int m = 0; m <= range; m++)
                for (int s = 0; s <= sum; s++) {
                    BigInteger z;
                    if (m == 0)
                        z = a[0][s];
                    else {
                        z = b[m - 1][s];
                        if (m <= s)
                            z = z.add(a[m][s - m]);
                    }
                    b[m][s] = z;
                    t[m][s] = z.doubleValue();
                }
            // swap a and b
            BigInteger[][] c = b;
            b = a;
            a = c;
        }
        return table;
    }

    @Override
    public int[] get() {
        int[] p = new int[numberCount];
        int m = range; // current max
        int s = sum; // current sum
        for (int i = numberCount - 1; i >= 0; i--) {
            double t = rand.nextDouble() * distributionTable[i + 1][m][s];
            double[][] tableCut = distributionTable[i];
            if (s < m)
                m = s;
            s -= m;
            while (true) {
                t -= tableCut[m][s];
                // m can be 0 here with t > 0 only due to imprecise subtraction
                if (t <= 0 || m == 0)
                    break;
                m--;
                s++;
            }
            p[i] = min + m;
        }
        assert s == 0;
        return p;
    }

    public static final GeneratorFactory factory = (numberCount, min, max, sum) ->
        new CombinationPartitionGenerator(numberCount, min, max, sum);
}

import java.util.*;

public class SmithTromblePartitionGenerator extends PartitionGenerator {
    public SmithTromblePartitionGenerator(int numberCount, int min, int max, int sum) {
        super(numberCount, min, max, sum, false);
    }

    @Override
    public int[] get() {
        List<Integer> ls = new ArrayList<>(numberCount + 1);
        int[] ret = new int[numberCount];
        int increasedSum = sum + numberCount;
        while (true) {
            ls.add(0);
            while (ls.size() < numberCount) {
                int c = 1 + rand.nextInt(increasedSum - 1);
                if (!ls.contains(c))
                    ls.add(c);
            }
            Collections.sort(ls);
            ls.add(increasedSum);
            boolean good = true;
            for (int i = 0; i < numberCount; i++) {
                int x = ls.get(i + 1) - ls.get(i) - 1;
                if (x > range) {
                    good = false;
                    break;
                }
                ret[i] = x;
            }
            if (good) {
                for (int i = 0; i < numberCount; i++)
                    ret[i] += min;
                return ret;
            }
            ls.clear();
        }
    }

    public static final GeneratorFactory factory = (numberCount, min, max, sum) ->
        new SmithTromblePartitionGenerator(numberCount, min, max, sum);
}

import java.util.Arrays;

// Enumerates all partitions with given parameters
public class SequentialEnumerator extends PartitionGenerator {
    private final int max;
    private final int[] p;
    private boolean finished;

    public SequentialEnumerator(int numberCount, int min, int max, int sum, boolean sorted) {
        super(numberCount, min, max, sum, sorted);
        this.max = max;
        p = new int[numberCount];
        startOver();
    }

    private void startOver() {
        finished = false;
        int unshiftedSum = sum + numberCount * min;
        fillMinimal(0, Math.max(min, unshiftedSum - (numberCount - 1) * max), unshiftedSum);
    }

    private void fillMinimal(int beginIndex, int minValue, int fillSum) {
        int fillRange = max - minValue;
        if (fillRange == 0)
            Arrays.fill(p, beginIndex, numberCount, max);
        else {
            int fillCount = numberCount - beginIndex;
            fillSum -= fillCount * minValue;
            int maxCount = fillSum / fillRange;
            int maxStartIndex = numberCount - maxCount;
            Arrays.fill(p, maxStartIndex, numberCount, max);
            fillSum -= maxCount * fillRange;
            Arrays.fill(p, beginIndex, maxStartIndex, minValue);
            if (fillSum != 0)
                p[maxStartIndex - 1] = minValue + fillSum;
        }
    }

    @Override
    public int[] get() { // returns null when there is no more partition, then starts over
        if (finished) {
            startOver();
            return null;
        }
        int[] pCopy = p.clone();
        if (numberCount > 1) {
            int i = numberCount;
            int s = p[--i];
            while (i > 0) {
                int x = p[--i];
                if (x == max) {
                    s += x;
                    continue;
                }
                x++;
                s--;
                int minRest = sorted ? x : min;
                if (s < minRest * (numberCount - i - 1)) {
                    s += x;
                    continue;
                }
                p[i++]++;
                fillMinimal(i, minRest, s);
                return pCopy;
            }
        }
        finished = true;
        return pCopy;
    }

    public static final GeneratorFactory permutationFactory = (numberCount, min, max, sum) ->
        new SequentialEnumerator(numberCount, min, max, sum, false);
    public static final GeneratorFactory combinationFactory = (numberCount, min, max, sum) ->
        new SequentialEnumerator(numberCount, min, max, sum, true);
}

import java.util.*;
import java.util.function.BiConsumer;
import PartitionGenerator.GeneratorFactory;

public class Test {
    private final int numberCount;
    private final int min;
    private final int max;
    private final int sum;
    private final int repeatCount;
    private final BiConsumer<PartitionGenerator, Test> procedure;

    public Test(int numberCount, int min, int max, int sum, int repeatCount,
            BiConsumer<PartitionGenerator, Test> procedure) {
        this.numberCount = numberCount;
        this.min = min;
        this.max = max;
        this.sum = sum;
        this.repeatCount = repeatCount;
        this.procedure = procedure;
    }

    @Override
    public String toString() {
        return String.format("=== %d numbers from [%d, %d] with sum %d, %d iterations ===",
                numberCount, min, max, sum, repeatCount);
    }

    private static class GeneratedVector {
        final int[] v;

        GeneratedVector(int[] vect) {
            v = vect;
        }

        @Override
        public int hashCode() {
            return Arrays.hashCode(v);
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            return Arrays.equals(v, ((GeneratedVector)obj).v);
        }

        @Override
        public String toString() {
            return Arrays.toString(v);
        }
    }

    private static final Comparator<Map.Entry<GeneratedVector, Integer>> lexicographical = (e1, e2) -> {
        int[] v1 = e1.getKey().v;
        int[] v2 = e2.getKey().v;
        int len = v1.length;
        int d = len - v2.length;
        if (d != 0)
            return d;
        for (int i = 0; i < len; i++) {
            d = v1[i] - v2[i];
            if (d != 0)
                return d;
        }
        return 0;
    };

    private static final Comparator<Map.Entry<GeneratedVector, Integer>> byCount =
            Comparator.<Map.Entry<GeneratedVector, Integer>>comparingInt(Map.Entry::getValue)
            .thenComparing(lexicographical);

    public static int SHOW_MISSING_LIMIT = 10;

    private static void checkMissingPartitions(Map<GeneratedVector, Integer> map, PartitionGenerator reference) {
        int missingCount = 0;
        while (true) {
            int[] v = reference.get();
            if (v == null)
                break;
            GeneratedVector gv = new GeneratedVector(v);
            if (!map.containsKey(gv)) {
                if (missingCount == 0)
                    System.out.println(" Missing:");
                if (++missingCount > SHOW_MISSING_LIMIT) {
                    System.out.println("  . . .");
                    break;
                }
                System.out.println(gv);
            }
        }
    }

    public static final BiConsumer<PartitionGenerator, Test> distributionTest(boolean sortByCount) {
        return (PartitionGenerator gen, Test test) -> {
            System.out.print("\n" + getName(gen) + "\n\n");
            Map<GeneratedVector, Integer> combos = new HashMap<>();
            // There's no point of checking permus for sorted generators
            // because they are the same as combos for them
            Map<GeneratedVector, Integer> permus = gen.isSorted() ? null : new HashMap<>();
            for (int i = 0; i < test.repeatCount; i++) {
                int[] v = gen.get();
                if (v == null && gen instanceof SequentialEnumerator)
                    break;
                if (permus != null) {
                    permus.merge(new GeneratedVector(v), 1, Integer::sum);
                    v = v.clone();
                    Arrays.sort(v);
                }
                combos.merge(new GeneratedVector(v), 1, Integer::sum);
            }
            Set<Map.Entry<GeneratedVector, Integer>> sortedEntries = new TreeSet<>(
                    sortByCount ? byCount : lexicographical);
            System.out.println("Combos" + (gen.isSorted() ? ":" : " (don't have to be uniform):"));
            sortedEntries.addAll(combos.entrySet());
            for (Map.Entry<GeneratedVector, Integer> e : sortedEntries)
                System.out.println(e);
            checkMissingPartitions(combos, test.getGenerator(SequentialEnumerator.combinationFactory));
            if (permus != null) {
                System.out.println("\nPermus:");
                sortedEntries.clear();
                sortedEntries.addAll(permus.entrySet());
                for (Map.Entry<GeneratedVector, Integer> e : sortedEntries)
                    System.out.println(e);
                checkMissingPartitions(permus, test.getGenerator(SequentialEnumerator.permutationFactory));
            }
        };
    }

    public static final BiConsumer<PartitionGenerator, Test> correctnessTest =
        (PartitionGenerator gen, Test test) -> {
        String genName = getName(gen);
        for (int i = 0; i < test.repeatCount; i++) {
            int[] v = gen.get();
            if (v == null && gen instanceof SequentialEnumerator)
                v = gen.get();
            if (v.length != test.numberCount)
                throw new RuntimeException(genName + ": array of wrong length");
            int s = 0;
            if (gen.isSorted()) {
                if (v[0] < test.min || v[v.length - 1] > test.max)
                    throw new RuntimeException(genName + ": generated number is out of range");
                int prev = test.min;
                for (int x : v) {
                    if (x < prev)
                        throw new RuntimeException(genName + ": unsorted array");
                    s += x;
                    prev = x;
                }
            } else
                for (int x : v) {
                    if (x < test.min || x > test.max)
                        throw new RuntimeException(genName + ": generated number is out of range");
                    s += x;
                }
            if (s != test.sum)
                throw new RuntimeException(genName + ": wrong sum");
        }
        System.out.format("%30s :   correctness test passed%n", genName);
    };

    public static final BiConsumer<PartitionGenerator, Test> performanceTest =
        (PartitionGenerator gen, Test test) -> {
        long time = System.nanoTime();
        for (int i = 0; i < test.repeatCount; i++)
            gen.get();
        time = System.nanoTime() - time;
        System.out.format("%30s : %8.3f s %10.0f ns/test%n", getName(gen), time * 1e-9, time * 1.0 / test.repeatCount);
    };

    public PartitionGenerator getGenerator(GeneratorFactory factory) {
        return factory.create(numberCount, min, max, sum);
    }

    public static String getName(PartitionGenerator gen) {
        String name = gen.getClass().getSimpleName();
        if (gen instanceof SequentialEnumerator)
            return (gen.isSorted() ? "Sorted " : "Unsorted ") + name;
        else
            return name;
    }

    public static GeneratorFactory[] factories = { SmithTromblePartitionGenerator.factory,
            PermutationPartitionGenerator.factory, CombinationPartitionGenerator.factory,
            SequentialEnumerator.permutationFactory, SequentialEnumerator.combinationFactory };

    public static void main(String[] args) {
        Test[] tests = {
                            new Test(3, 0, 3, 5, 3_000, distributionTest(false)),
                            new Test(3, 0, 6, 12, 3_000, distributionTest(true)),
                            new Test(50, -10, 20, 70, 2_000, correctnessTest),
                            new Test(7, 3, 10, 42, 1_000_000, performanceTest),
                            new Test(20, 3, 10, 120, 100_000, performanceTest)
                       };
        for (Test t : tests) {
            System.out.println(t);
            for (GeneratorFactory factory : factories) {
                PartitionGenerator candidate = t.getGenerator(factory);
                t.procedure.accept(candidate, t);
            }
            System.out.println();
        }
    }
}

你可以在ideone上试试这个。

r7s23pms

r7s23pms4#

这是约翰·麦克莱恩的置换分区生成器的算法,在本页的另一个答案中。它有两个阶段,即设置阶段和采样阶段,并生成 n 随机数[ min , max ]与总和 sum ,其中数字以随机顺序列出。
设置阶段:首先,使用以下公式构建解决方案表( t(y, x) 哪里 y 在[0, n ]以及 x 在[0, sum - n * min ]):
如果j==0,t(0,j)=1;否则为0
t(i,j)=t(i-1,j)+t(i-1,j-1)+…+t(i-1,j-(最大-最小))
这里,t(y,x)存储 y 数字(在适当的范围内)将相等 x . 这个概率是相对于所有t(y,x)具有相同的 y .
采样阶段:这里我们生成 n 数字。套 ssum - n * min ,然后针对每个位置 i ,从 n - 1 并向后工作到0:
v 到[0,t(i+1,s)中的随机整数。
rmin .
从中减去t(i,s) v .
v 保持0或更大,从中减去t(i,s-1) v ,将1添加到 r ,并从中减去1 s .
位置上的数字 i 在示例中设置为 r .
编辑:
通过对上述算法的细微更改,可以让每个随机数使用单独的范围,而不是对所有随机数使用相同的范围:
每个位置的随机数 i ∈ [0, n )具有最小值min(i)和最大值max(i)。
adjsum = sum - σ最小值(i)。
设置阶段:首先,使用以下公式构建解决方案表( t(y, x) 哪里 y 在[0, n ]以及 x 在[0, adjsum ]):
如果j==0,t(0,j)=1;否则为0
t(i,j)=t(i-1,j)+t(i-1,j-1)+…+t(i-1,j-(最大值(i-1)-最小值(i-1)))
采样阶段与之前完全相同,只是我们设置了 sadjsum (而不是 sum - n * min )并设置 r 至min(i)(而不是 min ).
编辑:
对于john mcclane的combinationpartitiongenerator,设置和采样阶段如下。
设置阶段:首先,使用以下公式构建解决方案表( t(z, y, x) 哪里 z 在[0, n ], y 在[0, max - min ],和 x 在[0, sum - n * min ]):
如果k==0,t(0,j,k)=1;否则为0
t(i,0,k)=t(i-1,0,k)
t(i,j,k)=t(i,j-1,k)+t(i-1,j,k-j)
采样阶段:这里我们生成 n 数字。套 ssum - n * min 以及 mrangemax - min ,然后针对每个位置 i ,从 n - 1 并向后工作到0:
v 到[0,t(i+1,m范围,s)中的随机整数。
mrange 至最小值( mrange , s )
减法 mranges .
rmin + mrange .
减去t( i , mrange , s )从 v .
v 保持0或更大,将1添加到 s ,从中减去1 r 一个来自 mrange ,然后减去t( i , mrange , s )从 v .
位置上的数字 i 在示例中设置为 r .

相关问题