Algorithm to get all possible string combinations from array up to certain length

后端 未结 12 938
攒了一身酷
攒了一身酷 2020-12-01 02:22

What is the best algorithm to get all possible string combinations from a given array with a minimum & maximum length value.

Note: This adds complexity since the

12条回答
  •  遥遥无期
    2020-12-01 02:55

    I suggest you find an implementation of pythons itertools.product feature in php. (or just copy the implementation yourself).

    The following code gets all permutations of the specified length. You would want lengths 1, 2, 3, 4.

    The final concern is that there are no duplicate characters, so you could add "letters = set(letters)" just to make sure.

    >>> letters = "abc123"
    >>> length = 3
    >>> from itertools import product
    >>> dimensions = [letters]*length
    >>> for point in product(*dimensions):
    ...     print "".join(point)
    ...
    aaa
    aab
    aac
    aa1
    aa2
    aa3
    aba
    abb
    abc
    ab1
    ab2
    ab3
    aca
    acb
    acc
    ac1
    ac2
    ac3
    a1a
    a1b
    a1c
    a11
    a12
    a13
    a2a
    a2b
    a2c
    a21
    a22
    a23
    a3a
    a3b
    a3c
    a31
    a32
    a33
    baa
    bab
    bac
    ba1
    ba2
    ba3
    bba
    bbb
    bbc
    bb1
    bb2
    bb3
    bca
    bcb
    bcc
    bc1
    bc2
    bc3
    b1a
    b1b
    b1c
    b11
    b12
    b13
    b2a
    b2b
    b2c
    b21
    b22
    b23
    b3a
    b3b
    b3c
    b31
    b32
    b33
    caa
    cab
    cac
    ca1
    ca2
    ca3
    cba
    cbb
    cbc
    cb1
    cb2
    cb3
    cca
    ccb
    ccc
    cc1
    cc2
    cc3
    c1a
    c1b
    c1c
    c11
    c12
    c13
    c2a
    c2b
    c2c
    c21
    c22
    c23
    c3a
    c3b
    c3c
    c31
    c32
    c33
    1aa
    1ab
    1ac
    1a1
    1a2
    1a3
    1ba
    1bb
    1bc
    1b1
    1b2
    1b3
    1ca
    1cb
    1cc
    1c1
    1c2
    1c3
    11a
    11b
    11c
    111
    112
    113
    12a
    12b
    12c
    121
    122
    123
    13a
    13b
    13c
    131
    132
    133
    2aa
    2ab
    2ac
    2a1
    2a2
    2a3
    2ba
    2bb
    2bc
    2b1
    2b2
    2b3
    2ca
    2cb
    2cc
    2c1
    2c2
    2c3
    21a
    21b
    21c
    211
    212
    213
    22a
    22b
    22c
    221
    222
    223
    23a
    23b
    23c
    231
    232
    233
    3aa
    3ab
    3ac
    3a1
    3a2
    3a3
    3ba
    3bb
    3bc
    3b1
    3b2
    3b3
    3ca
    3cb
    3cc
    3c1
    3c2
    3c3
    31a
    31b
    31c
    311
    312
    313
    32a
    32b
    32c
    321
    322
    323
    33a
    33b
    33c
    331
    332
    333
    

提交回复
热议问题