-1

皆さん、こんにちは、このコードで少し行き詰まっています。乱数をユーザー定義の量に加算することを除いて、私はそれをすべてパットしました。たとえば、ユーザー入力 23500 は、すべての乱数を合計して合計する必要があります。これは私がこれまでに持っているものです

package containerweights;
import java.util.Random;
import java.util.Scanner;
import java.io.*;
public class Containerweightgenerator {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);
        System.out.printf ("%n ***Random Number Genreator*** %n%n");
        System.out.print("Enter total: ");
        double total_weight = input.nextDouble();
        System.out.print("Enter amount: ");
        double total_pallets = input.nextDouble();

        double average_weight = total_weight / total_pallets;
        System.out.printf("%-40s -%10.2f%n", "Average Weight is: ", average_weight);

        double first_weight = average_weight - 50;
        double second_weight = average_weight + 50;

        double START = first_weight;
        double END = second_weight;
        Random random = new Random();
        for (int idx = 1; idx <= total_pallets; ++idx)
        {
            showRandomInteger(START, END, random);
        }
        }
    private static void showRandomInteger(double sTART, double eND, Random aRandom) throws Exception{
        if ( sTART > eND )
        {
            throw new Exception(" Start connot exceed End.");
        }
        long range = (long)eND - (long)sTART + 1;

        long fraction = (long)(range * aRandom.nextDouble());
        int randomNumber = (int)(fraction + sTART);
        System.out.println(randomNumber);
    } 
        private static void log(String aMessage)
        {
            log(aMessage);
        }   
    }
4

2 に答える 2

4

乱数を出すだけです。最後に与えた数値が合計を超えた場合、その数値の代わりに合計との差を返します

新しい要件により、回答を次のように編集します。

int pallets=10;
int targetWeight=100;
int totalSoFar = 0;
int[] palletWeight = new int[pallets];

//Give random weight to N-1 pallets
for (int i=0; i<pallets-1; ++i){
    palletWeight[i] = random.nextInt(1.33 * targetWeight / pallets);
    totalSoFar += palletWeight[i];
}

//Check if we exceeded our target
if (totalSoFar > targetWeight){    
    while(totalSoFar > targetWeight){
      int x = random.nextInt(pallets - 1); //pick a pallet at random
      int a = random.nextInt(palletWeight[x]);
      palletWeight[x] -= a; //take of a random 'a' grams out of its weight
      totalSoFar -= a;
    }
}
//Now we are under the target weight, let the last pallet be the difference
 palletWeight[pallets-1] = targetWeight - totalSoFar;
于 2013-04-08T12:01:29.880 に答える
1

Lefterisの答えがうまくいかない場合(おそらく、すべての値が実際に「ランダム」であることが要件であるため、それが何を意味するかは別として)、唯一の選択肢は、一連の乱数を繰り返し生成してそれらを合計することです。

それは醜くて遅いです、そして私はLefterisの答えを好みます. しかし、彼はシリーズの最後の数字がランダムではないことを意味しており、そのサイズ分布が際立っている可能性があります.

于 2013-04-08T12:58:06.713 に答える