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 14 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
34 changes: 28 additions & 6 deletions src/lesson1/task1/Simple.kt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
@file:Suppress("UNUSED_PARAMETER")

package lesson1.task1

import java.lang.Math.*
Expand Down Expand Up @@ -51,7 +52,11 @@ 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 {
val hour = hours * 60 * 60
Copy link
Contributor

Choose a reason for hiding this comment

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

Переменным лучше давать осмысленные имена, соответствующие их назначению в коде. Это не час, это количество секунд в заданном количестве часов.

val minute = minutes * 60
return hour + minute + seconds
}

/**
* Тривиальная
Expand All @@ -60,7 +65,11 @@ 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 {
val sagene = sagenes * 48
Copy link
Contributor

Choose a reason for hiding this comment

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

См. замечание выше

val arshin = arshins * 16
return (sagene + arshin + vershoks) * 4.445 / 100
}

/**
* Тривиальная
Expand All @@ -76,15 +85,19 @@ fun angleInRadian(grad: Int, min: Int, sec: Int): Double = TODO()
* Найти длину отрезка, соединяющего точки на плоскости с координатами (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 {
val sx = abs(x1 - x2)
Copy link
Contributor

Choose a reason for hiding this comment

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

Зачем брать модуль перед возведением в квадрат?

val sy = abs(y1 - y2)
return sqrt(sqr(sx) + sqr(sy))
}

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

/**
* Простая
Expand All @@ -93,7 +106,11 @@ 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 {
val sDepart = hoursDepart * 60 + minutesDepart
val sArrive = hoursArrive * 60 + minutesArrive
return sArrive - sDepart
}

/**
* Простая
Expand All @@ -110,4 +127,9 @@ fun accountInThreeYears(initial: Int, percent: Int): Double = TODO()
* Пользователь задает целое трехзначное число (например, 478).
*Необходимо вывести число, полученное из заданного перестановкой цифр в обратном порядке (например, 874).
*/
fun numberRevert(number: Int): Int = TODO()
fun numberRevert(number: Int): Int {
val x3 = number % 10
val x2 = number / 10 % 10
val x1 = number / 100
return x3 * 100 + x2 * 10 + x1
}
24 changes: 22 additions & 2 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 @@ -35,6 +36,7 @@ fun minBiRoot(a: Double, b: Double, c: Double): Double {
*/
fun ageDescription(age: Int): String = TODO()


/**
* Простая
*
Expand All @@ -44,7 +46,17 @@ fun ageDescription(age: Int): String = TODO()
*/
fun timeForHalfWay(t1: Double, v1: Double,
t2: Double, v2: Double,
t3: Double, v3: Double): Double = TODO()
t3: Double, v3: Double): Double {
val part1 = t1 * v1
val part2 = t2 * v2
val part3 = t3 * v3
val ps = (part1 + part2 + part3) / 2
when {
Copy link
Contributor

Choose a reason for hiding this comment

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

Вместо when { ... return ... return ... return ... } лучше сделать return when { ... }

part1 >= ps -> return ps / v1
part1 + part2 < ps -> return t1 + t2 + (ps - part1 - part2) / v3
else -> return t1 + (ps - part1) / v2
}
}

/**
* Простая
Expand Down Expand Up @@ -89,4 +101,12 @@ 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 {
when {
(c >= a) && (d <= b) -> return d - c
(a >= c) && (b <= d) -> return b - a
c in a..b -> return b - c
d in a..b -> return d - a
else -> return -1
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
Author

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.

Да, прошу прощения, не заметил второго коммита

}
}
19 changes: 15 additions & 4 deletions src/lesson2/task2/Logical.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
@file:Suppress("UNUSED_PARAMETER")

package lesson2.task2

import lesson1.task1.sqr


/**
* Пример
*
Expand All @@ -17,15 +19,21 @@ fun pointInsideCircle(x: Double, y: Double, x0: Double, y0: Double, r: Double) =
* Четырехзначное число назовем счастливым, если сумма первых двух ее цифр равна сумме двух последних.
* Определить, счастливое ли заданное число, вернуть true, если это так.
*/
fun isNumberHappy(number: Int): Boolean = TODO()
fun isNumberHappy(number: Int): Boolean {
val x4 = number % 10
val x3 = number / 10 % 10
val x2 = number / 100 % 10
val x1 = number / 1000
return (x1 + x2) == (x3 + x4)
}

/**
* Простая
*
* На шахматной доске стоят два ферзя (ферзь бьет по вертикали, горизонтали и диагоналям).
* Определить, угрожают ли они друг другу. Вернуть true, если угрожают.
*/
fun queenThreatens(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = TODO()
fun queenThreatens(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = ((y1 == y2) || (x1 == x2) || (Math.abs(y1 - y2) == Math.abs(x1 - x2)))

/**
* Средняя
Expand All @@ -35,7 +43,10 @@ fun queenThreatens(x1: Int, y1: Int, x2: Int, y2: Int): Boolean = TODO()
* Вернуть true, если утверждение верно
*/
fun circleInside(x1: Double, y1: Double, r1: Double,
x2: Double, y2: Double, r2: Double): Boolean = TODO()
x2: Double, y2: Double, r2: Double): Boolean {
val r = Math.sqrt(sqr(Math.abs(y1 - y2)) + sqr(Math.abs(x1 - x2))) + r1
Copy link
Contributor

Choose a reason for hiding this comment

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

Зачем модуль перед возведением в квадрат?

return (r <= r2)
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 @@ -46,4 +57,4 @@ fun circleInside(x1: Double, y1: Double, r1: Double,
* кирпич 4 х 4 х 4 пройдёт через отверстие 4 х 4.
* Вернуть true, если кирпич пройдёт
*/
fun brickPasses(a: Int, b: Int, c: Int, r: Int, s: Int): Boolean = TODO()
fun brickPasses(a: Int, b: Int, c: Int, r: Int, s: Int): Boolean = ((((a <= r) && (b <= s)) || ((a <= s) && (b <= r))) || (((a <= r) && (c <= s)) || ((a <= s) && (c <= r))) || (((b <= r) && (c <= s)) || ((b <= s) && (c <= r))))
Copy link
Contributor

Choose a reason for hiding this comment

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

Такой код лучше форматировать как

a && b
|| c && d
|| e && f
|| ...

111 changes: 99 additions & 12 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 @@ -51,43 +52,85 @@ fun digitCountInNumber(n: Int, m: Int): Int =
if (n == m) 1 else if (n < 10) 0
else digitCountInNumber(n / 10, m) + digitCountInNumber(n % 10, m)

fun pow(a: Int, b: Int): Int {
var n = 1
for (i in 1..b) {
n = n * a
}
return n
}

fun NOD(x: Int, y: Int): Int {
Copy link
Contributor

Choose a reason for hiding this comment

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

  • Функции в Котлине принято называть camelCase
  • Данную функцию лучше назвать gcd

var a = x
var b = y
while ((a != 0) && (b != 0)) {
if (a > b) a = a % b
else b = b % a
}
return a + b
}

/**
* Тривиальная
*
* Найти количество цифр в заданном числе n.
* Например, число 1 содержит 1 цифру, 456 -- 3 цифры, 65536 -- 5 цифр.
*/
fun digitNumber(n: Int): Int = TODO()
fun digitNumber(n: Int): Int = if (n / 10 != 0) digitNumber(n / 10) + 1 else 1

/**
* Простая
*
* Найти число Фибоначчи из ряда 1, 1, 2, 3, 5, 8, 13, 21, ... с номером n.
* Ряд Фибоначчи определён следующим образом: fib(1) = 1, fib(2) = 1, fib(n+2) = fib(n) + fib(n+1)
*/
fun fib(n: Int): Int = TODO()
fun fib(n: Int): Int {
var f1 = 1
var f2 = 0
var result = 1
if (n < 3) return result
Copy link
Contributor

Choose a reason for hiding this comment

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

Сколько раз будет выполнено тело цикла ниже, если n < 3? Имеет ли смысл данная проверка?

else
for (i in 3..n) {
f2 = result
result = result + f1
f1 = f2
}
return result
}

/**
* Простая
*
* Для заданных чисел m и n найти наименьшее общее кратное, то есть,
* минимальное число k, которое делится и на m и на n без остатка
*/
fun lcm(m: Int, n: Int): Int = TODO()
fun lcm(m: Int, n: Int): Int = (m * n) / NOD(m, n)

/**
* Простая
*
* Для заданного числа n > 1 найти минимальный делитель, превышающий 1
*/
fun minDivisor(n: Int): Int = TODO()
fun minDivisor(n: Int): Int {
var res = 2
while (true) {
if (n % res == 0) return res
res++
}
}

/**
* Простая
*
* Для заданного числа n > 1 найти максимальный делитель, меньший n
*/
fun maxDivisor(n: Int): Int = TODO()
fun maxDivisor(n: Int): Int {
var res = n - 1
Copy link
Contributor

Choose a reason for hiding this comment

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

Нет ли более точной верхней границы для возможных делителей, чем n?

Copy link
Author

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.

Если мы ищем делители числа n, не равные n, какое максимальное значение может принимать любой другой делитель?

while (true) {
if (n % res == 0) return res
res--
}
}

/**
* Простая
Expand All @@ -96,7 +139,7 @@ fun maxDivisor(n: Int): Int = TODO()
* Взаимно простые числа не имеют общих делителей, кроме 1.
* Например, 25 и 49 взаимно простые, а 6 и 8 -- нет.
*/
fun isCoPrime(m: Int, n: Int): Boolean = TODO()
fun isCoPrime(m: Int, n: Int): Boolean = (NOD(m, n) == 1)

/**
* Простая
Expand Down Expand Up @@ -131,7 +174,17 @@ fun cos(x: Double, eps: Double): Double = TODO()
* Поменять порядок цифр заданного числа n на обратный: 13478 -> 87431.
* Не использовать строки при решении задачи.
*/
fun revert(n: Int): Int = TODO()
fun revert(n: Int): Int {
var k = pow(10, digitNumber(n) - 1)
var revertNumber = 0
Copy link
Contributor

Choose a reason for hiding this comment

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

Лучше revertedNumber

var number = n
while (k > 0) {
revertNumber = revertNumber + k * (number % 10)
number = number / 10
k = k / 10
}
return revertNumber
}

/**
* Средняя
Expand All @@ -140,15 +193,19 @@ fun revert(n: Int): Int = TODO()
* первая цифра равна последней, вторая -- предпоследней и так далее.
* 15751 -- палиндром, 3653 -- нет.
*/
fun isPalindrome(n: Int): Boolean = TODO()
fun isPalindrome(n: Int): Boolean = revert(n) == n

/**
* Средняя
*
* Для заданного числа n определить, содержит ли оно различающиеся цифры.
* Например, 54 и 323 состоят из разных цифр, а 111 и 0 из одинаковых.
*/
fun hasDifferentDigits(n: Int): Boolean = TODO()
fun hasDifferentDigits(n: Int): Boolean {
for (i in 0..9)
if (digitNumber(n) == digitCountInNumber(n, i)) return false
return true
}

/**
* Сложная
Expand All @@ -157,7 +214,22 @@ fun hasDifferentDigits(n: Int): Boolean = TODO()
* 149162536496481100121144...
* Например, 2-я цифра равна 4, 7-я 5, 12-я 6.
*/
fun squareSequenceDigit(n: Int): Int = TODO()
fun squareSequenceDigit(n: Int): Int {
var square = 0
var sum = 0
var count = 1
var number = 0
while (sum < n) {
square = count * count
count++
sum = sum + digitNumber(square)
}
count = sum - n
if (count != 0) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Зачем эта проверка? Что сделает код ниже, если count == 0?

Copy link
Author

Choose a reason for hiding this comment

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

Ненужные действия - исправил. В последней задачи тоже надо исправить, но поздно сообразил (после того как уже запушил), не стал лишний раз коммит делать.

number = square / pow(10, count)
return number % 10
} else return square % 10
}

/**
* Сложная
Expand All @@ -166,4 +238,19 @@ fun squareSequenceDigit(n: Int): Int = TODO()
* 1123581321345589144...
* Например, 2-я цифра равна 1, 9-я 2, 14-я 5.
*/
fun fibSequenceDigit(n: Int): Int = TODO()
fun fibSequenceDigit(n: Int): Int {
var fibn = 0
var sum = 0
var count = 1
var number = 0
while (sum < n) {
fibn = fib(count)
count++
sum = sum + digitNumber(fibn)
}
count = sum - n
if (count != 0) {
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
Author

Choose a reason for hiding this comment

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

Да, я вчера заметил, исправлю

number = fibn / pow(10, count)
return number % 10
} else return fibn % 10
}