Advertisement
Kosheen

Список покупок

Dec 26th, 2024
549
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.50 KB | None | 0 0
  1. import java.util.*
  2.  
  3. fun main() {
  4.     val input = Scanner(System.`in`)
  5.     val purchases = mutableMapOf<String, MutableMap<String, Int>>()
  6.  
  7.     println("Введите покупки (нажмите Enter для завершения):")
  8.  
  9.     while (true) {
  10.         val line = input.nextLine().trim()
  11.         if (line.isEmpty()) break  // остановить ввод, если введена пустая строка
  12.  
  13.         if (line.isBlank()) continue  // игнорируем пустые строки
  14.         val parts = line.split(" ")
  15.         if (parts.size != 3) continue  // пропускаем некорректные строки
  16.  
  17.         val customer = parts[0]
  18.         val product = parts[1]
  19.         val quantity = parts[2].toIntOrNull() ?: continue  // игнорируем некорректные количества
  20.  
  21.         // Обновляем информацию о покупках
  22.         purchases.computeIfAbsent(customer) { mutableMapOf() }
  23.             .merge(product, quantity) { oldQuantity, newQuantity -> oldQuantity + newQuantity }
  24.     }
  25.  
  26.     // Сортируем покупателей в лексикографическом порядке
  27.     val sortedCustomers = purchases.keys.sorted()
  28.  
  29.     for (customer in sortedCustomers) {
  30.         println("$customer:")
  31.         val products = purchases[customer]?.toList()?.sortedBy { it.first } ?: emptyList()
  32.         for ((product, quantity) in products) {
  33.             println("$product $quantity")
  34.         }
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement