将对象数组排序到Swift中的每个可能序列中

时间:2015-06-02 03:13:58

标签: ios arrays swift sorting

想知道在Swift中是否有一种干净的方法。也许使用一个或几个全局函数,即Map / Reduce等

数组包含 n 数量的唯一自定义对象。

例如,有3个项目。但可能或多或少。的 [1,2,3]

将返回一个数组数组

[ [1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1] ]

Here is a way in Java完成任务。只需要进入Swift形式。

3 个答案:

答案 0 :(得分:2)

https://gist.github.com/JadenGeller/5d49e46d4084fc493e72

他创建了结构来处理排列:

var greetingPermutations = PermutationSequenceGenerator(elements: ["hi", "hey", "hello"])
while let greetingSequence = greetingPermutations.next(){
    for greeting in greetingSequence {
    print("\(greeting) ")
   }
   println()
}

或:

var numberSpace = PermutationSpaceGenerator(objects: Array(1...4))
while let numberArray = numberSpace.next() {
   println(numberArray)
}

修改

这是在objc.io

上找到的更简单的方法

添加扩展程序

extension Array {
    var decompose : (head: T, tail: [T])? {
        return (count > 0) ? (self[0], Array(self[1..<count])) : nil 
    }
}

在您的扩展程序和课程外添加

infix operator >>= {}
func >>=<A, B>(xs: [A], f: A -> [B]) -> [B] {
    return xs.map(f).reduce([], combine: +)
}

普通班级功能

func between<T>(x: T, ys: [T]) -> [[T]] {
    if let (head, tail) = ys.decompose {
        return [[x] + ys] + between(x, ys: tail).map { [head] + $0 }
    } else {
        return [[x]]
    }
}


func permutations<T>(xs: [T]) -> [[T]] {
    if let (head, tail) = xs.decompose {
        return permutations(tail) >>= { permTail in
            self.between(head, ys: permTail)
        }
    } else {
        return [[]]
    }
}

<强>测试

    let example = permutations([1,2,3,5,6,7,8])
    println(example)

此代码使用分解函数扩展数组,并添加&gt;&gt; ==运算符(展平)有关展平的更多信息:http://www.objc.io/snippets/4.html

答案 1 :(得分:2)

可能太过c-ish,但这里是已经发布的例子的替代品。

var a = [1, 2, 3, 4, 5]
var b = [[Int]]()

func perms<T>(n: Int, inout a: [T], inout b: [[T]]) {
    if n == 0 {
        b.append(a)
    } else {
        for i in 0..<n {
            perms(n - 1, &a, &b)
            var j = 0
            if n % 2 == 0 {
                j = i
            }
            swap(&a[j], &a[n - 1])
        }
    }
}


perms(a.count, &a, &b)
println(b)

答案 2 :(得分:0)

快捷键4

@DogCoffee的更新版本,用于swift 4,全部在数组扩展中:

extension Array {
private var decompose : (head: Element, tail: [Element])? {
    return (count > 0) ? (self[0], Array(self[1..<count])) : nil
}

private func between<T>(x: T, ys: [T]) -> [[T]] {
    if let (head, tail) = ys.decompose {
        return [[x] + ys] + between(x: x, ys: tail).map { [head] + $0 }
    } else {
        return [[x]]
    }
}

private func permutations<T>(xs: [T]) -> [[T]] {
    if let (head, tail) = xs.decompose {
        return permutations(xs: tail) >>= { permTail in
            self.between(x: head, ys: permTail)
        }
    } else {
        return [[]]
    }
}

func allPermutations() -> [[Element]] {
    return permutations(xs: self)
} 
}