Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将两个数组按随机顺序相乘_Java - Fatal编程技术网

Java 将两个数组按随机顺序相乘

Java 将两个数组按随机顺序相乘,java,Java,我有两个int类型的数组, int[]x={1,2,3,4,5}; int[]y={1,3,12} 我想以随机顺序乘以这两个数组(我的意思是第一个数组中的任何整数都可以乘以第二个数组中的任何整数),并且输出必须等于第一个数组的长度 你认为我该怎么做才能找到解决方案 首先要循环第一个数组的长度。然后您希望生成一个介于0和第二个数组长度减1之间的随机数 由于数组的索引为0,因此第二个数组的最后一个索引为2 然后,您需要将每次迭代的值与随机数相乘。它应该是这样的: 假设与第一个数组大小相同的第三个数组

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

我想以随机顺序乘以这两个数组(我的意思是第一个数组中的任何整数都可以乘以第二个数组中的任何整数),并且输出必须等于第一个数组的长度


你认为我该怎么做才能找到解决方案

首先要循环第一个数组的长度。然后您希望生成一个介于0和第二个数组长度减1之间的随机数

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

然后,您需要将每次迭代的值与随机数相乘。它应该是这样的:

假设与第一个数组大小相同的第三个数组称为“z”


z[i]=x[i]*y[随机数]

首先,我将使用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)];
    }
  }
}
//使用Java中的Random类(http://docs.oracle.com/javase/6/docs/api/java/util/Random.html#nextInt())
导入java.util.Random;
公共类随机数组乘法{
公共静态void main(字符串[]args){
int[]x={1,2,3,4,5};
int[]y={1,3,12};
//声明一个新的随机类
Random rn=新的Random();
//遍历第一个数组
对于(int i=0;i
问题不仅定义不清,而且堆栈溢出不是“请为我编写此代码”站点。你需要问一个关于如何做到这一点的具体问题,而不仅仅是问解决方案。选择要使用的语言是一件好事。谢谢,我会编辑它来定义问题。好吧,你用“for”循环第一个数组,然后用y[random(0,3)]乘以每个项目。@a.james这两种语言的解决方案都很简单。你的问题仍然有效地要求解决方案;将您的问题分解为组件(如何迭代数组、如何随机选择元素等),并确定您不知道如何做,然后询问。事实上,不要问这个问题;谷歌搜索它,因为我确信这些问题以前有人问过;)@詹姆斯注意到,这不仅仅是如何解决你当前的问题,而是如何解决每一个编程问题,以及你必须发展的一项技能。太好了,它工作得很好。。。但是我认为乘法应该是x[i]=x[i]*y[rn.nextInt(y.length)];