如何在Java中创建具有随机长度列的多维数组?

我需要在 Java 中创建一个多维数组,但列的长度是随机的。

例如,假设随机长度为 3、2、4 和 1,那么我们会有这样的结果:

[[1, 2, 3], [1, 2], [3, 4, 5, 6], [3]]

我已经尝试过这个,但它不会为每列创建随机长度:

int articles[][] = new int[50][(int) Math.floor(Math.random() * 30 + 1)];

有谁知道如何实现这一目标?

注意:数组始终有 50 行,我只需要每一列都是随机的。


一只斗牛犬
浏览 41回答 3
3回答

慕丝7291255

尝试在任何循环内的数组中初始化数组,例如:int articles[][] = new int[50][];for (int i = 0; i < 50; i++) {&nbsp; &nbsp; articles[i] = new int[(int) Math.floor(Math.random() * 30 + 1)];}

手掌心

我建议您研究 中的实用方法java.util.Arrays。它是处理数组的辅助方法的金矿。从 1.8 开始就有了这个:int articles[][] = new int[50][];Arrays.setAll(articles, i -> new int[(int)Math.floor(Math.random() * 30 + 1)]);在这个问题案例中,使用 lambda 并不比普通循环更有效,但通常可以提供更简洁的整体解决方案。我还建议不要自行扩展double(int请参阅来源Random.nextInt()并自行决定)。Random r = new Random();int articles[][] = new int[50][];Arrays.setAll(articles, i -> new int[r.nextInt(30)]);

繁花不似锦

要创建一个行数恒定但行长度随机的数组,并用随机数填充它:int rows = 5;int[][] arr = IntStream&nbsp; &nbsp; &nbsp; &nbsp; .range(0, rows)&nbsp; &nbsp; &nbsp; &nbsp; .mapToObj(i -> IntStream&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .range(0, (int) (Math.random() * 10))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(j -> (int) (Math.random() * 10))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toArray())&nbsp; &nbsp; &nbsp; &nbsp; .toArray(int[][]::new);// outputArrays.stream(arr).map(Arrays::toString).forEach(System.out::println);[3, 8][2, 7, 6, 8, 4, 9, 3, 4, 9][5, 4][0, 2, 8, 3][]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java