列出一组元素的组合


10

给定一组n元素,挑战在于编写一个函数,该函数列出k该集合中所有元素的组合。

Set: [1, 7, 4]
Input: 2
Output: [1,7], [1,4], [7,4]

Set: ["Charlie", "Alice", "Daniel", "Bob"]
Input: 2
Output ["Daniel", "Bob"], ["Charlie", "Alice"], ["Alice", "Daniel"], ["Charlie", "Daniel"], ["Alice", "Bob"], ["Charlie",  "Bob"]

规则(已编辑)

  • 您可以选择输出的顺序。
  • 输入可以是任何类型的数据。但是输出应与输入的类型相同。如果输入是整数列表,则输出也应该是整数列表。如果输入是字符串(字符数组),则输出也应该是字符串。
  • 该代码应与任意数量的输入变量一起使用。
  • 您可以使用任何编程语言。
  • 答案也应该能够使用任何东西(字符串,整数,双精度数...)作为输入和输出。
  • 禁止与组合和排列有关的任何内置函数。
  • 最短的代码获胜(以字节为单位)。
  • 决胜局:票。
  • 时间:1周。

PS请注意极端输入,例如负数,0等。


1
尽管codegolf.stackexchange.com/questions/6380/…确实有一个额外的限制,但是其答案可以原样复制,并且仍然难以克服
彼得·泰勒

1
通过输入可以是任何类型的数据。您是说任何类型的可迭代数据还是用任何类型的数据填充的可迭代数据?例如combos('ab', 1) -> ['a', 'b']有效吗?
卡尔文的爱好

1
如果输入为负,输出应该是什么?
Ypnypn 2014年

5
当到目前为止几乎所有答案都使用递归时,我看不出这个问题是“生成没有递归的组合”的重复。
xnor

2
取消限制不是重大更改。同样,使用现有答案来确定什么是重复项也不是一个好主意,因为您将无法识别重复项,除非它们已经被回答。有时您只需要动动脑子。
Rainbolt 2014年

Answers:


13

Haskell- 57 46字节

来吧,golfscripters。

0%_=[[]]
n%(x:y)=map(x:)((n-1)%y)++n%y
_%_=[]

用例(相同的函数可以实现多态):

2%[1,2,3,4]➔[[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]

3%“作弊”➔[“ che”,“ cha”,“ cht”,“ cea”,“ cet”,“ cat”,“ hea”,“ het”,“ hat”,“ eat”]

2%[“ Charlie”,“ Alice”,“ Daniel”,“ Bob”]➔[[“” Charlie“,” Alice“],[” Charlie“,” Daniel“],[” Charlie“,” Bob“] ,[“ Alice”,“ Daniel”],[“ Alice”,“ Bob”],[“ Daniel”,“ Bob”]]


1
谢谢马克,我什至没有考虑将其定为前缀。
ChaseC

顺便说一句,“加音”在您的方言中是什么意思?在我看来,这意味着挑战,但这在上下文中没有意义,因为在此重复的问题中,最终版本仍比我的初始版本长。
彼得·泰勒

7

巨蟒(72)

f=lambda S,k:S and[T+S[:1]for T in f(S[1:],k-1)]+f(S[1:],k)or[[]]*(k==0)

该函数f获取一个列表S和一个数字,k并返回所有长度k为的子列表的列表S。而不是列出所有子集,然后按大小过滤,我只在每一步中获得所需大小的子集。

我想S.pop()开始工作,以便以后将S[:1]通过与通过结合起来S[1:],但似乎消耗了太多的清单。

为了避免异议,任何这样的Python解决方案都会由于递归限制而违反“代码应在任何数量的输入变量中工作”的规则,我会注意到Stackless Python实现没有递归限制(尽管我尚未实际测试)此代码)。

示范:

S = [1, 2, 6, 8]
for i in range(-1,6):print(i, f(S,i))

#Output:    
-1 []
0 [[]]
1 [[1], [2], [6], [8]]
2 [[2, 1], [6, 1], [8, 1], [6, 2], [8, 2], [8, 6]]
3 [[6, 2, 1], [8, 2, 1], [8, 6, 1], [8, 6, 2]]
4 [[8, 6, 2, 1]]
5 []

3

Mathematica 10,70个字符

只是Haskell答案的翻译。

_~f~_={};_~f~0={{}};{x_,y___}~f~n_:=Join[Append@x/@f[{y},n-1],{y}~f~n]

用法:

在[1]:= f [{1,7,4},2]

Out [1] = {{7,1},{4,1},{4,7}}


3

木炭,23字节

EΦEX²Lθ⮌↨ι²⁼ΣιηΦ…θLι§ιμ

在线尝试!链接是详细版本的代码。说明:

    ²                   Literal 2
   X                    Raised to power
     L                  Length of
      θ                 Input array
  E                     Mapped over implicit range
         ι              Current index
        ↨               Converted to base
          ²             Literal 2
       ⮌                Reversed
 Φ                      Filtered on
            Σ           Digital sum of
             ι          Current base 2 value
           ⁼            Equal to
              η         Input `k`
E                       Mapped to
                 θ      Input array
                …       Chopped to length
                  L     Length of
                   ι    Current base 2 value
               Φ        Filtered on
                     ι  Current base 2 value
                    §   Indexed by
                      μ Current index

2

蟒蛇-129

s是一个列表,k是要产生的组合的大小。

def c(s, k):
    if k < 0: return []
    if len(s) == k: return [s]
    return list(map(lambda x: [s[0]]+x, c(s[1:], k-1))) + c(s[1:], k)

2

巨蟒,102

p=lambda s:p(s[1:])+[x+[s[0]]for x in p(s[1:])]if s else[s];c=lambda s,k:[x for x in p(s)if len(x)==k]

调用c运行:

c([5,6,7],2)=> [[6,7],[5,7],[5,6]]

它获取列表s的所有排列并过滤长度为k的排列。


2

珀斯 28岁

DcGHR?+m+]'HdctGtHcGtHH*]Y!G

这(基于)基于Haskell答案。

说明:

DcGH                           def c(G,H):
    R                          return
     ?                         Python's short circuiting _ if _ else _
       m+]'Hd                  map to [head(H)]+d
             ctGtH             c(G-1,tail(H))
       m+]'HdctGtH             map [head(H)]+d for d in c(tail(G),tail(H))
      +m+]'HdctGtHcGtH         (the above) + c(G,tail(H))
     ?                H        (the above) if H else (the below)
                       *]Y!G   [[]]*(not G)

注意:虽然Pyth的最新版本1.0.9已于今晚发布,因此不适合进行此挑战,但相同的代码在1.0.8中可以正常工作。



2

05AB1E14 13 字节

goLε¹ybRÏ}ʒgQ

受到@Neil的木炭答案的启发,因此请确保对他投票

在线尝试验证更多测试用例

如果允许内置,则可能是2 个字节

在线尝试验证更多测试用例

说明:

g              # Get the length of the first (implicit) input-list
 o             # Take 2 to the power this length
  L            # Create a list in the range [1, 2**length]
   ε           # Map each integer `y` to:
    ¹          #  Push the first input-list again
     ybR       #  Convert integer `y` to binary, and reverse it
        Ï      #  And only keep values at truthy indices of `y` (so where the bit is a 1)
             # After the map: filter the list of lists by:
           g   #  Where the length of the inner list
            Q  #  Is equal to the (implicit) input-integer
               # (then the result is output implicitly)

             # Get all `b`-element combinations in list `a`,
               # where `b` is the first (implicit) input-integer,
               # and `a` is the second (implicit) input-list
               # (then the result is output implicitly)

2

APL(NARS),80个字符,160个字节

{h←{0=k←⍺-1:,¨⍵⋄(k<0)∨k≥i←≢w←⍵:⍬⋄↑,/{w[⍵],¨k h w[(⍳i)∼⍳⍵]}¨⍳i-k}⋄1≥≡⍵:⍺h⍵⋄⍺h⊂¨⍵}

测试以及如何使用它:

  f←{h←{0=k←⍺-1:,¨⍵⋄(k<0)∨k≥i←≢w←⍵:⍬⋄↑,/{w[⍵],¨k h w[(⍳i)∼⍳⍵]}¨⍳i-k}⋄1≥≡⍵:⍺h⍵⋄⍺h⊂¨⍵}
  o←⎕fmt
  o 5 f 1 2 3 4
┌0─┐
│ 0│
└~─┘
  o 4 f 1 2 3 4 
┌1─────────┐
│┌4───────┐│
││ 1 2 3 4││
│└~───────┘2
└∊─────────┘
  o 3 f 1 2 3 4
┌4──────────────────────────────────┐
│┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐│
││ 1 2 3│ │ 1 2 4│ │ 1 3 4│ │ 2 3 4││
│└~─────┘ └~─────┘ └~─────┘ └~─────┘2
└∊──────────────────────────────────┘
  o 2 f 1 2 3 4
┌6────────────────────────────────────────┐
│┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐ ┌2───┐│
││ 1 2│ │ 1 3│ │ 1 4│ │ 2 3│ │ 2 4│ │ 3 4││
│└~───┘ └~───┘ └~───┘ └~───┘ └~───┘ └~───┘2
└∊────────────────────────────────────────┘
  o 1 f 1 2 3 4
┌4──────────────────┐
│┌1─┐ ┌1─┐ ┌1─┐ ┌1─┐│
││ 1│ │ 2│ │ 3│ │ 4││
│└~─┘ └~─┘ └~─┘ └~─┘2
└∊──────────────────┘
  o 0 f 1 2 3 4
┌0─┐
│ 0│
└~─┘
  o ¯1 f 1 2 3 4
┌0─┐
│ 0│
└~─┘
  o 3 f (0 0)(1 2)(3 ¯4)(4 ¯5)
┌4────────────────────────────────────────────────────────────────────────────────────────────────┐
│┌3────────────────────┐ ┌3────────────────────┐ ┌3─────────────────────┐ ┌3─────────────────────┐│
││┌2───┐ ┌2───┐ ┌2────┐│ │┌2───┐ ┌2───┐ ┌2────┐│ │┌2───┐ ┌2────┐ ┌2────┐│ │┌2───┐ ┌2────┐ ┌2────┐││
│││ 0 0│ │ 1 2│ │ 3 ¯4││ ││ 0 0│ │ 1 2│ │ 4 ¯5││ ││ 0 0│ │ 3 ¯4│ │ 4 ¯5││ ││ 1 2│ │ 3 ¯4│ │ 4 ¯5│││
││└~───┘ └~───┘ └~────┘2 │└~───┘ └~───┘ └~────┘2 │└~───┘ └~────┘ └~────┘2 │└~───┘ └~────┘ └~────┘2│
│└∊────────────────────┘ └∊────────────────────┘ └∊─────────────────────┘ └∊─────────────────────┘3
└∊────────────────────────────────────────────────────────────────────────────────────────────────┘
  o 4 f (0 0)(1 2)(3 ¯4)(4 ¯5)
┌1──────────────────────────────┐
│┌4────────────────────────────┐│
││┌2───┐ ┌2───┐ ┌2────┐ ┌2────┐││
│││ 0 0│ │ 1 2│ │ 3 ¯4│ │ 4 ¯5│││
││└~───┘ └~───┘ └~────┘ └~────┘2│
│└∊────────────────────────────┘3
└∊──────────────────────────────┘
  o 1 f (0 0)(1 2)(3 ¯4)(4 ¯5)
┌4────────────────────────────────────┐
│┌1─────┐ ┌1─────┐ ┌1──────┐ ┌1──────┐│
││┌2───┐│ │┌2───┐│ │┌2────┐│ │┌2────┐││
│││ 0 0││ ││ 1 2││ ││ 3 ¯4││ ││ 4 ¯5│││
││└~───┘2 │└~───┘2 │└~────┘2 │└~────┘2│
│└∊─────┘ └∊─────┘ └∊──────┘ └∊──────┘3
└∊────────────────────────────────────┘
  o 2 f ('Charli')('Alice')('Daniel')('Bob')
┌6──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐
│┌2─────────────────┐ ┌2──────────────────┐ ┌2───────────────┐ ┌2─────────────────┐ ┌2──────────────┐ ┌2───────────────┐│
││┌6──────┐ ┌5─────┐│ │┌6──────┐ ┌6──────┐│ │┌6──────┐ ┌3───┐│ │┌5─────┐ ┌6──────┐│ │┌5─────┐ ┌3───┐│ │┌6──────┐ ┌3───┐││
│││ Charli│ │ Alice││ ││ Charli│ │ Daniel││ ││ Charli│ │ Bob││ ││ Alice│ │ Daniel││ ││ Alice│ │ Bob││ ││ Daniel│ │ Bob│││
││└───────┘ └──────┘2 │└───────┘ └───────┘2 │└───────┘ └────┘2 │└──────┘ └───────┘2 │└──────┘ └────┘2 │└───────┘ └────┘2│
│└∊─────────────────┘ └∊──────────────────┘ └∊───────────────┘ └∊─────────────────┘ └∊──────────────┘ └∊───────────────┘3
└∊──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
  o ¯2 f ('Charli')('Alice')('Daniel')('Bob')
┌0─┐
│ 0│
└~─┘

输出似乎还可以...但是可能出现错误...

在实践中,如果输入alpha超出范围,则返回void设置为Zilde;否则返回false。如果alpha为1,则返回其集合中的所有元素(对吗?);

下面的代码似乎少了几个字符,但比上面的慢了2倍:

f←{(⍺>≢⍵)∨⍺≤0:⍬⋄1=⍺:,¨⍵⋄{w[⍵]}¨k/⍨{∧/</¨¯1↓{⍵,¨1⌽⍵}⍵}¨k←,⍳⍺⍴≢w←⍵}

1

JS- 117188

(a,b,c=[])=>((d=(e,f,g=[])=>f*e?g.push(e)+d(e-1,f-1,g)+g.pop
()+d(e-1,f,g):f||c.push(g.map(b=>a[b-1])))(a.length,b),c)

(<源代码>)([['Bob','Sally','Jonah'],2)

     [['Jonah','Sally'] ['Jonah','Bob'] ['Sally','Bob']]

数组方法疯狂

combination = (arr, k) =>
    Array
        .apply(0, { length: Math.pow(k+1, arr.length) })
        .map(Number.call, Number)
        .map(a => a
              .toString(arr.length)
              .split('')
              .sort()
              .filter((a, b, c) => c.indexOf(a) == b)
              .join(''))
        .filter((a, b, c) => a.length == k && c.indexOf(a) == b)
        .map(x => x.split('').map(y => arr[+y]))

1

C#(Visual C#交互式编译器),141个字节

l=>l.Any()?A(l.Skip(1)).Select(x=>l.Take(1).Union(x)).Union(A(l.Skip(1))):new object[][]{new object[]{}};B=(n,l)=>A(l).Where(x=>x.Count()==n)

可悲的是,Tio / Mono似乎不支持泛型T声明,因此我被迫丢失了对象类型的一些字节。

//returns a list of all the subsets of a list
A=l=>l.Any()?A(l.Skip(1)).Select(x=>l.Take(1).Union(x)).Union(A(l.Skip(1))):new object[][]{new object[]{}};

//return the subsets of the required size
B=(n,l)=>A(l).Where(x=>x.Count()==n);

在线尝试!

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.