MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: element selection

  • To: mathgroup at smc.vnet.net
  • Subject: [mg53621] Re: [mg53605] element selection
  • From: yehuda ben-shimol <benshimo at bgumail.bgu.ac.il>
  • Date: Fri, 21 Jan 2005 06:35:25 -0500 (EST)
  • References: <200501200847.DAA04095@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Bruyndonckx P. wrote:

>I have two long sorted lists of Integers.  If the difference between a number in list 1 and a 
>number in list 2 is less than a certain value, both are selected to create a couple.  I am 
>looking for a fast way to go through both lists and extract these elements to create a new list 
>of couples.  I tried a number of things, but all of them were rather slow so I need some expert 
>advice here.
>
>Thx,
>
>Peter
>
>  
>
Hi,
Call the first list a and the second b and the threshold th. In case 
that you want to check elements of the same positions in both lists say 
a[[1]] -b[[1]]<th, a[[2]]-b[[2]]<th etc use the following code(note that 
both lists need to be of identical length)

sel[l1_List, l2_List, th_] := Select[Thread[{l1, l2}], #[[
    1]] - #[[2]] < th &];

examining its performance on a modest laptop gives with two lists of 
100000 elements each
a=Table[Random[Integer,{1,10}],{100000}];
b=Table[Ransom[Integer,{1,10}],{100000}];
pairs=sel[a,b,3];//Timing
results with
{0.751 Second, Null}

In case you want to compare EACH element of l1 agianst each element of 
l2 (here l1 and l2 need not be of identical length)
you can use the following code
selAll[l1_List,l2_List,th_]:=Select[Tuples[{l1,l2}],#[[1]]-#[[2]]<th&];
here the number of pairs to be generated and checked is Length[l1] * 
Length[l2] so the performance of two list with 1000 elements each 
(1000000 pairs are generated and checked) is
a=Table[Random[Integer,{1,10}],{1000}];
b=Table[Ransom[Integer,{1,10}],{1000}];
pairsAll=selAll[a,b,3];//Timing

{9.153 Second, Null}

yehuda


  • Prev by Date: Re: global option?
  • Next by Date: Re: A NewBie Question
  • Previous by thread: Re: element selection
  • Next by thread: Re: element selection