Save Contacts
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 21 of 63.
Build a Contact Book that saves, finds and removes contacts, then lists names and reports statistics. A mutable map stores one phone per name. Commands in one call share that map; each new call starts fresh. The supplied input code reads three equally sized lists. Implement the command loop in contactBook.
val contacts = mutableMapOf<String, String>()Challenge
HardComplete contactBook with parameters commands: List<String>, names: List<String>, phones: List<String>. Build an in-memory contact book that starts empty for each function call. The three lists have equal length, at most 100. At each index, commands selects an operation; names and phones supply its arguments. Names are nonempty lowercase ASCII words; phones are nonempty digit strings and must stay strings to preserve leading zeros. Every command produces one reply in the returned list. Support PUT: save or replace the phone for the supplied name, then reply saved. Inputs contain only commands supported in this step. Ignored argument strings can be any nonempty text.
Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.
Return a value of type List<String>. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.
Try it yourself
fun contactBook(commands: List<String>, names: List<String>, phones: List<String>): List<String> {
// Write your solution here.
return emptyList()
}
fun main() {
val commandsCount = readln().toInt()
val commands = mutableListOf<String>()
for (i0 in 0 until commandsCount) {
val commandsItem = readLine().orEmpty()
commands.add(commandsItem)
}
val namesCount = readln().toInt()
val names = mutableListOf<String>()
for (i0 in 0 until namesCount) {
val namesItem = readLine().orEmpty()
names.add(namesItem)
}
val phonesCount = readln().toInt()
val phones = mutableListOf<String>()
for (i0 in 0 until phonesCount) {
val phonesItem = readLine().orEmpty()
phones.add(phonesItem)
}
println(contactBook(commands, names, phones))
}All lessons in Logic & Flow
4Nested Collections
Lists of ListsTraversing RowsRow SummariesFlattening Nested ListsRecap - Seating Rows7Collection Pipelines
Transforming with MapFiltering ValuesTesting Collection RulesAccumulating with FoldRecap - Approved Totals5Project - Contact Book
Save ContactsFind ContactsPractice on your own: Kotlin playground