Start learning free

LESSON 380 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: head v4 — Negative n drops the tail in Scala

Practice

Same signature as v2/v3, but now n may be negative. Real head -n -K prints all lines except the last K. So when n < 0 return all lines except the last |n|; when n ≥ 0 behave exactly like v3 (return the first n, capped at the input length). If |n| is at least the number of lines, nothing is left, so return the empty string.

Function signature:

def head(lines: List[String], n: Int): String

Example (negative n):

Input: lines = ["a", "b", "c", "d", "e"], n = -2

Output: "a\nb\nc"

When printed:
a
b
c

Compute the cut-off with a single if/else expression: when n < 0, the end index is math.max(0, lines.size + n); otherwise it's math.min(n, lines.size). Then take(end) and mkString("\n").

val end = if (n < 0) math.max(0, lines.size + n) else math.min(n, lines.size)
lines.take(end).mkString("\n")


The full solution:
class Solution {
    def head(lines: List[String], n: Int): String = {
        val end = if (n < 0) math.max(0, lines.size + n) else math.min(n, lines.size)
        lines.take(end).mkString("\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check

    Head V4 in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free