Problem overview
The method wordLengths receives an ArrayBuffer[String] named words and returns an ArrayBuffer[Int] with the length of each word, in the same order. For ArrayBuffer("I", "love", "pancakes") the result is ArrayBuffer(1, 4, 8).
Approach
One word gives exactly one length, so the loop runs once per word and adds one number to a new buffer each time. Adding at the end keeps the order: the first word's length is first, and so on. ArrayBuffer("banana", "kiwi", "fig") gives ArrayBuffer(6, 4, 3).
Step by step
- Create the result. A
valnamedlengthsholds an emptyArrayBuffer[Int](). - Loop over the words with
for (word <- words). - Append each length.
word.lengthis the number of characters, and+=adds it at the end of the buffer. - Return after the loop. A return inside the loop would stop after the first word.
The solution in Scala
class Solution {
def wordLengths(words: ArrayBuffer[String]): ArrayBuffer[Int] = {
val lengths = ArrayBuffer[Int]()
for (word <- words) {
lengths += word.length
}
return lengths
}
}
valdoes not freeze the buffer. It only fixes which bufferlengthsrefers to. The buffer itself can still grow.lengthwithout parentheses. On aString,word.lengthis written without(), and it counts characters.ArrayBuffer[Int]()withoutnew. The companion object'sapplybuilds the buffer.- A shorter form.
words.map(_.length)gives the same result for anArrayBuffer. The lesson uses the explicit loop to practise building a result.
What the for loop does
for (word <- words) reads as "for each word in words". The part before <- is a new name that holds the current element on each pass, and the loop body runs once per element, from the first to the last. This form doesn't produce a value by itself: it runs its body for its side effects, here the += on the buffer.
Scala has a second form, for (word <- words) yield word.length, which builds a new collection from the values of the body. For an ArrayBuffer it produces an ArrayBuffer(1, 4, 8) on the same input. The lesson uses the first form to practise creating a buffer, appending to it and returning it.
The lesson's file already imports ArrayBuffer, so the short name works. In a program of your own, add import scala.collection.mutable.ArrayBuffer at the top.
Where this pattern leads
Turning each element of a collection into one new value is called mapping, and it is the most common shape of loop there is. The recipe never changes: create an empty result, visit every element, append the transformed value, return the result. Only the transformation, here word.length, differs from one problem to the next. Written with the library, the same idea is words.map(_.length), where _.length is a short way to write "take each word and ask for its length".
Following the loop
For ArrayBuffer("I", "love", "pancakes"), the buffer grows by one number per word:
| word | lengths afterwards |
|---|---|
| I | ArrayBuffer(1) |
| love | ArrayBuffer(1, 4) |
| pancakes | ArrayBuffer(1, 4, 8) |
The result always has as many entries as words, because the loop never skips a word and never adds two numbers for one word. Nothing here removes or reorders anything, so order is kept for free.
Edge cases and common mistakes
- One word.
ArrayBuffer("code")givesArrayBuffer(4). - Returning inside the loop. Only the first length would come back.
- Using
Array[Int]as the result type. The method's signature asks for anArrayBuffer[Int], which can grow as the loop adds lengths; a plainArrayhas a fixed size.
Testing
ArrayBuffer("I", "love", "pancakes")givesArrayBuffer(1, 4, 8).ArrayBuffer("banana", "kiwi", "fig")givesArrayBuffer(6, 4, 3).ArrayBuffer("code")givesArrayBuffer(4).
