我正在尝试获取每个数组中的第一个和最后一个数字,并找到2的总和并在控制台中将其打印出来。一些指导?不确定如何做到这一点谢谢!这就是我到目前为止它只是打印出阵列。
public class Permutations {
public static void main(String args[]) {
List<Integer> permutation = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
for (int i = 0; i < 10; i++) {
Collections.shuffle(permutation);
}
System.out.println("List 1 " + permutation);
System.out.println("List 2 " + permutation);
System.out.println("List 3 " + permutation);
System.out.println("List 4 " + permutation);
System.out.println("List 5 " + permutation);
System.out.println("List 6 " + permutation);
System.out.println("List 7 " + permutation);
System.out.println("List 8 " + permutation);
System.out.println("List 9 " + permutation);
System.out.println("List 10 " + permutation);
}
}
//print off
List 1 [2, 3, 6, 10, 1, 4, 7, 9, 8, 5]
List 2 [2, 3, 6, 10, 1, 4, 7, 9, 8, 5]
List 3 [2, 3, 6, 10, 1, 4, 7, 9, 8, 5]
List 4 [2, 3, 6, 10, 1, 4, 7, 9, 8, 5]
List 5 [2, 3, 6, 10, 1, 4, 7, 9, 8, 5]
List 6 [2, 3, 6, 10, 1, 4, 7, 9, 8, 5]
List 7 [2, 3, 6, 10, 1, 4, 7, 9, 8, 5]
List 8 [2, 3, 6, 10, 1, 4, 7, 9, 8, 5]
List 9 [2, 3, 6, 10, 1, 4, 7, 9, 8, 5]
List 10 [2, 3, 6, 10, 1, 4, 7, 9, 8, 5]
答案 0 :(得分:1)
您是否考虑过使用List.get
然后你可以简单地做
for (int i = 0; i < 10; i++) {
Collections.shuffle(permutation);
System.out.println("List " + (i + 1) + " " + permutation.get(0) + " " +
permutation.get(9) + " sum is " + (permutation.get(0) + permutation.get(9)));
}
当然最好使用数组的长度而不是9
答案 1 :(得分:0)
以下是根据您的兴趣汇总某些元素的不同解决方案:
IntStream.of(0, 9).map(permutation::get).sum();
这样做的潜在优势在于,可以轻松扩展您想要求和的项目,或者在不改变解决方案结构的情况下过滤或映射它们。