Filling the Scala list with random double capture forever

I am new to Scala and trying to get a list of random double values:

The fact is that when I try to run this, it takes too long compared to its Java partner. Any ideas on why this or a suggestion for a better approach?

def random: Double = java.lang.Math.random()
var f = List(0.0)
for (i <- 1 to 200000)
 ( f = f ::: List(random*100)) 
 f = f.tail
+5
source share
7 answers

You can also achieve this as follows:

List.fill(200000)(math.random)

the same thing happens, for example. Array ...

Array.fill(200000)(math.random)

etc.

+21
source

You can build an endless stream of random doubles:

def randomList(): Stream[Double] = Stream.cons(math.random, randomList)

val f = randomList().take(200000)

, , . 200 000 . f var.

+9

:

val it = Iterator.continually(math.random)
it.take(200000).toList

Stream continually, .

+7

, , java, Java-. Java . , .

-, , , .

, prepend, .

+5

, , ​​ , += ( Java-).

?

val f = for (_ <- 1 to 200000) yield (math.random * 100)

: var f = List(0.0)... f = f.tail var f: List[Double] = Nil . ( , ;)

+4

! :

def randlist(n: Int, part: List[Double] = Nil): List[Double] = {
  if (n<=0) part
  else randlist(n-1, 100*random :: part)
}

:

(1 to 200000).map(_ => 100*random).toList
+2

, Vector List. O (1) prepend, Vector O (1) append. , , Vector:

def random: Double = java.lang.Math.random()
var f: Vector[Double] = Vector()
for (i <- 1 to 200000)
  f = f :+ (random*100)

?

+1

All Articles