以随机顺序乘以两个数组

时间:2016-08-26 23:05:04

标签: java

我有两个int类型的数组, int[] x = {1,2,3,4,5}; int[] y = {1,3,12};

我希望以随机顺序将两个数组相乘(我的意思是第一个数组中的任何整数都可以乘以第二个数组的任何整数),输出必须等于第一个数组的长度。< / p>

您如何看待我应该做些什么才能达成解决方案。

2 个答案:

答案 0 :(得分:3)

您首先要循环第一个数组的长度。然后。你想在0和第二个数组的长度减1之间生成一个随机数字。

由于数组以索引0开头,因此第二个数组的最后一个索引为2.

然后,您希望将每次迭代的值乘以随机数。它应该看起来像这样:

假设您的第三个数组与第一个数组的大小相同,则称为&#34; z&#34;

z[i] = x[i] * y[randomNumber];

答案 1 :(得分:0)

首先,我将使用for循环索引第一个数组,并且对于第一个循环中的每个元素,您可以将它乘以第二个元素的随机元素。然后,将乘法设置回原始的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)];
    }
  }
}