查找两个阵列之间的所有可能的值组合组合、阵列、两个

2023-09-11 02:17:38 作者:别和我谈感情,戒了

予有字符串两个阵列,相同长度的不是必须的,我想找到的所有可能的套的来自阵列的两个值之间的组合,而不偏离任一阵列重复。 例如,给定的阵列: {A1,A2,A3} {B1,B2} 我要的结果如下设置: {(A1,B1),(A2,B2)} {(A1,B1),(A3,B 2)} {(A1,B2),(A2,B1)} {(A1,B2),(A3,B 1)} {(A2,B1),(A3,B 2)} {(A2,B2),(A3,B 1)}

I have two arrays of strings, not necessarily of the same length, I want to find all the possible "sets" of combinations between two values from the arrays, without repeats from either array. For example, given the arrays: { "A1", "A2", "A3" } { "B1", "B2" } The result I want is the following sets: { ("A1", "B1"), ("A2", "B2") } { ("A1", "B1"), ("A3", "B2") } { ("A1", "B2"), ("A2", "B1") } { ("A1", "B2"), ("A3", "B1") } { ("A2", "B1"), ("A3", "B2") } { ("A2", "B2"), ("A3", "B1") }

我的总的方向是建立递归函数,它作为参数的两个数组并删除每一个选择字符串的时间,自称直到数组是空的,但是我有点担心性能问题(我需要运行在大约千双字符串数组)本code。 任何人都可以直接我对一个有效的方法来做到这一点?

My general direction is to create recursive function that takes as a parameter the two arrays and removes each "chosen" strings at a time, calling itself until either array is empty, however I'm kinda worried about performance issues (I need to run this code on about a 1000 pairs of string arrays). Can anyone direct my towards an efficient method to do this?

推荐答案

这可能是有益的,觉得两个数组作为表的两面:

It might be beneficial to think of the two arrays as sides of a table:

        A1      A2      A3
---+-------+-------+-------+
B1 | B1,A1 | B1,A2 | B1,A3 |
---+-------+-------+-------+
B2 | B2,A1 | B2,A2 | B2,A3 |
---+-------+-------+-------+

此意味着嵌套在另一个循环,一个循环为行,另一个用于列。这会给你的初始设置对:

This implies a loop nested within another, one loop for the rows and the other for the columns. This will give you the initial set of pairs:

{B1,A1} {B1,A2} {B1,A3} {B2,A1} {B2,A2} {B2,A3}

然后,它是建立该初始集合的组合的问题。可以想像的组合同样地,与该组对的两个行和列:

Then it is a matter of building up the combinations of that initial set. You can visualise the combinations similarly, with the set of pairs for both the rows and columns:

      B1,A1 B1,A2 B1,A3 B2,A1 B2,A2 B2,A3
-----+-----+-----+-----+-----+-----+-----+
B1,A1|     |  X  |  X  |  X  |  X  |  X  |
-----+-----+-----+-----+-----+-----+-----+
B1,A2|     |     |  X  |  X  |  X  |  X  |
-----+-----+-----+-----+-----+-----+-----+
B1,A3|     |     |     |  X  |  X  |  X  |
-----+-----+-----+-----+-----+-----+-----+
B2,A1|     |     |     |     |  X  |  X  |
-----+-----+-----+-----+-----+-----+-----+
B2,A2|     |     |     |     |     |  X  |
-----+-----+-----+-----+-----+-----+-----+
B2,A3|     |     |     |     |     |     |
-----+-----+-----+-----+-----+-----+-----+

同样可以完成此一对嵌套循环(提示:你的内循环的范围将由外部循环的值来确定)

Again this can be accomplished with a pair of nested loops (hint: your inner loop's range will be determined by the outer loop's value).