Scala:Val Order的随机列表

时间:2016-10-12 02:51:26

标签: list scala random shuffle

我有一些val应该随机进入结果列表。这是代码:

def motivation(name:String, score:Int){
val quote1 = "You're not lost. You're locationally challenged." //score=10
val quote2 = "Time is the most valuable thing a man can spend." //score=20
val quote3 = "At times one remains faithful to a cause." //score=10
val quote4 = "Only because its opponents do not cease to be insipid." //score=10
val quote5 = "Life can be complicated." //score=20

case Some(score) => val quoteRes = shufle(????)
}
  1. 如何标记每个引号的分数,以便能够计算出来。
  2. 如何根据名称的score随机选择引号并同时执行shuffle订单?
  3. 例如,如果John(姓名)有40(得分),结果可能是quotes2 + quotes3 + quotes4或quotes4 + quotes5或quotes1 + quotes2 + quotes5

1 个答案:

答案 0 :(得分:0)

我想我可能会从所有引号和各自的分数开始。

val quotes = Map( "quote this" -> 10
                , "no quote" -> 20
                , "quoteless" -> 10
                )

然后以尽可能多的方式组合它们。

// all possible quote combinations
val qCombos = (1 to quotes.size).flatMap(quotes.keys.toList.combinations)

将其转换为Map按其各自的得分总和键入。

// associate all quote combinations with their score total
val scoreSum = qCombos.groupBy(_.map(quotes).sum)

现在你打电话查看所有引用,当它们合并时,总和到给定的数量。

// get all the quote combinations that have this score total
scoreSum(20) 
//res0: IndexedSeq[List[String]] = Vector(List(no quote), List(quote this, quoteless))

至于以随机顺序显示结果,因为您已经询问了twice already,并得到了好的答案,我会假设这样做了不会成为问题。