2014年9月6日土曜日

開発環境

Practical Programming: An Introduction to Computer Science Using Python 3 (Pragmatic Programmers) (Paul Gries (著)、Jennifer Campbell (著)、Jason Montojo (著)、Lynn Beighley (編集)、Pragmatic Bookshelf)のChapter 9(Repeating Code Using Loops)、9.10(Exercises) 5.をSwiftで考えてみる。

9.10(Exercises) 5.

コード(Xcode)

main.swift

//
//  main.swift
//  sample5
//
//  Created by kamimura on 9/6/14.
//  Copyright (c) 2014 kamimura. All rights reserved.
//

import Foundation

func mysteryFunction<T>(values:[[T]]) -> [[T]] {
    var result:[[T]] = []
    
    for sub_array in values {
        var temp:[T] = []
        temp.append(sub_array[0])
        for n in sub_array.slice(start: 1) {
            temp.insert(n, atIndex: 0)
        }
        result.append(temp)
    }
    return result
}

for values in [[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[1, 2]], [[1, 2], [1]], [[1], [1, 2]]] {
    println(mysteryFunction(values))
}

array.swift

//
//  array.swift
//  array
//
//  Created by kamimura on 8/21/14.
//  Copyright (c) 2014 kamimura. All rights reserved.
//

import Foundation

extension Array {
    func indexAt(i:Int) -> T {
        if i >= 0 {
            return self[i]
        }
        let new_index:Int = self.count + i
        return self[new_index]
    }
    func slice(start:Int = 0, end:Int? = nil) -> Array {
        var new_start = start >= 0 ? start : self.count + start
        var new_end:Int
        if end == nil {
            new_end = self.count
        } else if end! >= 0 {
            new_end = end!
        } else {
            new_end = self.count + end!
        }
        var result:Array = []
        if new_start >= new_end {
            return []
        }
        for i in new_start..<new_end {
            result.append(self[i])
        }
        return result
    }
    func forEach(f:(T) -> ()) {
        for e in self {
            f(e)
        }
    }
}

入出力結果(Console Output)

[[5, 4, 3, 2, 1], [10, 9, 8, 7, 6]]
[[2, 1]]
[[2, 1], [1]]
[[1], [2, 1]]
Program ended with exit code: 0

0 コメント:

コメントを投稿