Created
November 7, 2012 14:45
-
-
Save numa08/4032012 to your computer and use it in GitHub Desktop.
Scalaで重み付き乱択アルゴリズム ref: http://qiita.com/items/9fab26545ae931a1dc67
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
val makeRandomChooser = (shops : List[Shop]) => { | |
val sortedList = shops.sort(_.likely > _.likely) | |
var likeSum = 0.0 | |
sortedList.foreach(likeSum += _.likely) | |
val targetList = sortedList.map{tem => new Shop(0, tem.name, tem.likely / likeSum)} | |
println(targetList) | |
sortedList.foreach(likeSum += _.likely) | |
def choosen (targetList : List[Shop], likeSum : Double) = { | |
val rand = Math.random | |
var sum = 0.0 | |
val result = targetList.find{(shop: Shop) => | |
sum += shop.likely | |
rand < sum | |
} | |
if(result == None){ | |
targetList.last | |
} else { | |
result.get | |
} | |
} | |
choosen(targetList, likeSum) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment