From 2f6f07903967c80000de52864ca6501179902586 Mon Sep 17 00:00:00 2001 From: Sergei Korotaev Date: Fri, 28 Feb 2025 22:32:39 +0300 Subject: [PATCH 1/2] Initial commit --- build.gradle | 2 +- .../kotlin/ru/otus/homework/NaturalList.kt | 15 +++++++--- .../ru/otus/homework/mapswap/mapSwap.kt | 23 ++++++++++++++- .../ru/otus/homework/persons/persons.kt | 28 +++++++++++++++++-- 4 files changed, 60 insertions(+), 8 deletions(-) diff --git a/build.gradle b/build.gradle index e145486..94bb66b 100644 --- a/build.gradle +++ b/build.gradle @@ -1,5 +1,5 @@ plugins { - id 'org.jetbrains.kotlin.jvm' version '1.9.10' + id 'org.jetbrains.kotlin.jvm' version '2.0.21' } test { diff --git a/src/main/kotlin/ru/otus/homework/NaturalList.kt b/src/main/kotlin/ru/otus/homework/NaturalList.kt index a8a41b1..6d0710b 100644 --- a/src/main/kotlin/ru/otus/homework/NaturalList.kt +++ b/src/main/kotlin/ru/otus/homework/NaturalList.kt @@ -35,14 +35,21 @@ class NaturalList(n: Int) : List { * Вернуть под-список этого списка, включая [fromIndex] и НЕ включая [toIndex] */ override fun subList(fromIndex: Int, toIndex: Int): List { - TODO("Not yet implemented") + val result = mutableListOf() + for (i in fromIndex until toIndex) { + result.add(this[i]) + } + return result } /** * Returns true if list contains all numbers in the collection */ override fun containsAll(elements: Collection): Boolean { - TODO("Not yet implemented") + elements.forEach { + if (!this.contains(it)) return false + } + return true } override fun toString(): String { @@ -53,13 +60,13 @@ class NaturalList(n: Int) : List { * Функция должна возвращать true, если сравнивается с другой реализацией списка тех же чисел * Например, NaturalList(5) должен быть равен listOf(1,2,3,4,5) */ - override fun equals(other: Any?): Boolean = false + override fun equals(other: Any?): Boolean = subList(0, size) == other /** * Функция должна возвращать тот же hash-code, что и список другой реализации тех же чисел * Например, NaturalList(5).hashCode() должен быть равен listOf(1,2,3,4,5).hashCode() */ - override fun hashCode(): Int = -1 + override fun hashCode(): Int = subList(0, size).hashCode() } private class NaturalIterator(private val n: Int) : Iterator { diff --git a/src/main/kotlin/ru/otus/homework/mapswap/mapSwap.kt b/src/main/kotlin/ru/otus/homework/mapswap/mapSwap.kt index 913be37..f77b957 100644 --- a/src/main/kotlin/ru/otus/homework/mapswap/mapSwap.kt +++ b/src/main/kotlin/ru/otus/homework/mapswap/mapSwap.kt @@ -3,4 +3,25 @@ package ru.otus.homework.mapswap /** * Меняет местами ключи и значения */ -fun Map.swap(): Map = TODO("Доделать swap") \ No newline at end of file +fun Map.swap(): Map { + val result = mutableMapOf() + this.forEach { + result[it.value] = it.key + } + return result +} + + + + +fun main() { + val m = mapOf( + 1 to "one", + 2 to "two", + 3 to "three" + ) + val s = m.swap() + + println("Initial: $m") + println("Swapped: $s") +} \ No newline at end of file diff --git a/src/main/kotlin/ru/otus/homework/persons/persons.kt b/src/main/kotlin/ru/otus/homework/persons/persons.kt index fc1265d..1411ebe 100644 --- a/src/main/kotlin/ru/otus/homework/persons/persons.kt +++ b/src/main/kotlin/ru/otus/homework/persons/persons.kt @@ -3,11 +3,35 @@ package ru.otus.homework.persons /** * Отсортировать список персон по возрасту в порядке убывания */ -fun List.sortByAge(): List = TODO("Доделать sortByAge") +fun List.sortByAge(): List = sortedByDescending { it.age } /** * Отсортировать список персон по фамилии * - Фамилии сортируются по алфавиту в порядке возрастания * - Если фамилии совпадают, персоны сортируются по имени в порядке возрастания */ -fun List.sortByName(): List = TODO("Доделать sortBySurname") \ No newline at end of file +fun List.sortByName(): List = sortedBy { it.name }.sortedBy { it.surname } + + + +fun List.mapToPerson(): List { + return this.map { + val name = it.split(", ")[0] + val surname = it.split(", ")[1] + val age = it.split(", ")[2] + Person(name, surname, age.toInt()) + } +} + +fun main() { + val p = listOf( + "Иван, Иванов, 1", + "Сидор, Сидоров, 100", + "Петр, Петров, 10", + "Иван, Сидоров, 100" + ).mapToPerson() + + println("Initial: $p") + println("By Age: ${p.sortByAge()}") + println("By Name: ${p.sortByName()}") +} \ No newline at end of file From 017e69313af09e149cbf57f91da42169ae370853 Mon Sep 17 00:00:00 2001 From: Sergei Korotaev Date: Sat, 1 Mar 2025 14:42:26 +0300 Subject: [PATCH 2/2] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87=D0=B0=D0=BD=D0=B8=D1=8F?= =?UTF-8?q?.=20=D0=90=D0=BB=D0=B3=D0=BE=D1=80=D0=B8=D1=82=D0=BC=20=D0=B2?= =?UTF-8?q?=D1=8B=D1=87=D0=B8=D1=81=D0=BB=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=85?= =?UTF-8?q?=D0=B5=D1=88=20=D0=B4=D0=BB=D1=8F=20=D1=81=D0=BF=D0=B8=D1=81?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BD=D0=B5=20=D0=BD=D0=B0=D1=88=D0=B5=D0=BB=20?= =?UTF-8?q?-=20=D0=BF=D0=BE=D0=B4=D1=81=D0=BC=D0=BE=D1=82=D1=80=D0=B5?= =?UTF-8?q?=D0=BB=20=D1=83=20=D1=81=D0=BE=D1=81=D0=B5=D0=B4=D0=B5=D0=B9,?= =?UTF-8?q?=20=D1=81=D0=BB=D0=B8=D1=88=D0=BA=D0=BE=D0=BC=20=D0=BC=D0=BD?= =?UTF-8?q?=D0=BE=D0=B3=D0=BE=20=D0=B2=D1=80=D0=B5=D0=BC=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=20=D1=83=D1=88=D0=BB=D0=BE.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../kotlin/ru/otus/homework/NaturalList.kt | 31 +++++++++++++++++-- .../ru/otus/homework/mapswap/mapSwap.kt | 10 +----- .../ru/otus/homework/persons/persons.kt | 3 +- 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/src/main/kotlin/ru/otus/homework/NaturalList.kt b/src/main/kotlin/ru/otus/homework/NaturalList.kt index 6d0710b..2dc9f01 100644 --- a/src/main/kotlin/ru/otus/homework/NaturalList.kt +++ b/src/main/kotlin/ru/otus/homework/NaturalList.kt @@ -46,6 +46,7 @@ class NaturalList(n: Int) : List { * Returns true if list contains all numbers in the collection */ override fun containsAll(elements: Collection): Boolean { + /** return elements.all { it in this } или */ elements.forEach { if (!this.contains(it)) return false } @@ -60,13 +61,39 @@ class NaturalList(n: Int) : List { * Функция должна возвращать true, если сравнивается с другой реализацией списка тех же чисел * Например, NaturalList(5) должен быть равен listOf(1,2,3,4,5) */ - override fun equals(other: Any?): Boolean = subList(0, size) == other + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is List<*>) return false + return this.size == other.size + } + /** * Функция должна возвращать тот же hash-code, что и список другой реализации тех же чисел * Например, NaturalList(5).hashCode() должен быть равен listOf(1,2,3,4,5).hashCode() */ - override fun hashCode(): Int = subList(0, size).hashCode() + override fun hashCode(): Int { + /** + * Hashcode is calculated using below formula + * + * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[0] + * + * where: + * + * s is ith character in the string + * n is length of the string + * + */ + /** + * Нашел описание для строки, оставлю на всякий. Не нашел для целочисленного списка, + * подсмотрел у соседей + */ + var hash = 1 + for (i in this) { + hash = 31 * hash + i.hashCode() + } + return hash + } } private class NaturalIterator(private val n: Int) : Iterator { diff --git a/src/main/kotlin/ru/otus/homework/mapswap/mapSwap.kt b/src/main/kotlin/ru/otus/homework/mapswap/mapSwap.kt index f77b957..5c2bc6d 100644 --- a/src/main/kotlin/ru/otus/homework/mapswap/mapSwap.kt +++ b/src/main/kotlin/ru/otus/homework/mapswap/mapSwap.kt @@ -3,15 +3,7 @@ package ru.otus.homework.mapswap /** * Меняет местами ключи и значения */ -fun Map.swap(): Map { - val result = mutableMapOf() - this.forEach { - result[it.value] = it.key - } - return result -} - - +fun Map.swap(): Map = entries.associate { (k, v) -> v to k } fun main() { diff --git a/src/main/kotlin/ru/otus/homework/persons/persons.kt b/src/main/kotlin/ru/otus/homework/persons/persons.kt index 1411ebe..32a1998 100644 --- a/src/main/kotlin/ru/otus/homework/persons/persons.kt +++ b/src/main/kotlin/ru/otus/homework/persons/persons.kt @@ -10,8 +10,7 @@ fun List.sortByAge(): List = sortedByDescending { it.age } * - Фамилии сортируются по алфавиту в порядке возрастания * - Если фамилии совпадают, персоны сортируются по имени в порядке возрастания */ -fun List.sortByName(): List = sortedBy { it.name }.sortedBy { it.surname } - +fun List.sortByName(): List = sortedWith(compareBy({it.surname}, {it.name})) fun List.mapToPerson(): List {