score:21
convert into Vector
and get random element from it
scala> val fruits = Set("apple", "grape", "pear", "banana")
fruits: scala.collection.immutable.Set[String] = Set(apple, grape, pear, banana)
scala> import scala.util.Random
import scala.util.Random
scala> val rnd=new Random
rnd: scala.util.Random = scala.util.Random@31a9253
scala> fruits.toVector(rnd.nextInt(fruits.size))
res8: String = apple
score:0
Not converting the Set
to an ordered collection but using zipWithIndex
we can attribute an index to each item in the collection,
fruits.zipWithIndex
Set((apple,0), (grape,1), (pear,2), (banana,3))
Thus for val rnd = util.Random.nextInt(fruits.size)
,
fruits.zipWithIndex.find( _._2 == rnd)
Option[(String, Int)] = Some((banana,3))
Given an empty set,
Set[String]().zipWithIndex.find( _._2 == 3)
Option[(String, Int)] = None
score:0
If you don't mind an O(n)
solution:
import util.Random
// val fruits = Set("apple", "grape", "pear", "banana")
Random.shuffle(fruits).head
// "pear"
score:1
import Scala.util.Random
val fruits = Set("apple", "grape", "pear", "banana").toVector
val sz =fruits.size
val num = Random.nextInt(sz)
fruits(num)
score:2
Solution1
Random way ( import scala.util.Random
)
scala> fruits.toList(Random.nextInt(fruits.size))
res0: java.lang.String = banana
Solution2
Math way (no imports)
scala> fruits.toList((math.random*fruits.size).toInt)
res1: String = banana
score:2
You can directly access an element of a Set with slice. I used this when I was working with a set that was changing in size, so converting it to a Vector every time seemed like overkill.
val roll = new Random ()
val n = roll nextInt (fruits size)
fruits slice (n, n + 1) last
score:3
Drawing inspiration from the other answers to this question, I've come up with:
private def randomItem[T](items: Traversable[T]): Option[T] = {
val i = Random.nextInt(items.size)
items.view(i, i + 1).headOption
}
This doesn't copy anything, doesn't fail if the Set
(or other type of Traversable
) is empty, and it's clear at a glance what it does. If you're certain that the Set
is not empty, you could use .head
instead of headOption
, returning a T
.
score:22
So, every answer posted before has complexity O(n) in terms of space, since they create a copy a whole collection in some way. Here is a solution without any additional copying (therefore it is "constant space"):
def random[T](s: Set[T]): T = {
val n = util.Random.nextInt(s.size)
s.iterator.drop(n).next
}
Source: stackoverflow.com
Related Query
- How to get a random element from a Set in Scala
- How to set and get keys from scala TreeMap?
- How to efficiently select a random element from a Scala immutable HashSet
- How to get the set of rows which contains null values from dataframe in scala using filter
- How to do this in Scala way: get the first element from Option[Seq[String]]
- How to get each double element from scala Iterator[(Double, Double)]
- How to generate the random values of map from a given set of values and then store the key and values into separate variables in scala
- How to get distinct values from an element within list of tuples in Scala
- How get random element from list in one line
- how to get all element from array of arrays of spark dataframe column scala
- How to get Scala List from Java List?
- How do I get the Scala version from within Scala itself?
- In Scala, how to get a slice of a list from nth element to the end of the list without knowing the length?
- How to choose a random element from an array in Scala?
- How to get last element of an array in scala
- How can I idiomatically "remove" a single element from a list in Scala and close the gap?
- How to get probabilities corresponding to the class from Spark ML random forest
- How to correctly get current loop count from a Iterator in scala
- Get element from Set
- How to get distinct items from a Scala Iterable, maintaining laziness
- Gatling in scala how to get url from redirect
- How to get auto-complete in Scala REPL launched from ensime?
- How to get first line from file in Scala
- How to return multiple random elements from List scala
- How to Random Choice element from Enum Scala3
- Spark, Scala - How to get Top 3 value from each group of two column in dataframe
- How do I get an AtomicReferenceFieldUpdater from a scala companion object?
- How to get Long/Int value of a enum set in Scala 2.8
- How to get a scala Map value, when the key is a tuple in which only the first element is known?
- How can I get random data generated for scala case classes with the ability to "change some values" for unit testing?
More Query from same tag
- Scala Slick Class Table Definition, Error Declaring DateTime columns
- Returning true if all items in a list are true, otherwise false
- Using scalaz state in a more complicated computation
- How to use reduceByKey to add a value into a Set in Scala Spark?
- Play ws how to map response in typesafe manner
- Cassandra filter with ordering query modeling
- Kafka Wheel Timer
- Task not serializable - Regex
- scala filtering list of strings with multiple commas
- Finding individual filenames when loading multiple files in Apache Spark
- Execution Context not getting shutdown
- convert Iteratee to Result
- Appending element to list in Scala
- How to run a Spark test from IntelliJ (or other IDE)
- how to use filter function in scala
- Implementing map on Option
- Spark - Scala - Number of days between two dates
- Java compile speed vs Scala compile speed
- Adding just specific dependencies to an SBT-packaged jar file
- Debugging Futures and Iteratees in Play 2.2
- Using IntelliJ, how can i determine whether particular function stems from Java or Scala
- scala & intellij : difficulties to create a runnnable jar
- How do I get the runtime Class of a parameterized Type in a Scala trait
- How can I use groupBy of multiple columns by passing in a variable rather than a literal
- Attach a callback to run after a scala spray server successfully sends a response
- How I am supposed to translate this spark scala line to java
- How memory allocation takes place in scala
- How to represent a dynamic form with Play forms?
- Unable to iterate Java List in Scala
- Spark - groupByKey map-side aggregation