LoginSignup
3
3

More than 5 years have passed since last update.

Swiftでarray.permutation

Posted at

permutation

ちょっとした探索を書いている時に, ふとpermutationが欲しくなったのでメモ.

let a = [1,2,3]
a.permutaion(2)
// => [[1, 2], [2, 1], [1, 3], [3, 1], [2, 3], [3, 2]]

という感じのものが欲しかったので検索. ExSwiftに欲しいものを見つけた. ただこれはSwift 2.0に対応していなかったので少し修正.

combinationもrepeatedPermutationもあったので一緒に抜き出してきた.

let a = [1,2,3]
a.combination(2)
// => [[1, 2], [1, 3], [2, 3]]
a.repeatedPermutation(2)
// => [[1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]]

簡単な全探索ならこれでさくっとかけるようになった.

おまけ

Swiftには標準でPermutationGeneratorなるものがある. しかしPermutationSequenceはない. 期待に胸を膨らませて実行.

let a = [1, 2, 3]
var p = PermutationGenerator(elements: a, indices: [1, 2, 0])
p.next()
// => Optional(2), =a[1]
p.next()
// => Optional(3), =a[2]
p.next()
// => Optional(1), =a[0]
p.next()
// => nil

違うそうじゃない...

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3