Skip to content
This repository was archived by the owner on Sep 6, 2018. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from 6 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
18 changes: 10 additions & 8 deletions src/lesson1/task1/Simple.kt
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ fun main(args: Array<String>) {
* Пользователь задает время в часах, минутах и секундах, например, 8:20:35.
* Рассчитать время в секундах, прошедшее с начала суток (30035 в данном случае).
*/
fun seconds(hours: Int, minutes: Int, seconds: Int): Int = TODO()
fun seconds(hours: Int, minutes: Int, seconds: Int): Int = (hours * 3600 + minutes * 60 + seconds)
Copy link
Contributor

Choose a reason for hiding this comment

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

Скобки вокруг выражения здесь излишни


/**
* Тривиальная
Expand All @@ -60,31 +60,31 @@ fun seconds(hours: Int, minutes: Int, seconds: Int): Int = TODO()
* Определить длину того же отрезка в метрах (в данном случае 18.98).
* 1 сажень = 3 аршина = 48 вершков, 1 вершок = 4.445 см.
*/
fun lengthInMeters(sagenes: Int, arshins: Int, vershoks: Int): Double = TODO()
fun lengthInMeters(sagenes: Int, arshins: Int, vershoks: Int): Double = ((sagenes * 48 + arshins * 16 + vershoks)* 4.445) / 100

/**
* Тривиальная
*
* Пользователь задает угол в градусах, минутах и секундах (например, 36 градусов 14 минут 35 секунд).
* Вывести значение того же угла в радианах (например, 0.63256).
*/
fun angleInRadian(grad: Int, min: Int, sec: Int): Double = TODO()
fun angleInRadian(grad: Int, min: Int, sec: Int): Double = (grad + min/60.0 + sec/3600.0)*Math.PI/180
Copy link
Contributor

Choose a reason for hiding this comment

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

Форматирование кода должно быть одинаковым везде. Либо отделяете штуки друг от друга пробелами, либо не отделяете. Попробуйте отформатировать код при помощи IntelliJ IDEA и в дальнейшем придерживайтесь такого же стиля.


/**
* Тривиальная
*
* Найти длину отрезка, соединяющего точки на плоскости с координатами (x1, y1) и (x2, y2).
* Например, расстояние между (3, 0) и (0, 4) равно 5
*/
fun trackLength(x1: Double, y1: Double, x2: Double, y2: Double): Double = TODO()
fun trackLength(x1: Double, y1: Double, x2: Double, y2: Double): Double = sqrt(((x1-x2)*(x1-x2))+((y1-y2)*(y1-y2)))
Copy link
Contributor

Choose a reason for hiding this comment

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

Лишние скобки


/**
* Простая
*
* Пользователь задает целое число, большее 100 (например, 3801).
* Определить третью цифру справа в этом числе (в данном случае 8).
*/
fun thirdDigit(number: Int): Int = TODO()
fun thirdDigit(number: Int): Int = (number/100)%10

/**
* Простая
Expand All @@ -93,7 +93,8 @@ fun thirdDigit(number: Int): Int = TODO()
* прибыл на станцию назначения в h2 часов m2 минут того же дня (например в 13:01).
* Определите время поезда в пути в минутах (в данном случае 216).
*/
fun travelMinutes(hoursDepart: Int, minutesDepart: Int, hoursArrive: Int, minutesArrive: Int): Int = TODO()
fun travelMinutes(hoursDepart: Int, minutesDepart: Int, hoursArrive: Int, minutesArrive: Int): Int =
(hoursArrive*60+minutesArrive)-(hoursDepart*60+minutesDepart)

/**
* Простая
Expand All @@ -102,12 +103,13 @@ fun travelMinutes(hoursDepart: Int, minutesDepart: Int, hoursArrive: Int, minute
* Сколько денег будет на счету через 3 года (с учётом сложных процентов)?
* Например, 100 рублей под 10% годовых превратятся в 133.1 рубля
*/
fun accountInThreeYears(initial: Int, percent: Int): Double = TODO()
fun accountInThreeYears(initial: Int, percent: Int): Double =
(((initial+initial*percent/100.0)+(initial+initial*percent/100.0)*percent/100.0)+((initial+initial*percent/100.0)+(initial+initial*percent/100.0)*percent/100.0)*percent/100.0)
Copy link
Contributor

Choose a reason for hiding this comment

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

Все это выражение можно записать намного проще, если воспользоваться алгебраическими свойствами


/**
* Простая
*
* Пользователь задает целое трехзначное число (например, 478).
*Необходимо вывести число, полученное из заданного перестановкой цифр в обратном порядке (например, 874).
*/
fun numberRevert(number: Int): Int = TODO()
fun numberRevert(number: Int): Int =((number%10)*100)+((number/10%10)*10)+(number/100)
31 changes: 28 additions & 3 deletions src/lesson2/task1/IfElse.kt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@file:Suppress("UNUSED_PARAMETER")

package lesson2.task1

import lesson1.task1.discriminant
Expand Down Expand Up @@ -33,7 +34,13 @@ fun minBiRoot(a: Double, b: Double, c: Double): Double {
* Мой возраст. Для заданного 0 < n < 200, рассматриваемого как возраст человека,
* вернуть строку вида: «21 год», «32 года», «12 лет».
*/
fun ageDescription(age: Int): String = TODO()
fun ageDescription(age: Int): String =
when {
(age % 10) == (1) -> ("$age год")
Copy link
Contributor

Choose a reason for hiding this comment

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

Очень много лишних скобок

(age in (10..20)) -> "$age лет"
(age % 10) in (2..4) -> "$age года"
else -> ("$age лет")
}

/**
* Простая
Expand All @@ -46,6 +53,7 @@ fun timeForHalfWay(t1: Double, v1: Double,
t2: Double, v2: Double,
t3: Double, v3: Double): Double = TODO()


/**
* Простая
*
Expand All @@ -56,7 +64,14 @@ fun timeForHalfWay(t1: Double, v1: Double,
*/
fun whichRookThreatens(kingX: Int, kingY: Int,
rookX1: Int, rookY1: Int,
rookX2: Int, rookY2: Int): Int = TODO()
rookX2: Int, rookY2: Int): Int =
when {
(kingX == rookX2 && kingY == rookY1)-> 3
Copy link
Contributor

Choose a reason for hiding this comment

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

Лучше сперва посчитать в отдельные переменные, атакует ли какая-либо ладья короля, а потом уже делать по этим переменным when

(kingX == rookX1 && kingY == rookY2)-> 3
(kingX == rookX1 || kingY == rookY1)-> 1
(kingX == rookX2 || kingY == rookY2)-> 2
else -> 0}


/**
* Простая
Expand Down Expand Up @@ -89,4 +104,14 @@ fun triangleKind(a: Double, b: Double, c: Double): Int = TODO()
* Найти длину пересечения отрезков AB и CD.
* Если пересечения нет, вернуть -1.
*/
fun segmentLength(a: Int, b: Int, c: Int, d: Int): Int = TODO()
fun segmentLength(a: Int, b: Int, c: Int, d: Int): Int =
if (b<c || d<a) -1 else
Copy link
Contributor

Choose a reason for hiding this comment

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

Данное выражение лучше оформить как when

if (c>a && d<b) (d-c)
else if (a>c && b<d) (b-a)
else if (b>=c && d>=b) (b-c)
else if (d>=a && b>=d) (d-a)
else -1




7 changes: 6 additions & 1 deletion src/lesson2/task2/Logical.kt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@file:Suppress("UNUSED_PARAMETER")

package lesson2.task2

import lesson1.task1.sqr
Expand All @@ -17,7 +18,11 @@ fun pointInsideCircle(x: Double, y: Double, x0: Double, y0: Double, r: Double) =
* Четырехзначное число назовем счастливым, если сумма первых двух ее цифр равна сумме двух последних.
* Определить, счастливое ли заданное число, вернуть true, если это так.
*/
fun isNumberHappy(number: Int): Boolean = TODO()
fun isNumberHappy(number: Int): Boolean {
if ((((number % 100) / 10) + (number % 10)) == (number / 1000) + ((number) / 100) % 10)
Copy link
Contributor

Choose a reason for hiding this comment

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

  • Выражение if (cond) true else false можно заменить на cond
  • Функцию с телом в виде одного return expr можно записать как fun foo(...) = expr

Copy link
Contributor

Choose a reason for hiding this comment

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

Выражение if (cond) true else false можно заменить на cond

return true
else return false
}

/**
* Простая
Expand Down
26 changes: 22 additions & 4 deletions src/lesson3/task1/Loop.kt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@file:Suppress("UNUSED_PARAMETER")

package lesson3.task1

/**
Expand Down Expand Up @@ -34,7 +35,7 @@ fun isPrime(n: Int): Boolean {
*/
fun isPerfect(n: Int): Boolean {
var sum = 1
for (m in 2..n/2) {
for (m in 2..n / 2) {
if (n % m > 0) continue
sum += m
if (sum > n) break
Expand All @@ -57,7 +58,15 @@ fun digitCountInNumber(n: Int, m: Int): Int =
* Найти количество цифр в заданном числе n.
* Например, число 1 содержит 1 цифру, 456 -- 3 цифры, 65536 -- 5 цифр.
*/
fun digitNumber(n: Int): Int = TODO()
fun digitNumber(n: Int): Int {
var count = 0
var numb = n
Copy link
Contributor

Choose a reason for hiding this comment

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

number

Copy link
Contributor

Choose a reason for hiding this comment

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

Ап

while (n !== 0) {
numb /= 10
count++
}
return count
}

/**
* Простая
Expand All @@ -73,7 +82,17 @@ fun fib(n: Int): Int = TODO()
* Для заданных чисел m и n найти наименьшее общее кратное, то есть,
* минимальное число k, которое делится и на m и на n без остатка
*/
fun lcm(m: Int, n: Int): Int = TODO()
fun lcm(m: Int, n: Int): Int {
var k = 1
while ((k < m) || (k < n)) {
k++
Copy link
Contributor

@ice-phoenix ice-phoenix Oct 20, 2016

Choose a reason for hiding this comment

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

Почему не просто Math.max(...) или if???

Copy link
Contributor

Choose a reason for hiding this comment

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

Ап

}
while (((k % m) !== 0) || ((k % n) !== 0)) {
k++
Copy link
Contributor

Choose a reason for hiding this comment

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

Почитайте про более быстрые алгоритмы поиска НОК

Copy link
Contributor

Choose a reason for hiding this comment

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

Ап

}
return k
}


/**
* Простая
Expand Down Expand Up @@ -158,7 +177,6 @@ fun hasDifferentDigits(n: Int): Boolean = TODO()
* Например, 2-я цифра равна 4, 7-я 5, 12-я 6.
*/
fun squareSequenceDigit(n: Int): Int = TODO()

/**
* Сложная
*
Expand Down
16 changes: 14 additions & 2 deletions src/lesson4/task1/List.kt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@file:Suppress("UNUSED_PARAMETER")

package lesson4.task1

import lesson1.task1.discriminant
Expand Down Expand Up @@ -111,15 +112,26 @@ fun abs(v: List<Double>): Double = TODO()
*
* Рассчитать среднее арифметическое элементов списка list. Вернуть 0.0, если список пуст
*/
fun mean(list: List<Double>): Double = TODO()
fun mean(list: List<Double>): Double {
if (list.isEmpty() == true) return 0.0
Copy link
Contributor

Choose a reason for hiding this comment

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

  • return можно вытащить перед if
  • Функцию с телом в виде одного return expr можно записать как fun foo(...) = expr
  • if (cond == true) ==> if (cond)

else return list.sum() / list.size
}

/**
* Средняя
*
* Центрировать заданный список list, уменьшив каждый элемент на среднее арифметическое всех элементов.
* Если список пуст, не делать ничего. Вернуть изменённый список.
*/
fun center(list: MutableList<Double>): MutableList<Double> = TODO()
fun center(list: MutableList<Double>): MutableList<Double> {
val averageEqual = list.sum() / list.size
Copy link
Contributor

Choose a reason for hiding this comment

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

Что будет, если список пустой?

Copy link
Contributor

Choose a reason for hiding this comment

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

Можно было просто воспользоваться функцией mean(...)

for (i in 0..list.size - 1) {
val secondList = list[i]
list[i] = secondList-averageEqual
Copy link
Contributor

Choose a reason for hiding this comment

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

Можно list[i] = list[i] - average

}
return list
}


/**
* Средняя
Expand Down