Skip to content

Instantly share code, notes, and snippets.

@brownsoo
Last active October 10, 2023 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brownsoo/085cfe33087055d15e4da440f23c7e49 to your computer and use it in GitHub Desktop.
Save brownsoo/085cfe33087055d15e4da440f23c7e49 to your computer and use it in GitHub Desktop.
배열 요소의 모든 조합 구하기 (순열, 순서고려)
/// 배열의 모든 조합 구하기 (순열)
/// 순서에 상관하여 같은 요소라도 순서가 다르면 다른 조합으로 처리
/// - Parameters:
/// - arr: 제공되는 배열
/// - select: 몇개의 요소를 선택해서 조합할지 결정
/// - Returns: 제공된 배열에서 select 개를 선택해서 조합된 새 배열
func getAllPermutations(_ arr: [Int], select: Int) -> [[Int]] {
var results: [[Int]] = []
if select == 1 {
return arr.map { [$0] }
}
arr.enumerated().forEach { el in
let rest = Array(arr[0..<el.offset] + arr[(el.offset + 1)..<arr.count])
let permutations = getAllPermutations(rest, select: select - 1)
let attached = permutations.map({ [el.element] + $0 })
results.append(contentsOf: attached)
}
return results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment