1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scalaで重み付き乱択アルゴリズム

Last updated at Posted at 2012-11-07

Play Framework始めました。

Scala良いよScala って思ってたけど、案外イバラの道感。

先日Rubyで実装したものと同じ物をScalaでやってみました。

あれ?Scalaってもっと格好良く書けるんじゃねえの?あれ?あれえ?

chooser.scala
	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)
	}	
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?