Scala:Val顺序的随机列表 [英] Scala: Random List of Val Order

查看:75
本文介绍了Scala:Val顺序的随机列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些val应该随机出现在结果列表中.这是代码:

I have some of val that should randomly coming to list of result. Here's the code:

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的顺序也一样?
  1. How do I marked score of each quotes so it will be able to calculated.
  2. How do I randomly pick the quotes based of score of name and do the shuffle the order also?

例如,如果John(name)有40(分数),则结果可能是quotes2 + quotes3 + quotes4或quotes4 + quotes5或quotes1 + quotes2 + quotes5

for example if John(name) has 40(score) the result could be quotes2+quotes3+quotes4 or quotes4+quotes5 or quotes1+quotes2+quotes5

推荐答案

我想我很可能会从所有引号和它们各自的分数开始.

I guess I'd be likely to start with all the quotes and their respective scores.

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

然后以尽可能多的方式将它们组合在一起.

Then combine them in as many ways as possible.

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

将其转换为以各自得分总和为键的Map.

Turn that into a Map keyed by their respective score sums.

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

现在您可以调用查找所有报价,这些报价加起来后加总成给定的数量.

Now you call look up all the quotes that, when combined, sum to a given amount.

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

关于随机显示结果,因为您已经问过两次 已经,并且已经获得了很好的答案,我认为这不会成为问题

As for presenting the results in a random order, since you've already asked about that twice already, and gotten good answers, I'll assume that's not going to be a problem.

这篇关于Scala:Val顺序的随机列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆