如何找到1D数组与3D数组之间的公共元素数量?

huangapple go评论71阅读模式
英文:

How to find the number of common elements between 1D array vs 3D array?

问题

我想找到arr1(1D)在arr2(3D)中的共同元素数量,不使用循环。

arr1=[1,2,3];

arr2=[y][x][1,2,3,4,5,6];

(y和x可以是任何索引)。

输出:3。

关键是能够在MQL5上运行,通过导入numPy或类似的库。

感谢您的帮助。

英文:

I want to find the number of common elements of arr1 (1D) inside arr2 (3D), not using loops.

arr1=[1,2,3];

arr2=[y][x][1,2,3,4,5,6];

(y and x could be any index).

Output: 3.

The thing is to be able to run on MQL5, by importing numPy or similar.

Thanks for your help.

答案1

得分: 0

func countCommonElements(_ array1D: [Int], _ array3D: [[[Int]]]) -> Int {
    let flattenedArray3D = array3D.flatMap { $0.flatMap { $0 } }

    var count = 0

    for element in array1D {
        if flattenedArray3D.contains(element) {
            count += 1
        }
    }

    return count
}

// Example
let array1D = [1, 2, 3, 4, 5]
let array3D = [[[5, 6], [7, 8]], [[1, 2], [9, 10]]]

let commonElementsCount = countCommonElements(array1D, array3D)
print(commonElementsCount) // 输出: 2
英文:
 **try this**   

func countCommonElements(_ array1D: [Int], _ array3D: [[[Int]]]) -> Int {
    let flattenedArray3D = array3D.flatMap { $0.flatMap { $0 } }

    var count = 0

    for element in array1D {
        if flattenedArray3D.contains(element) {
            count += 1
        }
    }

    return count
}

// Example
let array1D = [1, 2, 3, 4, 5]
let array3D = [[[5, 6], [7, 8]], [[1, 2], [9, 10]]]

let commonElementsCount = countCommonElements(array1D, array3D)
print(commonElementsCount) // Output: 2

答案2

得分: 0

arr1 = np.array([1, 2, 3])
arr2 = np.array([[[1, 2, 3, 4, 5, 6]],
[[7, 8, 9, 10, 11, 12]],
[[3, 4, 5, 6, 7, 8]]])
flatarray = arr2.flatten()
common_elements = np.intersect1d(arr1, flatarray)
a = len(common_elements)
print(a)

英文:
arr1 = np.array([1, 2, 3])
arr2 = np.array([[[1, 2, 3, 4, 5, 6]],
             [[7, 8, 9, 10, 11, 12]],
             [[3, 4, 5, 6, 7, 8]]])
flatarray = arr2.flatten()
common_elements = np.intersect1d(arr1, flatarray)
a = len(common_elements)
print(a)

huangapple
  • 本文由 发表于 2023年6月26日 12:25:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76553508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定