2014年8月9日土曜日

開発環境

Head First JavaScript Programming (Eric T. Freeman (著)、 Elisabeth Robson (著)、 O'Reilly Media )のChapter 4(Putting Some Order in Your Data: Arrays)、SHARPEN YOUR PENCIL(p.160)をSwiftで考えてみる。

SHARPEN YOUR PENCIL(p.160)

コード(Xcode)

main.swift

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

import Foundation

var scores:[Int] = [
    60, 50, 60, 58, 54, 54, 58, 50, 52, 54,
    48, 69, 34, 55, 51, 52, 44, 51, 69, 64,
    66, 55, 52, 61, 46, 31, 57, 52, 44, 18,
    41, 53, 55, 61, 51, 44
]

func printAndGetHighScores(scores:[Int]) -> Int {
    var high_score :Int = 0
    var score:Int
    for i in 0..<scores.endIndex {
        score = scores[i]
        let output:String = "Bubble solution #\(i) score: \(score)"
        println(output)
        if (score > high_score) {
            high_score = score
        }
    }
    return high_score
}

func getBestResults (scores:[Int], high_score:Int) -> [Int] {
    var best_solutions:[Int] = []
    for i in 0..<scores.endIndex {
        if scores[i] == high_score {
            best_solutions.append(i)
        }
    }
    return best_solutions
}

let high_score:Int = printAndGetHighScores(scores)
println("Bubble tests: \(scores.count)")
println("Highest bubble score: \(high_score)")

let best_solutions:[Int] = getBestResults(scores, high_score)
let output:String = ",".join(best_solutions.map({(n:Int) in String(n)}))
println("Solutions with the highest score: \(output)")

入出力結果(Console Output)

Bubble solution #0 score: 60
Bubble solution #1 score: 50
Bubble solution #2 score: 60
Bubble solution #3 score: 58
Bubble solution #4 score: 54
Bubble solution #5 score: 54
Bubble solution #6 score: 58
Bubble solution #7 score: 50
Bubble solution #8 score: 52
Bubble solution #9 score: 54
Bubble solution #10 score: 48
Bubble solution #11 score: 69
Bubble solution #12 score: 34
Bubble solution #13 score: 55
Bubble solution #14 score: 51
Bubble solution #15 score: 52
Bubble solution #16 score: 44
Bubble solution #17 score: 51
Bubble solution #18 score: 69
Bubble solution #19 score: 64
Bubble solution #20 score: 66
Bubble solution #21 score: 55
Bubble solution #22 score: 52
Bubble solution #23 score: 61
Bubble solution #24 score: 46
Bubble solution #25 score: 31
Bubble solution #26 score: 57
Bubble solution #27 score: 52
Bubble solution #28 score: 44
Bubble solution #29 score: 18
Bubble solution #30 score: 41
Bubble solution #31 score: 53
Bubble solution #32 score: 55
Bubble solution #33 score: 61
Bubble solution #34 score: 51
Bubble solution #35 score: 44
Bubble tests: 36
Highest bubble score: 69
Solutions with the highest score: 11,18
Program ended with exit code: 0

0 コメント:

コメントを投稿