Scala:Val顺序的随机列表
Scala: Random List of Val Order
我有一些 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
顺序排列?
例如,如果约翰(名字)有 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))
至于以随机顺序呈现结果,既然你已经问过这个问题 ,并且得到了很好的答案,我认为这不会成为问题。
我有一些 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
顺序排列?
例如,如果约翰(名字)有 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))
至于以随机顺序呈现结果,既然你已经问过这个问题