[英]Set limit on sum of elements in Java Array
我正在嘗試創建一個數組,其中元素數從 3 隨機到 20,其中所有元素的總和為 45。我的問題是我無法設置限制,因此總和不超過 45 的值。
假設有4個元素:
我的當前輸出:15 21 19 26
我需要什么:7 11 23 4
public static void startGame(int[] cards) {
cards = new int[45];
Random rand = new Random();
int sum = 45;
int numStacks = 1;
numStacks = rand.nextInt(18) + 3;
for (int i = 0; i < numStacks; i++) {
cards[i] = (rand.nextInt(45) + 1) - numStacks;
sum += cards[i];
System.out.println(cards[i]);
}
}
你可以試試這個實現:
public static void startGame() {
Random rand = new Random();
int sum = 45;
int numStacks = 1;
numStacks = rand.nextInt(18) + 3;
int[] cards = new int[numStacks];
int upperBound = 20;
int lowerBound = 3;
if(lowerBound*numStacks > sum || upperBound*numStacks < sum) {
throw new IllegalArgumentException(String.format("Cannot make the stack - improper distribution for numStacks :%d upperBound: %d lowerBound: %d", numStacks, upperBound, lowerBound));
}
Arrays.fill(cards, lowerBound);
for (int i = 0; i < sum; i++)
{
boolean keepCalculating = true;
while(keepCalculating) {
int randomIndex = rand.nextInt(numStacks);
int nextValue = cards[randomIndex] + 1;
if(nextValue <= upperBound) {
cards[randomIndex] = nextValue;
keepCalculating = false;
}
}
}
System.out.printf("numStacks: %d%n", numStacks);
System.out.printf("cards: %s%n", Arrays.toString(cards));
System.out.printf("sum: %d%n", Arrays.stream(cards).sum());
}
cards
有結果。 示例運行:
numStacks: 7
cards: [7, 7, 5, 8, 5, 2, 11]
sum: 45
如果它不能創建堆棧,這里是它拋出的異常。
Exception in thread "main" java.lang.IllegalArgumentException: Cannot make the stack - improper distribution for numStacks :20 upperBound: 20 lowerBound: 3
如果您希望程序“始終”計算堆棧,則可以嘗試以下代碼:
public static void startGame() {
Random rand = new Random();
int sum = 45;
int numStacks = 1;
int maxNumberOfCards = 18;
int minNumberOfCards = 3;
int upperBound = 20;
int lowerBound = 3;
boolean calculateValidNumberOfStacks = true;
while(calculateValidNumberOfStacks) {
int checkVal = rand.nextInt(maxNumberOfCards) + minNumberOfCards;
if(lowerBound*checkVal < sum && upperBound*checkVal > sum) {
numStacks = checkVal;
calculateValidNumberOfStacks = false;
}
}
int[] cards = new int[numStacks];
Arrays.fill(cards, lowerBound);
for (int i = 0; i < sum; i++) {
boolean keepCalculating = true;
while(keepCalculating) {
int randomIndex = rand.nextInt(numStacks);
int nextValue = cards[randomIndex] + 1;
if(nextValue <= upperBound) {
cards[randomIndex] = nextValue;
keepCalculating = false;
}
}
}
System.out.printf("numStacks: %d%n", numStacks);
System.out.printf("cards: %s%n", Arrays.toString(cards));
System.out.printf("sum: %d%n", Arrays.stream(cards).sum());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.