Skip to content

kotlin 4 hw #57

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.9.10'
id 'org.jetbrains.kotlin.jvm' version '2.1.10'
}

test {
Expand All @@ -16,4 +16,5 @@ repositories {
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib"
implementation 'org.junit.jupiter:junit-jupiter:5.8.1'
implementation "org.jetbrains.kotlin:kotlin-reflect:2.1.10"
}
30 changes: 24 additions & 6 deletions src/main/kotlin/ru/otus/homework/NaturalList.kt
Original file line number Diff line number Diff line change
Expand Up @@ -35,31 +35,47 @@ class NaturalList(n: Int) : List<Int> {
* Вернуть под-список этого списка, включая [fromIndex] и НЕ включая [toIndex]
*/
override fun subList(fromIndex: Int, toIndex: Int): List<Int> {
TODO("Not yet implemented")
return filterIndexed { index, _ -> index in fromIndex until toIndex }
}

/**
* Returns true if list contains all numbers in the collection
*/
override fun containsAll(elements: Collection<Int>): Boolean {
TODO("Not yet implemented")
return elements.all { this.contains(it) }
}

override fun toString(): String {
return "NaturalList(1..$size)"
return joinToString(prefix = "[", postfix = "]", separator = ", ")
}

/**
* Функция должна возвращать true, если сравнивается с другой реализацией списка тех же чисел
* Например, NaturalList(5) должен быть равен listOf(1,2,3,4,5)
*/
override fun equals(other: Any?): Boolean = false
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this === other) return true
if (other is List<*> && (other as List<*>)[0] is Int && (other as List<*>).size == size) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне кажется, тут слишком подробно и можно сократить до сравнения размеров и потом поэлементного сравнения с ранним выходом. contains - довольно дорогая операция тут получается, так как на каждый элемент обходится вся коллекция. А нам нужно сравнить порядок элементов и их значение. Если по значению элементы совпадают, но порядок у них разный - списки не считаются равными!

containsAll(other as List<*>)
return all { (other as List<*>).contains(it) }
}
return false
}

private fun naturalList() = this

/**
* Функция должна возвращать тот же hash-code, что и список другой реализации тех же чисел
* Например, NaturalList(5).hashCode() должен быть равен listOf(1,2,3,4,5).hashCode()
*/
override fun hashCode(): Int = -1
override fun hashCode(): Int {
var hashCode = 1
for (i in this) {
hashCode = 31 * hashCode + (i.hashCode())
}
return hashCode
}
}

private class NaturalIterator(private val n: Int) : Iterator<Int> {
Expand All @@ -73,19 +89,21 @@ private class NaturalIterator(private val n: Int) : Iterator<Int> {
}

private class NaturalListIterator(private val n: Int, index: Int = 0) : ListIterator<Int> {
private var index:Int = index.coerceIn(0, n - 1)
private var index: Int = index.coerceIn(0, n - 1)
override fun hasNext(): Boolean = index < n
override fun hasPrevious(): Boolean = index > 0
override fun next(): Int = if (hasNext()) {
++index
} else {
throw NoSuchElementException()
}

override fun nextIndex(): Int = index
override fun previous(): Int = if (hasPrevious()) {
index--
} else {
throw NoSuchElementException()
}

override fun previousIndex(): Int = index
}
2 changes: 1 addition & 1 deletion src/main/kotlin/ru/otus/homework/mapswap/mapSwap.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ package ru.otus.homework.mapswap
/**
* Меняет местами ключи и значения
*/
fun <K, V> Map<K, V>.swap(): Map<V, K> = TODO("Доделать swap")
fun <K, V> Map<K, V>.swap(): Map<V, K> = map { it.value to it.key }.toMap()
6 changes: 4 additions & 2 deletions src/main/kotlin/ru/otus/homework/persons/persons.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ package ru.otus.homework.persons
/**
* Отсортировать список персон по возрасту в порядке убывания
*/
fun List<Person>.sortByAge(): List<Person> = TODO("Доделать sortByAge")
fun List<Person>.sortByAge(): List<Person> = sortedByDescending { it.age }

/**
* Отсортировать список персон по фамилии
* - Фамилии сортируются по алфавиту в порядке возрастания
* - Если фамилии совпадают, персоны сортируются по имени в порядке возрастания
*/
fun List<Person>.sortByName(): List<Person> = TODO("Доделать sortBySurname")
fun List<Person>.sortByName(): List<Person> {
return sortedWith(compareBy({ it.surname }, { it.name }))
}