2016-09-15 57 views
1

我正在製作一個遊戲,我必須隨機生成一個4元素的int數組。我的問題是,所有數組元素的意思總是必須是一個整數。數組中的隨機數,其中平均值是整數

實施例: 陣列1 {4,2,3,7},陣列的平均值爲28,75這不是我尋找,

陣列2 {3,7,6 ,4},意思是20這是好的

現在我可以做一個循環,我檢查是否隨機生成的數字的平均值是一個整數,但似乎並不是一個有效的方式來做到這一點。

我工作的遊戲是知道它的人的平均總和。

+0

除非你能想出一個公式來證明手段並只生成那些特定的值,否則我不知道你會怎樣去完成它。實際上,你正在強化這種方法。 – Makoto

+2

選擇一個目標平均值,乘以4得到總和;然後選擇與該數字相加的隨機數(即選擇一個小於總和的隨機數,從總和中減去;重複)。 –

+5

_array 1 {4,2,3,7},數組的平均值是28,75 _...真的嗎?該數組的平均值或總和都不是28.75。 – GriffeyDog

回答

1

如果平均值是一個整數,然後總和必須整除4.

int[] n = new int[4]; 

選擇四個數字,並計算它們的總和:

int sum = 0; 
for (int i = 0; i < 4; ++i) { 
    sum += (n[i] = random.nextInt()); 
} 

計算的sum/4其餘部分:

int r = sum % 4; 

因此,您現在需要調整總和,以便sum % 4 == 0。你可以:

  • 減法r從任何陣列的元素:

    n[random.nextInt(4)] -= r; 
    
  • 或添加4 - r到任何元件:

    n[random.nextInt(4)] += 4 - r; 
    

Ideone demo

0

挑選目標平均值m和隨機整數n1,n2

您的排列[m-n1,m+n1,m-n2,m+n2]。沒有想過這種分配的屬性會是什麼,但它應該起作用。

0

我相信下面的函數做你想要的,給出你想要生成多少個值的參數(n),以及這些值的總和的上限是什麼(max)。

private static Random r = new Random(); 

public static int[] makeSet(int n, int max) { 
    // The next line guarantees the result is divisible by n 
    int currentMax = n * (1 + r.nextInt(max/n)); 
    Set<Integer> s = new HashSet<Integer>(); 

    // Generate a set of unique values between 0 and the currentMax, 
    // containing those bounds 
    s.add(0); 
    s.add(currentMax); 
    do { 
     s.add(r.nextInt(currentMax)); 
    } while(s.size() <= n); 
    Integer[] values = new Integer[n + 1]; 

    /* 
    * Convert to array, sort the results, and find successive 
    * differences. By construction, those differences WILL sum 
    * to the currentMax, which IS divisible by the number of 
    * values generated by differencing! 
    */ 

    s.toArray(values); 
    Arrays.sort(values); 
    int[] results = new int[n]; 
    for(int i = 0; i < n; ++i) { 
     results[i] = values[i+1] - values[i]; 
    } 
    return results; 
}