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

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

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

  1. func countCommonElements(_ array1D: [Int], _ array3D: [[[Int]]]) -> Int {
  2. let flattenedArray3D = array3D.flatMap { $0.flatMap { $0 } }
  3. var count = 0
  4. for element in array1D {
  5. if flattenedArray3D.contains(element) {
  6. count += 1
  7. }
  8. }
  9. return count
  10. }
  11. // Example
  12. let array1D = [1, 2, 3, 4, 5]
  13. let array3D = [[[5, 6], [7, 8]], [[1, 2], [9, 10]]]
  14. let commonElementsCount = countCommonElements(array1D, array3D)
  15. print(commonElementsCount) // 输出: 2
英文:
  1. **try this**
  2. func countCommonElements(_ array1D: [Int], _ array3D: [[[Int]]]) -> Int {
  3. let flattenedArray3D = array3D.flatMap { $0.flatMap { $0 } }
  4. var count = 0
  5. for element in array1D {
  6. if flattenedArray3D.contains(element) {
  7. count += 1
  8. }
  9. }
  10. return count
  11. }
  12. // Example
  13. let array1D = [1, 2, 3, 4, 5]
  14. let array3D = [[[5, 6], [7, 8]], [[1, 2], [9, 10]]]
  15. let commonElementsCount = countCommonElements(array1D, array3D)
  16. 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)

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

确定