[英]How to check if an element from an array is being repeated in another array. All these arrays are inside of a Multidimensional array?
基本上我循环遍历每个数组中的每个元素,试图找到一个元素也是另一个数组中的元素,如果有一个元素在另一个数组中重复,我想打印出该元素以及停止循环 。 简而言之,这就是我所拥有的:
def list = [[2,3,5,10,13], [12,23,9,8], [34,11,14,15,67,28,5], [7,23,67,27,30,33]]
重要信息 :元素永远不会在同一个数组中出现两次
我需要遍历每个数组的元素并将其与其他数组中的其他元素进行比较,如果有一个元素正在重复(例如:5 - 这个数字在array1和array3中重复)那么我的循环应该是STOP 。 我被困在这一段时间了。 有谁知道如何在Groovy中解决这个问题? 非常感谢提前!
def list = [
[2,3,5,10,13],
[12,23,9,8],
[34,11,14,15,67,28,5],
[7,23,67,27,30,33]
]
list.flatten().countBy { it }.findResult { k, v -> v > 1 ? k : null }
声明Bidimensional-Array
Integer [][]a = {{2,3,5,10,13}, {12,23,9,8}, {34,5,11,14,15}, {7,23,67,27,30,33}};
寻找集合之间相交的数字
boolean numberFound = false;
int number=0;
for (int i = 0; i < a.length && !numberFound; i++){
for (int j = i+1; j < a.length && !numberFound; j++) {
HashSet<Integer> intersection = new HashSet<Integer>(Arrays.asList(a[i]));
intersection.retainAll(Arrays.asList(a[j]));
if(intersection.size()>0){
numberFound = true;
number = intersection.iterator().next().intValue();
}
}
}
印花
if(numberFound){
System.out.println("Number found is: " +number);
} else{
System.out.println("Number not found");
}
UPDATE
如果我们确定一个元素永远不会在同一个数组中出现两次,我们就可以使用这个代码:
Entry<Integer, Long> entry = Arrays.stream(a)
.flatMapToInt(Arrays::stream)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(s -> s.getValue() > 1)
.findAny()
.orElse(null);
if(entry == null){
System.out.println("Number not found");
}else {
System.out.println("Number found: " + orElse.getKey());
}
int[][] list = {{2,3,5,10,13}, {12,23,9,8}, {34,11,14,15,67,28,5}, {7,23,67,27,30,33}};
HashSet<Integer> seenItems = new HashSet<>();
for(int i = 0; i < list.length; i++) {
int[] l = list[i];
for(int j = 0; j < l.length; j++) {
int itemToCheck = l[j];
if (seenItems.contains(itemToCheck)) {
System.out.println("We've already seen " + itemToCheck);
return;
} else {
seenItems.add(itemToCheck);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.