今天突然想到一個問題,微信紅包的金額怎麼隨機出來,或者拼多多那個砍價,怎麼隨機出來,他們都有兩個共同點,一個是固定的金額總數,一個就是參與的人數,只要這麼多人蔘與了,這些人獲取的數的總和.肯定是那個金額.
後面想了一下,這個問題,可不可以先理解爲一個整數a,拆分爲n個整數之和,如果能拆分,那小數點那個就好處理了.直接上我的demo,可能寫得不夠好,但是基本功能還是實現了,如果有更好的辦法,希望告訴我一下.
package com.xd.cps;
import java.util.Arrays;
import java.util.Random;
public class Test {
public static void main(String[] args)throws Exception{
// 這裏隨機生成100次試試看看結果.
for(int i=0;i<100;i++){
System.out.println(Arrays.toString(randomStr(6,10)));
System.out.println("----------------");
}
}
/**
* @param L 一個整數
* @param n 分成幾個整數
* @return 數組集合
*/
public static int[] random(int L, int n){
int[] result = new int[n];
// 這裏簡單判斷,可以實際修改。
if(L/n<1){
return result;
}
int sum = 0; // 已生成的隨機數總和
for(int i=0; i<n-1; i++){
int temp = L - sum;
int random = getRandom(temp,i,n);
System.out.println( "整數L=" + L + " 已生成的隨機數總和sum=" + sum + " 剩餘temp=" + temp + " 生成的隨機數random=" + random );
result[i] = random;
sum += random;
}
result[n-1] = L - sum;
return result;
}
/**
* 這個是個簡單的方式生成小數點的數據.
* @param L
* @param n
* @return
*/
public static double[] randomStr(int L, int n){
double[] result = new double[n];
int Multiple = 100; //你要幾位小數點
L = L*Multiple;
// 這裏簡單判斷,可以實際修改。
if(L/n<1){
return result;
}
int sum = 0; // 已生成的隨機數總和
for(int i=0; i<n-1; i++){
int temp = L - sum;
int random = getRandom(temp,i,n);
System.out.println( "整數L=" + L + " 已生成的隨機數總和sum=" + sum + " 剩餘temp=" + temp + " 生成的隨機數random=" + random);
sum += random;
result[i] = random*1.0/Multiple;
}
result[n-1] = (L - sum)*1.0/Multiple;
return result;
}
/**
* 獲取一個隨機數
* @param temp 剩餘總數
* @param i 第幾次循環了
* @param n 總循環 這兩個變量主要是判斷最後那幾個數據不能小於1.
* @return
*/
private static int getRandom(int temp,int i, int n){
Random rand = new Random();
int random = rand.nextInt(temp-1)+1;
// 這個判斷 規則可以再修改一下,主要是爲了均勻分配整數.
while((temp-random)<=n-i-1){
return getRandom(temp,i,n);
}
return random;
}
}