我有一些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(????)
}
- 我如何标记每个报价的分数,以便能够计算。
- 我如何根据名称的
score
随机选择报价,并且shuffle
也做订单?
例如,如果John(name)有40(分数),结果可以是quotes2+quotes3+quotes4或quotes4+quotes5或quotes1+quotes2+quotes5
我想我可能会从所有的引号和它们各自的分数开始。
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))
至于以随机顺序呈现结果,既然你已经问过两次了,并且得到了很好的答案,我认为这不会是一个问题。