为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

一只斗牛犬 2024-01-25 21:39:56
我需要在 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 行,我只需要每一列都是随机的。
查看完整描述

3 回答

?
慕丝7291255

TA贡献1859条经验 获得超6个赞

尝试在任何循环内的数组中初始化数组,例如:


int articles[][] = new int[50][];

for (int i = 0; i < 50; i++) {

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

}


查看完整回答
反对 回复 2024-01-25
?
手掌心

TA贡献1942条经验 获得超3个赞

我建议您研究 中的实用方法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)]);


查看完整回答
反对 回复 2024-01-25
?
繁花不似锦

TA贡献1851条经验 获得超4个赞

要创建一个行数恒定但行长度随机的数组,并用随机数填充它:


int rows = 5;

int[][] arr = IntStream

        .range(0, rows)

        .mapToObj(i -> IntStream

                .range(0, (int) (Math.random() * 10))

                .map(j -> (int) (Math.random() * 10))

                .toArray())

        .toArray(int[][]::new);

// output

Arrays.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]

[]


查看完整回答
反对 回复 2024-01-25
  • 3 回答
  • 0 关注
  • 33 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信