Skip to content

Instantly share code, notes, and snippets.

@numa08
Created November 7, 2012 14:45
Show Gist options
  • Save numa08/4032012 to your computer and use it in GitHub Desktop.
Save numa08/4032012 to your computer and use it in GitHub Desktop.
Scalaで重み付き乱択アルゴリズム ref: http://qiita.com/items/9fab26545ae931a1dc67
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