2017-10-04 21 views
-1
func combinations<T>(of array: [[T]]) -> [[T]] { 
    return array.reduce([[]]) { combihelper(a1: $0, a2: $1) } 
} 

func combihelper<T>(a1: [[T]], a2: [T]) -> [[T]] { 
    var x = [[T]]() 
    for elem1 in a1 { 
     for elem2 in a2 { 
      x.append(elem1 + [elem2]) 
     } 
    } 
    return x 
} 

什麼是在一個func中編寫代碼的最佳解決方案?swift 4種組合func

+0

你能提供一個關於該功能應該做什麼的例子的描述嗎? –

+0

是的,當然。它給你參數的組合。例如,var par = [[Double]]() par.append(Array(stride(from:0,through:10,by:1.0))) par.append(Array(stride(from:-10 ,通過:0,通過:1.0))) let comb = combinations(of:par) – Anton

回答

2

如果你想要的是這兩種方法結合成一個單一的一個只是改變A1至$ O,並且A $ 1:

func combinations<T>(of array: [[T]]) -> [[T]] { 
    return array.reduce([[]]) { 
     var x = [[T]]() 
     for elem1 in $0 { 
      for elem2 in $1 { 
       x.append(elem1 + [elem2]) 
      } 
     } 
     return x 
    } 
} 

let multi = [[1,2,3,4,5],[1,2,3,4,5,6,7,8,9,0]] 
combinations(of: multi) // [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7], [1, 8], [1, 9], [1, 0], [2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7], [2, 8], [2, 9], [2, 0], [3, 1], [3, 2], [3, 3], [3, 4], [3, 5], [3, 6], [3, 7], [3, 8], [3, 9], [3, 0], [4, 1], [4, 2], [4, 3], [4, 4], [4, 5], [4, 6], [4, 7], [4, 8], [4, 9], [4, 0], [5, 1], [5, 2], [5, 3], [5, 4], [5, 5], [5, 6], [5, 7], [5, 8], [5, 9], [5, 0]] 
+0

那麼,它變得非常簡單) – Anton

0

你也可以做到這一點沒有任何for循環:

func combinations<T>(of array: [[T]]) -> [[T]] 
{ 
    return array.reduce([[]]){ c,a in c.flatMap{ e in a.map{e + [$0] } } } 
}