[英]How to partition a given list of numbers to N array where the sum of each array is closest to a specific number, M?
[英]How can I generate a sorted list of LogN unique numbers, where N is the given size of the array?
所以基本上我想生成隨機數並將它們放入給定大小 N 的列表中。
例如,這會生成一個排序列表,其中唯一數字的數量大致等於 N/2 我如何修改它以使唯一數字大致等於 LogN?
for (int i = 0; i < N; i++) {
list.add(i, list.get(i) + new Java.util.Random.nextInt(2);
}
如果您想要一個一致准確的log(n)
唯一數字列表,為什么不先生成它們呢? 您可以稍后填充數組。
import java.util.Random;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class RandomExample {
public static void main(String[] args) {
System.out.println(fillLogNUnique(100, 0, 100));
}
public static List <Integer> fillLogNUnique(final int n, final int lowLimit, final int highLimit) {
final Random random = ThreadLocalRandom.current();
// Assuming log base 2.0.
final int requiredUniqueCount = (int) Math.floor(Math.log(n) / Math.log(2.0));
final List <Integer> uniques = random
.ints(lowLimit, highLimit)
.limit(requiredUniqueCount)
.boxed()
.collect(Collectors.toList());
return IntStream
.range(0, n)
.map(x -> uniques.get(random.nextInt(uniques.size())))
.boxed()
.collect(Collectors.toList());
}
}
輸入是n
:所需隨機數的數量, lowLimit
:生成數字的下限和highLimit
:上限。
output 是:
[17, 29, 98, 17, 17, 29, 64, 64, 64, 17, 98, 98, 91, 17, 64, 50, 17, 50, 50, 64, 98, 91, 29, 50, 91, 50, 91, 98, 91, 98, 98, 29, 91, 91, 98, 64, 29, 98, 91, 50, 64, 50, 64, 17, 17, 50, 29, 29, 50, 50, 91, 50, 17, 17, 98, 64, 17, 98, 64, 17, 50, 17, 50, 50, 91, 50, 64, 91, 64, 91, 64, 64, 64, 91, 64, 64, 50, 50, 91, 50, 17, 17, 64, 98, 91, 17, 17, 17, 64, 50, 91, 29, 29, 91, 29, 50, 29, 91, 17, 91]
...恰好有 6,因為以 2 為底的log(100)
的 integer 值(下限)為 6。
請注意,此答案適用於 Java >= 8。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.