[英]Randomly filling a 2d boolean array with equal amounts of both values
我試圖找到一種方法,用布爾值隨機填充長度為n的2d數組。 如果n為偶數,則數組中每個值的數量必須相等。如果n為奇數,則每次附加值都必須為相同的布爾值(與哪一個無關)。 關於如何在Java中執行此操作的任何提示? 我目前正在改組使用相等數量的兩個值構成的數組,但這並不是真正隨機的,因為總會有n / 2(對於奇數ns為n / 2 + 1和n / 2-1)每個值。
有什么建議嗎?
根據您的要求,用所需的數量填充陣列,然后將其改組是一個很好的解決方案。
確保使用真正的隨機改組算法,例如Fisher-Yates改組,而不是“多次交換隨機對”方法。 如果您使用的是Collections.shuffle
或類似的東西,則無需擔心。
使Fisher-Yates隨機播放適應2D數組可能是最簡單的方法。
boolean[][] array = new boolean[rows][cols];
boolean alternating = false;
Random random = new Random();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int k = random.nextInt(i * cols + j + 1);
int swapRow = k / cols;
int swapCol = k % cols;
boolean tmp = array[swapRow][swapCol];
array[swapRow][swapCol] = alternating;
array[i][j] = tmp;
alternating = !alternating;
}
}
這幾乎是http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_.22inside-out.22_algorithm的逐字實現,只是我們在填充數組時會使用false和trues。
另一種方法可能是隨機分配您要放置下一個值的位置,而不是值本身。 您會提前確切知道要放置的每個值中有多少個。
就像是:
List<Integer> indicesList = IntStream.range(0, n * n).collect(Collectors.toList());
Collections.shuffle(indicesList);
indicesList.stream().forEach(n -> array[n % size][n / size] = (n % 2 == 0));
根據我的理解,這應該可以讓您完全隨機放置值,並且每個值的數量相等。
這是同事想出的一個真正簡單的解決方案。 在我看來,它確實可以正常工作並且是隨機的(請告訴我,如果不是,我對這種事情有很直覺),盡管這確實很丑陋。 與我想象的洗牌相比,這將是非常有效的。
public boolean[][] generateRandom2dBooleanArray(int length) {
int numFalses = (length*length)/2;
int numTrues = (length*length)/2;
if ((length*length)%2!=0) numTrues++;
boolean[][] array = new boolean[length][length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (Math.random() > 0.5) {//Or is it >= 0.5?
if (numTrues >= 0) {
array[i][j] = true;
numTrues--;
} else {
//Since boolean arrays are false by default, you could probably just break here to get the right anser, but...
array[i][j] = false;
numFalses--;
}
} else {
if (numFalses >= 0) {
array[i][j] = false;
numFalses--;
} else {
array[i][j] = true;
numTrues--;
}
}
}
}
}
return array;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.