Created
March 27, 2011 05:28
-
-
Save akihiro4chawon/888945 to your computer and use it in GitHub Desktop.
モナドとしての Option を for式 で連結
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// お題:ランダム文字列 | |
// <http://d.hatena.ne.jp/fumokmm/20110326/1301144291> | |
// に対する scala での答案(Iterator.continually編)by @akihiro4chawon | |
object Prob2 extends Application{ | |
def gen(nDigits: Int) = { | |
val range = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9') :+ '_' | |
Iterator.continually(range(Random.nextInt(range.size))) take nDigits mkString | |
} | |
println(gen(16)) | |
println(gen(16)) | |
println(gen(16)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// お題:時間帯重複チェック | |
// <http://d.hatena.ne.jp/fumokmm/20110326/1301146382> | |
// に対する scala での答案(for式とOption編)by @akihiro4chawon | |
// jikoku の for | |
object Prob1 extends Application { | |
type Duration = (Int, Int, Int, Int) | |
def timePointInMinutes(hour: Int, min: Int) = | |
for { | |
inMinutes <- Some(60 * hour + min) | |
if inMinutes <= 60 * 24 | |
if 0 to 24 contains hour | |
if 0 to 60 contains min | |
} yield inMinutes | |
val durationInMinutes = (d: Duration) => { | |
val (h1, m1, h2, m2) = d | |
for { | |
t1 <- timePointInMinutes(h1, m1) | |
t2 <- timePointInMinutes(h2, m2) | |
if (t1 <= t2) | |
} yield t1 until t2 | |
} | |
// 問題への回答となる関数 | |
def timeDuplicationCheck(duration1: Duration, duration2: Duration) = | |
for { | |
d1 <- durationInMinutes(duration1) | |
d2 <- durationInMinutes(duration2) | |
intersection = d1 intersect d2 | |
} yield intersection.nonEmpty | |
println(timeDuplicationCheck((1, 0, 5, 30), (9, 0, 23, 0))) // => Some(false) (重複なし) | |
println(timeDuplicationCheck((1, 0, 2, 0), (2, 0, 3, 0))) // => Some(false) (重複なし) | |
println(timeDuplicationCheck((1, 0, 2, 1), (1, 59, 3, 0))) // => Some(true) (重複あり) | |
println(timeDuplicationCheck((1, 0, 5, 75), (9, 0, 23, 0))) // => None 範囲外の時刻 | |
println(timeDuplicationCheck((5, 30, 1, 5), (9, 0, 23, 0))) // => None 範囲外の時刻 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment