Scala: Random List of Val Order

2019-04-17 07:09发布

问题:

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. 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?

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

回答1:

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)

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.