[英]Is it possible to change range of random numbers?
我有一個在0-20范圍內生成的非重復隨機數數組
int[] numbers = {6,14,11,18,13};
現在,我想將這些數字轉換為0-10,並且我希望結果也為非重復。
可能嗎 ?
任何形式的建議將不勝感激。
將它們除以二是一個很好的解決方案,因為您具有相同的輸入大小,並且可以保持一致性:
對於[0; 10 [中的每個數字x],它可以來自[0; 20 [:2 * x和2 * x + 1]中的兩個數字。
對於10和11這樣的數字,它會給您相同的結果,但是誰在乎呢?
我想出了以下三種方法:
// divide by 2
Arrays.stream(numbers).map(x -> x / 2);
// subtract 10 from everything that's > 10
Arrays.stream(numbers).map(x -> x > 10 ? x - 10 : x);
// remove every number that's > 10
Arrays.stream(numbers).filter(x -> x < 10);
現在,我知道您不想重復數字,您應該通過調用distinct
刪除所有重復項。
如果隨機生成的數字大於10,則可以減去10。我知道這不是一個合適的解決方案,但肯定會為您服務。
如果您使用的是Java8,則可以使用以下代碼生成唯一的隨機數:
int[] rand = new Random().ints(0, 11).distinct().limit(5).toArray();
此代碼生成5個唯一的隨機數,范圍從0到10。
范圍0-20包含21個數字,0-10包含11個數字。 因此,導致數字均勻分布的唯一解決方案是僅取原始集合中0-10范圍內的數字,而舍棄11-20范圍內的數字。
您可以使用if條件在增強的for循環中迭代數組。由於從數字數組中獲取值,因此已經具有非重復值。您可以使用arraylist或任何其他數據結構存儲小於10的隨機數。
ArrayList<Integer> numberList = new ArrayList<>();
for(int number:numbers){
if(number<10){
numberList.add(number);
}
}
一種可能的解決方案是使用具有雙精度值的輔助數組。
接下來是算法。
coefficient = 10 / max
。 筆記
這就是它的代碼。
public static void main(String[] args) {
int[] numbers = { 6, 14, 11, 18, 13 };
// crate a new array with double values
double[] newNumbers = new double[numbers.length];
for (int i = 0; i < numbers.length; i++) {
newNumbers[i] = (double) numbers[i] / 2;
}
// get coefficient
double max = maxValue(newNumbers);
double coefficient = 10 / max;
// scale numbers
for (int i = 0; i < newNumbers.length; i++) {
newNumbers[i] = newNumbers[i] * coefficient;
}
int[] newIntNumbers = new int[newNumbers.length];
for (int i = 0; i < newNumbers.length; i++) {
newIntNumbers[i] = (int) Math.round(newNumbers[i]);
}
System.out.println(Arrays.toString(newNumbers));
System.out.println();
System.out.println(Arrays.toString(newIntNumbers));
}
private static double maxValue(double[] array) {
double max = Double.MIN_VALUE;
for (double num : array) {
max = Math.max(max, num);
}
return max;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.