【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

浙公网安备 33010602011771号