Start learning free

LESSON 115 OF 677 · ARRAYS I

Slicing an ArrayBuffer in Scala

Lesson

TL ; DR:

buf.slice(i, j) is a new ArrayBuffer with the items from index i up to, not including, j. The original doesn't change.


val letters = scala.collection.mutable.ArrayBuffer("a", "b", "c", "d", "e")

val middle = letters.slice(1, 4)
println(middle)    // ArrayBuffer(b, c, d)

println(letters)   // ArrayBuffer(a, b, c, d, e)


Full lesson:

Sometimes you need only part of an ArrayBuffer, like the first few items. The slice method copies that part into a new ArrayBuffer.

Give it the start index and the end index. The item at the end index is not included. So letters.slice(1, 4) has the items at 1, 2 and 3.

That makes the length easy to see: 4 - 1 = 3 items.

To go to the very end, use the size as the end index:

val tail = letters.slice(3, letters.size)
println(tail)   // ArrayBuffer(d, e)

The original ArrayBuffer stays as it was.

An end past the size is no error. So letters.slice(3, 100) simply stops at the end.


Your task

runners holds a race's runners, in the order they finished.

Put the first three in a new ArrayBuffer named podium. Put everyone else, from index 3 to the end, in one named rest.

The code below prints both, then the length of runners.

Expected output:

Ana Ben Cleo
Dan Eve
5
STEP 1 OF 2
    Ctrl + Enter to check