開発環境
- OS X Mavericks - Apple(OS)
- Xcode 6.0 Beta
- Swift (プログラミング言語)
Head First JavaScript Programming (Eric T. Freeman (著)、 Elisabeth Robson (著)、 O'Reilly Media )のChapter 4(Putting Some Order in Your Data: Arrays)、EXERCISE(p.164)をSwiftで考えてみる。
EXERCISE(p.164)
コード(Xcode)
main.swift
// // main.swift // sample164 // // Created by kamimura on 8/10/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 ] var costs:[Float] = [ 0.25, 0.27, 0.25, 0.25, 0.25, 0.25, 0.33, 0.31, 0.25, 0.29, 0.27, 0.22, 0.31, 0.25, 0.25, 0.33, 0.21, 0.25, 0.25, 0.25, 0.28, 0.25, 0.24, 0.22, 0.20, 0.25, 0.30, 0.25, 0.24, 0.25, 0.25, 0.25, 0.27, 0.25, 0.26, 0.29 ] 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 getMostCostEffectiveSolution(scores:[Int], costs:[Float], highScore:Int) -> Int { var cost:Float = 100 var index:Int = 0 for i in 0..<scores.count { if scores[i] == highScore { if cost > costs[i] { index = i cost = costs[i] } } } return index } let highScore = printAndGetHighScores(scores) let mostCostEffective = getMostCostEffectiveSolution(scores, costs, highScore) println("Bubble Solution #\(mostCostEffective) is the most cost effective")
入出力結果(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 Solution #11 is the most cost effective Program ended with exit code: 0
0 コメント:
コメントを投稿