私はint型の2つの配列を持っています
int[] x = {1,2,3,4,5};
int[] y = {1,3,12};
そして、私は2つの配列を乗算したいランダムな順序(iは、最初の配列の任意の整数が2番目の配列の任意の整数に乗算できることを意味します)。出力は、最初の配列の長さと等しくなければなりません。
ソリューションに到達するにはどうすればよいと思いますか?
回答:
回答№1の場合は3最初にしたい ループ その 長さ 最初の配列の。それから。あなたが生成したい ランダム 0から2番目の配列の長さ-1までの数値。
配列はインデックス0で始まるため、2番目の配列の最後のインデックスは2です。
次に、各反復の値に乱数を掛けます。次のようになります。
最初の配列と同じサイズの3番目の配列を「z」と呼びます
z[i] = x[i] * y[randomNumber];
回答№2の場合は0
まず、最初の配列を使用してインデックスを作成しますforループと最初のループの各要素に対して、2番目の要素のランダム要素を乗算できます。その後、乗算を元のx配列に戻します。
コードは次のようになります。
//using the Random Class from Java (http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt())
import java.util.Random;
public class randomArrayMultiplication {
public static void main(String [] args) {
int[] x = {1,2,3,4,5};
int[] y = {1,3,12};
//declare a new random class
Random rn = new Random();
//iterate through the first array
for (int i = 0; i < x.length; i ++) {
//for every element of the x array multiply it by a random
//element in the y array (using the randomInt method from the
//random class in which " Returns a pseudorandom, uniformly
//distributed int value between 0 (inclusive) and the specified
//value (exclusive), drawn from this random number generator"s
//sequence."). Therefore, we will choose a random element in
//the y array and multiple it by the x array. At the same time,
//we will end up setting that back to the x array so that every
//array in x is multiplied by a random element in y.
x[i] = x[i] * y[rn.nextInt(y.length)];
}
}
}