Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A nice way to split a Range in Scala

Tags:

scala

Suppose I have the following code, is there any way to simplify this to more a beautify way?

var i = 0
val step = 100
val limitArr = new ArrayBuffer[(Int, Int)]
while (i < rddPartNumber) {
   limitArr += ((i, i + step))
   i += step
}
like image 647
Djvu Avatar asked Dec 07 '22 19:12

Djvu


2 Answers

What you are doing is basically looping over a sequence of numbers. That can be expressed by mapping on a Range

val limits = (0 until rddPartNumber by step) map {i => (i , i + step)}

Or if you prefer for syntax

for {i <- 0 until rddPartNumber by step}
yield (i, i + step)
like image 159
puhlen Avatar answered Dec 29 '22 22:12

puhlen


Use Array.tabulate for an interval from a to rddPartNumber as follows

Array.tabulate((rddPartNumber-a)/step) { i => (i*step, i*step+step) }
like image 38
elm Avatar answered Dec 29 '22 22:12

elm