Skip to content

My homework #56

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
40 changes: 36 additions & 4 deletions src/main/kotlin/ru/otus/homework/NaturalList.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package ru.otus.homework

import java.util.Collections

/**
* Список натуральных чисел от 1 до n
* @param n Последнее натуральное число в списке
Expand Down Expand Up @@ -35,14 +37,24 @@ class NaturalList(n: Int) : List<Int> {
* Вернуть под-список этого списка, включая [fromIndex] и НЕ включая [toIndex]
*/
override fun subList(fromIndex: Int, toIndex: Int): List<Int> {
TODO("Not yet implemented")
val list = mutableListOf<Int>()
for(element in fromIndex+1 until toIndex+1){
list.add(element)
}
return list.toList()
}

/**
* Returns true if list contains all numbers in the collection
*/
override fun containsAll(elements: Collection<Int>): Boolean {
TODO("Not yet implemented")
for(element in elements){
if(element in 1 .. size){
Copy link
Collaborator

Choose a reason for hiding this comment

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

Тут можно написать element !in elements, чтобы не делать лишнюю ветку.

} else {
return false
}
}
return true
}

override fun toString(): String {
Expand All @@ -53,13 +65,33 @@ class NaturalList(n: Int) : List<Int> {
* Функция должна возвращать true, если сравнивается с другой реализацией списка тех же чисел
* Например, NaturalList(5) должен быть равен listOf(1,2,3,4,5)
*/
override fun equals(other: Any?): Boolean = false
override fun equals(other: Any?): Boolean {
if (this === other) return true
try {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Лучше использовать other as? Collection и сравнить это дело с null. Выброс исключения - относительно дорогое удовольствие. Тут это не так важно, но не нужно привыкать

other as Collection<Int>
} catch (e: Exception) {
return false
}
if(size != other.size) return false
for(element in other){
if (other.indexOf(element) != indexOf(element)) return false
}

return true
}

/**
* Функция должна возвращать тот же 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 (element in 1 .. size) {
val integer = element.hashCode()
hashCode = 31 * hashCode + integer
}
return hashCode
}
}

private class NaturalIterator(private val n: Int) : Iterator<Int> {
Expand Down
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 { (K, V) -> V to K }.toMap()
4 changes: 2 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,11 @@ 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> = sortedWith(compareBy ({ it.surname}, {it.name}))