gpt4 book ai didi

Java:前n个整数的数组

转载 作者:搜寻专家 更新时间:2023-11-01 01:06:09 24 4
gpt4 key购买 nike

有什么快捷方式可以在不进行显式循环的情况下创建前 n 个整数的 Java 数组?在 R 中,它将是

intArray = c(1:n) 

(生成的 vector 将为 1,2,...,n)。

最佳答案

如果您使用 ,你可以这样做:

int[] arr = IntStream.range(1, n).toArray();

这将创建一个数组,其中包含来自 [0, n) 的整数。您可以使用 rangeClosed如果您想在结果数组中包含 n

如果你想指定一个步骤,你可以iterate然后 limit流获取您想要的第一个 n 元素。

int[] arr = IntStream.iterate(0, i ->i + 2).limit(10).toArray(); //[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

否则我想最简单的方法是使用循环并填充数组。如果需要,您可以创建辅助方法。

static int[] fillArray(int from, int to, int step){
if(to < from || step <= 0)
throw new IllegalArgumentException("to < from or step <= 0");

int[] array = new int[(to-from)/step+1];
for(int i = 0; i < array.length; i++){
array[i] = from;
from += step;
}
return array;
}
...
int[] arr3 = fillArray(0, 10, 3); //[0, 3, 6, 9]

您可以根据需要调整此方法,以每个示例从上界到下界,步长为负。

关于Java:前n个整数的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23142291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com