Start learning free

LESSON 628 OF 677 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: sort v4 — Sort by Key Column

Practice

Build the next version of the Unix sort command, this time with the -k flag baked in. Each input line is comma-separated and is guaranteed to have at least field fields (a field may be empty, as in "a,,c"). Given a 1-indexed field number, sort the lines stably by the value at that field, compared as strings by character code, and return the original lines joined by newlines (\n). Lines whose fields are equal keep their original relative order. This matches the real command sort -t, -k N,N -s in the C locale. If the list is empty, return the empty string.

Function signature:

def sortLines(lines: Array[String], field: Int): String

Example:

Input: field = 2, lines = ["alice,30", "bob,25", "carol,40"]

Output: "bob,25\nalice,30\ncarol,40"

When printed:
bob,25
alice,30
carol,40

Use sortBy with a function that splits each line on "," (with limit -1, so empty trailing fields are kept) and returns the field - 1 element. Scala's sortBy is a stable sort.

The full solution:
class Solution {
    def sortLines(lines: Array[String], field: Int): String = {
        val sortedLines = lines.sortBy(l => l.split(",", -1)(field - 1))
        return sortedLines.mkString("\n")
    }
}

STEP 1 OF 2
    Ctrl + Enter to check