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 10 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
aaef63b
Мы решили fun seconds
Sep 8, 2016
5df633c
Мы решили fun lengthInMeters и angleInRadian
Sep 8, 2016
2b345c3
Выполнила все задания из первого урока.
AnastasiyaTarasova Sep 12, 2016
2089f93
Lesson2. task1,2
Sep 27, 2016
4e87474
Lesson1\\requested changes\\
Sep 28, 2016
e07bbf8
Lesson2.task1,2\\requested changes\\
Sep 28, 2016
86deb7e
Lesson3
Oct 9, 2016
54489b4
Lesson3/digitNumber\
Oct 9, 2016
0723736
Lesson3/fix\
Oct 12, 2016
eea6e06
Lesson 4
Oct 22, 2016
f52459b
fix all
Oct 27, 2016
da7fe92
fix maxDivisor
Oct 28, 2016
d53148d
fix maxDivisor + Lesson5
Oct 31, 2016
9551b2d
fix maxDivisor + Lesson5
Oct 31, 2016
cf5013f
fix dateStrToDigit
Oct 31, 2016
2b7153a
Lesson5 + fixes
Nov 6, 2016
fd6576c
Lesson5 + fixes
Nov 6, 2016
d2f8933
Lesson5 + fixes
Nov 6, 2016
b14546b
fixes =)
Nov 14, 2016
ffcb823
Impossible + lesson7
Nov 18, 2016
a3296aa
fix
Nov 18, 2016
efdf1f2
fix
Nov 18, 2016
8401f8d
fix
Nov 18, 2016
34bcdc0
lesson7(+ 1 Normal) + some fixes
Nov 24, 2016
5ffb88c
lesson6(Impossible)
Nov 24, 2016
9bcf582
fixes? really?
Nov 29, 2016
48bf8bd
fix
Dec 5, 2016
573e3e9
fix
Dec 5, 2016
a7361f8
fix
Dec 5, 2016
a9a2bb9
fix
Dec 12, 2016
633ff7a
new (lesson 8)
Dec 12, 2016
ddace56
substrings
Dec 12, 2016
09d43f4
substrings
Dec 12, 2016
9880866
substrings
Dec 12, 2016
96fd842
substrings
Dec 12, 2016
d4239b7
fix
Dec 16, 2016
c77f014
fix
Dec 16, 2016
b9388ef
fix
Dec 16, 2016
556a71a
fix
Dec 16, 2016
9106d90
fix
Dec 16, 2016
8d3e526
fix
Dec 16, 2016
0e0caf8
regex
Dec 16, 2016
5f211aa
sumSubMatrix
Dec 17, 2016
530aa30
countSubstrings
Dec 18, 2016
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
27 changes: 19 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) = hours * 3600 + minutes * 60 + seconds

/**
* Тривиальная
Expand All @@ -60,31 +60,33 @@ 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 =
((vershoks * 4.445 + arshins * 16* 4.445 + sagenes * 48* 4.445) / 100)
Copy link
Contributor

Choose a reason for hiding this comment

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

Лишние скобки вокруг законченного выражения


/**
* Тривиальная
*
* Пользователь задает угол в градусах, минутах и секундах (например, 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 + sec / 60.0) /60.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.

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


/**
* Тривиальная
*
* Найти длину отрезка, соединяющего точки на плоскости с координатами (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) = sqrt(sqr(x2 - x1) + sqr(y2 - y1))

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

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


/**
* Простая
Expand All @@ -93,7 +95,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) =
((hoursArrive * 60 + minutesArrive) - (hoursDepart * 60 + minutesDepart))

/**
* Простая
Expand All @@ -102,12 +105,20 @@ 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 {
val k = initial + initial*0.01*percent
return (k + k*0.01*percent) + (k + k*0.01*percent)*0.01*percent
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 {
val x1 = number / 100
val x2 = (number / 10) % 10
val x3 = number % 10
return x3*100+x2*10+x1
}
66 changes: 55 additions & 11 deletions src/lesson2/task1/IfElse.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,15 @@ 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 {
if ((age / 10) % 10 == 1)
Copy link
Contributor

Choose a reason for hiding this comment

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

Этот if может быть частью следующего за ним when

return "$age лет"
return when (age % 10) {
1 -> "$age год"
in 2..4 -> "$age года"
else -> "$age лет"
}
}
/**
* Простая
*
Expand All @@ -44,8 +51,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 s1 = v1 * t1
val s2 = v2 * t2
val s = s1 + s2 + v3 * t3
if (s / 2 <= s1) return (s / 2) / v1
Copy link
Contributor

Choose a reason for hiding this comment

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

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

else if ((s / 2 > s1) && (s / 2 <= s1 + s2)) return t1 + ((s / 2 - s1) / v2)
else return t1 + t2 + (s / 2 - s1 - s2) / v3
}
/**
* Простая
*
Expand All @@ -56,8 +69,15 @@ 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 {
return when {
(kingX != rookX1) && (kingX != rookX2) && (kingY != rookY1) && (kingY != rookY2) -> 0
Copy link
Contributor

Choose a reason for hiding this comment

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

Выражения, соответствующие факту атаки короля той или иной ладьей, следует вынести в отдельные переменные

((kingX == rookX1) || (kingY == rookY1)) && (kingX != rookX2) && (kingY != rookY2) -> 1
((kingX == rookX2) || (kingY == rookY2)) && (kingX != rookX1) && (kingY != rookY1) -> 2
((kingX == rookX1) || (kingY == rookY1)) && ((kingX == rookX2) || (kingY == rookY2)) -> 3
else -> -1
}
}
/**
* Простая
*
Expand All @@ -69,8 +89,15 @@ fun whichRookThreatens(kingX: Int, kingY: Int,
*/
fun rookOrBishopThreatens(kingX: Int, kingY: Int,
rookX: Int, rookY: Int,
bishopX: Int, bishopY: Int): Int = TODO()

bishopX: Int, bishopY: Int): Int {
return if ((kingX != rookX) && (kingY != rookY)
Copy link
Contributor

Choose a reason for hiding this comment

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

  • Данное выражение лучше оформить как when
  • Факты атаки короля ладьей или слоном следует вынести в отдельные переменные

&& ((Math.abs(kingX - bishopX)) != (Math.abs(kingY - bishopY)))) 0
else if (((kingX == rookX) || (kingY == rookY)) &&
((Math.abs(kingX - bishopX)) != (Math.abs(kingY - bishopY)))) 1
else if ((kingX != rookX) && (kingY != rookY) &&
((Math.abs(kingX - bishopX)) == (Math.abs(kingY - bishopY)))) 2
else 3
}
/**
* Простая
*
Expand All @@ -79,8 +106,17 @@ fun rookOrBishopThreatens(kingX: Int, kingY: Int,
* прямоугольным (вернуть 1) или тупоугольным (вернуть 2).
* Если такой треугольник не существует, вернуть -1.
*/
fun triangleKind(a: Double, b: Double, c: Double): Int = TODO()

fun triangleKind(a: Double, b: Double, c: Double): Int {
val cosA = (b * b + c * c - a * a) / (2 * b * c)
Copy link
Contributor

Choose a reason for hiding this comment

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

Достаточно посчитать косинус угла против максимальной стороны треугольника

val cosB = (a * a + c * c - b * b) / (2 * a * c)
val cosC = (a * a + b * b - c * c) / (2 * a * b)
return when {
((a + b) <= c) || ((a + c) <= b) || ((b + c) <= a) -> -1
(Math.abs(cosA) < 0.00001) || (Math.abs(cosB) < 0.00001) || (Math.abs(cosC) < 0.00001) -> 1
(cosA < 0) || (cosB < 0) || (cosC < 0) -> 2
else -> 0
}
}
/**
* Средняя
*
Expand All @@ -89,4 +125,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 {
return when {
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

(d < a) || (c > b) -> -1
(c >= a) && (b >= d) -> d - c
(a >= c) && (b >= d) -> d - a
(a >= c) && (d >= b) -> b - a
else -> b - c
}
}
23 changes: 19 additions & 4 deletions 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,15 +18,23 @@ 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 f = (number / 1000) % 10
Copy link
Contributor

Choose a reason for hiding this comment

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

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

val th = (number / 100) % 10
val t = (number / 10) % 10
val o = number % 10
return f + th == t + o
}

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

}

/**
* Средняя
Expand All @@ -35,7 +44,9 @@ 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 {
return (Math.sqrt(sqr(x1 - x2) + sqr(y1 - y2)) + r1) <= r2
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

}

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

(b <= r) && (c <= s) || (b <= r) && (a <= s) ||
(c <= r) && (a <= s) || (c <= r) && (b <= s)
}
Loading