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 12 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 x1 = 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.

Переменным лучше давать осмысленные имена

Copy link
Contributor

Choose a reason for hiding this comment

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

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

val x2 = minutes * 60
return x1 + x2 + 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 s = 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 a = arshins * 16
return (s + a + 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
}
30 changes: 28 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,14 @@ 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 ps = (t1 * v1 + t2 * v2 + t3 * v3) / 2
Copy link
Contributor

Choose a reason for hiding this comment

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

Повторно вычисляемые подвыражения лучше вынести в отдельные переменные

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 { ... }

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

/**
* Простая
Expand Down Expand Up @@ -89,4 +98,21 @@ 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 ((c in a..b) && (d in a..b)) {
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 d - c
} else if ((c in a..b) && (d !in a..b)) {
return b - c
} else if ((d in a..b) && (c !in a..b)) {
return d - a
} else if ((a in c..d) && (b in c..d)) {
return b - a
} else if ((a in c..d) && (b !in c..d)) {
return d - a
} else if ((b in c..a) && (a !in c..d)) {
return b - c
} else {
return -1
}
}
21 changes: 17 additions & 4 deletions src/lesson2/task2/Logical.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
@file:Suppress("UNUSED_PARAMETER")

package lesson2.task2

import lesson1.task1.sqr
import lesson4.task1.abs
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.

Никогда не добавлял импорт ни в один урок, он сам


/**
* Пример
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 = if ((y1 == y2) && (x1 == x2) && (Math.abs(y1 - y2) == Math.abs(x1 - x2))) true else false
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


/**
* Средняя
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.

Подобное выражение лучше записать как R <= r2

}

/**
* Средняя
Expand All @@ -46,4 +57,6 @@ 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 {
return ((a * b <= r * s) || (a * c <= r * s) || (b * c <= r * s))
Copy link
Contributor

Choose a reason for hiding this comment

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

  • Функцию с телом в виде одного return expr можно записать как fun foo(...) = expr
  • Данный набор условий не проверяет, проходит ли кирпич в отверстие

}
117 changes: 105 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,82 @@ 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
}

/**
* Тривиальная
*
* Найти количество цифр в заданном числе 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 {
var k = Math.min(n, m)
val min = Math.min(m, n)
Copy link
Contributor

Choose a reason for hiding this comment

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

Зачем два раза вызывать min(m, n)?

while (true) {
if ((k % m == 0) && (k % n == 0)) return k
else k = k + min
Copy link
Contributor

Choose a reason for hiding this comment

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

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

}
}

/**
* Простая
*
* Для заданного числа 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 +136,16 @@ 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 {
var a: Int = m
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.

  • Объясните, что делает ваш новый код, в комментарии
  • Нельзя ли вынести часть функциональности вашей функции в отдельную функцию, которая могла бы помочь при решении других задач?

Copy link
Author

Choose a reason for hiding this comment

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

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

var b: Int = n
while ((a != 0) && (b != 0)) {
if (a > b) a = a % b
else b = b % a
}
if (a + b == 1) return true
else return false
}

/**
* Простая
Expand Down Expand Up @@ -131,7 +180,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 = 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 + pow(10, k) * (number % 10)
Copy link
Contributor

Choose a reason for hiding this comment

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

Почему бы вместо переменной k и постоянного возведения в степень не начать с требуемой степени десятки и уменьшать ее на 10 каждый раз?

Copy link
Author

Choose a reason for hiding this comment

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

Хорошая идея:)

number = number / 10
k--
}
return revertNumber
}

/**
* Средняя
Expand All @@ -140,15 +199,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 +220,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 +244,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
}