【IDL】数组求交集、并集和差集的函数
IDL对两个数组求交集、并集和差集的函数,从以往的blog里面翻出来的,转帖出来,备查。
;+-------------------------------------------------------------------------------------------------
;| 数组求并集
;+-------------------------------------------------------------------------------------------------
function setunion, a, b
;
compile_opt StrictArr
if n_elements(a) eq 0 then return, b ;A union NULL = a
if n_elements(b) eq 0 then return, a ;B union NULL = b
return, where(histogram([a,b], OMin = omin)) + omin ; Return combined set
end
;+-------------------------------------------------------------------------------------------------
;| 数组求交集
;+-------------------------------------------------------------------------------------------------
function setintersection, a, b
;
compile_opt StrictArr
minab = min(a, Max=maxa) > min(b, Max=maxb) ;Only need intersection of ranges
maxab = maxa < maxb
;
; If either set is empty, or their ranges don't intersect: result = NULL.
if maxab lt minab or maxab lt 0 then return, -1
r = where((histogram(a, Min=minab, Max=maxab) ne 0) and $
(histogram(b, Min=minab, Max=maxab) ne 0), count)
if count eq 0 then return, -1 else return, r + minab
end
;+-------------------------------------------------------------------------------------------------
;| 数组求差集
;+-------------------------------------------------------------------------------------------------
function setdifference, a, b
;
compile_opt StrictArr
;
; = a and (not b) = elements in A but not in B
mina = min(a, Max=maxa)
minb = min(b, Max=maxb)
if (minb gt maxa) or (maxb lt mina) then return, a ;No intersection...
r = where((histogram(a, Min=mina, Max=maxa) ne 0) and $
(histogram(b, Min=mina, Max=maxa) eq 0), count)
if count eq 0 then return, -1 else return, r + mina
end
;数组交集、并集和差集测试
pro test_array
arr1 = [1,2,3,4]
arr2 = [3,4,5,6]
print,'交集',setintersection(arr1,arr2)
print,'并集',setunion(arr1,arr2)
print,'差集',setdifference(arr1,arr2)
end
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?