英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论