2015-08-21 59 views
0

我有一個元素列表作爲一個宏,我想生成一個宏,其中包含所有可能的元素對,用&符號分隔。例如,具有三個元素azbycxStata:生成列表中所有可能的元素對

local elementList az by cx 

我想動態地生成一個包含宏成對列表:

az&by az&cx by&cx 

(兩個元件中的一對中的順序不應該的問題,所以無論是az &或& az應該在pairList但不是兩個。)

這聽起來很簡單,但我不是sur如何優雅地做到這一點。 (在我的情況下,我有大約十個元素開始。)

+1

另請參見SSC中的元組。在Stata中,'ssc desc tuples'是如何開始的。 –

+0

謝謝尼克,恐怕我無法使用機器上的「外部」軟件包。 – Peutch

回答

3

我同意尼克的這個任務的tuples建議。下面的例子表明你給出的方法稍微更優雅一些。

local elementList a b c d e f g h i j k l 

local pairList // initialize the list of pairs 
local seenList // initialize the list of elements already seen 

foreach first of local elementList { 
    foreach second of local seenList { 
     local pairList `pairList' `second'&`first' 
    } 
    local seenList `seenList' `first' 
} 
display "List of unique pairs: `pairList'" 
0

我不知道如何使用遞歸算法,就像我在其他S.O.上找到的遞歸算法。線程,所以這裏是我的「蠻力」方法。絕對不是最優雅的,但確實個工作:

local elementList a b c d e f g h i j k l 

local pairList // initialize the list of pairs 

foreach first in `elementList' { 
    foreach second in `elementList' { 
     // only do something if the elements are not the same 
     if("`first'" != "`second'") { 
      local pair   `first'&`second' // pair 
      local pairReverse `second'&`first' // pair in reverse order 

      // if pair (or its inverse) is not already in the list, add the pair 
      if(strpos("`pairList'","`pair'") == 0 & strpos("`pairList'","`pairReverse'") == 0) { 
       local pairList `pairList' `pair' 
      } 
     } 
    } // end of loop on second element 
} // end of loop on first element 
display "List of unique pairs: `pairList'"