2014年9月13日土曜日

開発環境

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) 11.をSwiftで考えてみる。

9.10(Exercises) 11.

コード(Xcode)

main.swift

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

import Foundation

let numbers1 = 2...22
let numbers2 = 2..<23

var total = 0

for number in numbers1 {
    total += number
}

var average = total / Array(numbers1).count

println(total)
println(average)

total = 0
for number in numbers2 {
    total += number
}
average = total / Array(numbers2).count

println(total)
println(average)

total = Array(numbers1).reduce(0, combine: {(initial, n) in initial + n})
average = total / Array(numbers1).count

println(total)
println(average)

let array = Array(numbers1)
total = sum(array)
average = total / array.count

println(total)
println(average)

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)
        }
    }
}

func sum(nums:[Int]) -> Int {
    return nums.reduce(0, combine: {(x, y) in x + y})
}

func range(start:Int = 0, end:Int, step:Int = 1) -> [Int] {
    assert(step != 0, "arg 3 must not be zero")

    var result:[Int] = []
    var elem = start
    
    if step > 0 {
        while elem < end {
            result.append(elem)
            elem += step
        }
    } else {
        while elem > end {
            result.append(elem)
            elem += step
        }
    }
    
    return result
}

入出力結果(Console Output)

252
12
252
12
252
12
252
12
Program ended with exit code: 0

0 コメント:

コメントを投稿