Stata:生成列表中所有可能的元素对

Stata: Generate all possible pairs of elements in a list

我有一个元素列表作为宏,我想生成一个宏,其中包含所有可能的这些元素对,用“&”号分隔。例如,具有三个元素 azbycx

local elementList az by cx

我想动态生成一个宏 pairList 包含:

az&by az&cx by&cx

(一对中两个元素的顺序无关紧要,因此 az&by 或 by&az 应该在 pairList 中,但不能同时出现。)

听起来很简单,但我不确定如何优雅地做到这一点。 (在我的例子中,我有大约十个元素开始。)

我不确定如何使用我在其他 S.O 上发现的递归算法。线程,所以这是我的 "brute force" 方法。绝对不是最优雅的,但可以做到:

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'"

我同意 Nick 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'"