-
-
Save ymnk/402014 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
* This source-code is based on | |
* source-code on http://blog.srinivasan.biz/software/if-you-have-to-learn-just-one-programming-language | |
* Using foldLeft often simplifies functional codes. | |
*/ | |
/* | |
* Question: Do you want to play this game? | |
* You put down some money and roll a die between 1 and 100 | |
* Depending on your roll: | |
* 1-50: I keep your money. | |
* 51-65: You get your money back. | |
* 66-75: You get 1.5 times your money | |
* 76-99: You get 2 times your money | |
* 100: You get 3 times your money | |
* Do you want to play? | |
*/ | |
object game { // object is used to define a singleton class | |
// alas, type inference doesn't work for function args. | |
def play(bet: Double, numPlays: Int) = { | |
// parameter values can't be changed | |
import java.util.Random // imports can be inside function | |
// val is like final in java or const in C | |
val r = new Random() | |
// type of moneyStart and money need not be specified. | |
// However, unlike python or ruby, they are inferred as | |
// Double at compile time. Similarly for r and dice. | |
val moneyStart = numPlays * bet | |
val money = Stream.fill(numPlays)(r.nextInt(100)+1).foldLeft(moneyStart){ | |
(money, dice) => | |
if(dice <= 50) money - bet | |
else if(dice >= 66 && dice <= 75) money + 0.5 * bet | |
else if(dice >= 76 && dice <= 99) money + bet | |
else if(dice == 100) money + 2 * bet | |
else money | |
} | |
printf("%6.0f$ became %6.0f$ after %6d plays: " + | |
"You get %.2f for a dollar\n", moneyStart, | |
money, numPlays, (money / moneyStart)) | |
} | |
} | |
game.play(1.0, 100000) // Each bet is $1, play 100000 times | |
game.play(1.5, 5000) | |
game.play(4.0, 10000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment