2014-09-09 4 views
0

Swift에서 여러 배열의 요소를 가능한 모든 방식으로 조합하는 방법은 무엇입니까?여러 배열의 요소 선택

let myArray = [[2,3,4], 
[1,2,3,4,5], 
[1,2], 
] 

myArray 요소의 개수가 다를 수 있고, 동일 그 안에 배열 간다 : 여기

는 일례이다.

이 코드는 출력을 한 번에 각 배열에서 하나 개의 요소를 따기에 의해 배열, 기본 보이지만 지금

+0

지금까지 작성한 코드를 표시하십시오. – bdesham

+0

어떻게 접근해야하는지 알 수는 없지만 일부 for for 루프를 사용 중입니다. – Carpsen90

답변

2

https://stackoverflow.com/a/20049365/1187415에서 아이디어를 사용하여 볼 수 없습니다,이 가

로 스위프트 수행 할 수 있습니다한다 마지막 기능

func combinations(array : [[Int]]) -> [[Int]] { 
    return reduce(array, [[]]) { combihelper($0, $1) } 
} 

실시 예로 더 신속 하 쓸 수

// Append all elements of a2 to each element of a1 
func combihelper(a1 : [[Int]], a2 : [Int]) -> [[Int]] { 
    var result = [[Int]]() 
    for elem1 in a1 { 
     for elem2 in a2 { 
      result.append(elem1 + [elem2]) 
     } 
    } 
    return result 
} 

func combinations(array : [[Int]]) -> [[Int]] { 
    // Start with the "empty combination" , then successively 
    // add combinations with each row of array: 
    var result : [[Int]] = [[]] 
    for row in array { 
     result = combihelper(result, row) 
    } 
    return result 
} 

: 0,123,516

let myArray = [[1], 
    [2,3,4], 
    [5,6], 
] 
let result = combinations(myArray) 
println(result) 
// [[1, 2, 5], [1, 2, 6], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6]] 

(사용자의 입력이 정수로 제한되어 있지 않은 경우, 위 기능에 Any에 의해 Int을 바꿀 수 있습니다.)


업데이트 에 대한 스위프트 3과 일반적인 기능으로서, 그 때문에 모든 요소 유형과 함께 사용되는 이 될 수 있습니다.

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

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


let myArray = [[1], 
       [2,3,4], 
       [5,6], 
] 

let result = combinations(of: myArray) 
print(result) // [[1, 2, 5], [1, 2, 6], [1, 3, 5], [1, 3, 6], [1, 4, 5], [1, 4, 6]] 
+0

죄송합니다. 나는'reduce'를 놓쳤습니다. – zaph