-
Notifications
You must be signed in to change notification settings - Fork 102
Sidorina_Test_1 #71
Sidorina_Test_1 #71
Conversation
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson1.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 11 / 12 Example: 4 / 4 Succeeded:
Failed:
Seed: -2615085513165313255 ownerElenaLaufeyson [] |
src/lesson1/task1/Simple.kt
Outdated
* Вывести значение того же угла в радианах (например, 0.63256). | ||
*/ | ||
fun angleInRadian(grad: Int, min: Int, sec: Int): Double = TODO() | ||
fun angleInRadian(grad: Int, min: Int, sec: Int): Double = (Math.PI / 180)*(grad + min/60 + sec/3600) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
min/60 и sec/3600 -- это целочисленное деление (нацело). А поскольку в примерах минут и секунд не больше 59, результат этого деления будет всегда равен 0. Чтобы операция деления имела вещественный результат, один из её аргументом должен быть вещественным. Проще всего этого добиться, добавив дробную часть константе.
src/lesson1/task1/Simple.kt
Outdated
*/ | ||
fun travelMinutes(hoursDepart: Int, minutesDepart: Int, hoursArrive: Int, minutesArrive: Int): Int = TODO() | ||
fun travelMinutes(hoursDepart: Int, minutesDepart: Int, hoursArrive: Int, minutesArrive: Int): | ||
Int = (minutesArrive + 60*hoursArrive) - (minutesDepart + 60*hoursDepart) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Обычно здесь перенос делается так:
fun travelMinutes(hoursDepart: Int, minutesDepart: Int, hoursArrive: Int, minutesArrive: Int): Int =
(minutesArrive + 60*hoursArrive) - (minutesDepart + 60*hoursDepart)
Тогда заголовок функции у вас весь в одной строчке, а тело в другой -- лучше читается.
fun angleInRadian() { | ||
assertEquals(0.63256, angleInRadian(36, 14, 35), 1e-5) | ||
assertEquals(0.63256, angleInRadian(36, 14, 35), 1e-2) | ||
assertEquals(Math.PI / 2.0, angleInRadian(90, 0, 0), 1e-5) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Здесь неспроста была указана допустимая погрешность именно 1e-5. Вы её увеличили, и как результат не видите собственную ошибку (см. выше).
…кцию angleInRadian), а также сделала 3 задания из второго урока.
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson1.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 12 / 12 Example: 4 / 4 Succeeded:
Seed: 4722322226857675651 lesson2.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 2 / 7 Example: 1 / 1 Succeeded:
Failed:
Seed: 4722322226857675651 ownerElenaLaufeyson [] |
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson2.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 2 / 7 Example: 1 / 1 Succeeded:
Failed:
Seed: -1546190477764130964 ownerElenaLaufeyson [] |
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson2.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 3 / 7 Example: 1 / 1 Succeeded:
Failed:
Seed: 5745979226007047722 ownerElenaLaufeyson [] |
Хорошо, первый урок засчитан. |
src/lesson2/task1/IfElse.kt
Outdated
val s1 = t1*v1 | ||
val s2 = t2*v2 | ||
val s3 = t3*v3 | ||
val HalfS = (s1 + s2 + s3)/2 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Переменные не следует называть с большой буквы
rookX1: Int, rookY1: Int, | ||
rookX2: Int, rookY2: Int): Int = TODO() | ||
rookX2: Int, rookY2: Int): Int { | ||
return when { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это решение можно записать существенно короче
src/lesson2/task1/IfElse.kt
Outdated
if (HalfS == 0.0) return Double.NaN | ||
return when { | ||
HalfS == s1 -> t1 | ||
HalfS == s2 -> t2 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это условие неверное
src/lesson2/task1/IfElse.kt
Outdated
val s2 = t2*v2 | ||
val s3 = t3*v3 | ||
val HalfS = (s1 + s2 + s3)/2 | ||
if (HalfS == 0.0) return Double.NaN |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В задании явно не написано, каким должен быть результат, если весь пройденный путь равен нулю. Строго говоря, в подобной ситуации должен подходить любой ответ в интервале от 0 до t1 + t2 + t3, Double.NaN как признак неопределённости ответа тоже подходит. Поэтому, заявление бота о том, что ваш ответ в этой ситуации неверен -- неправильно.
src/lesson2/task1/IfElse.kt
Outdated
return when { | ||
HalfS == s1 -> t1 | ||
HalfS == s2 -> t2 | ||
(HalfS < s1) && (v1 != 0.0) -> HalfS/v1 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А бывает так, что Halfs < s1 && v1 == 0.0? Если да, придумайте тест на эту ситуацию и добавьте его в тестовую функцию.
По второму уроку незначительные замечания по коду. Вы можете также, если чувствуете в себе силы, порешать более сложные задачи из второго урока |
Исправлены ошибки в функциях timeForHalfWay и whichRookThreatens и решена функция rookOrBishopThreatens
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson2.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 3 / 7 Example: 1 / 1 Succeeded:
Failed:
Seed: 7538209373031074599 ownerElenaLaufeyson [] |
Ваши ответы в задаче про ладью и слона верные, сообщение бота ошибочно. |
{ | ||
if (rookX in min(bishopX, kingX)..max(bishopX, kingX) && | ||
rookY in min(bishopY, kingY)..max(bishopY, kingY)) | ||
dangerbishop = false |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Правильный способ выравнивания здесь такой:
if (rookX in ... &&
rookY in ...) {
dangerBishop = false
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Несмотря на то, что в if выполняется один оператор, рекомендуется всё равно ставить фигурные скобки
// => король под угрозой слона | ||
if (abs(bishopX - kingX) == abs(bishopY - kingY)) | ||
{ | ||
dangerbishop = true |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Название переменной состоит из двух слов: danger + bishop. Такие имена по Code Style следует записывать так называемой camelCase нотацией: dangerBishop.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
То же с dangerRook
dangerrook = true | ||
//если между ладьей и королем стоит слон | ||
if (bishopY == kingY && bishopX in min(kingX,rookX)..max(kingX,rookX)) | ||
dangerrook = false |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Здесь тоже немножко неаккуратно выравнивание
} | ||
///////////////// | ||
return when { | ||
dangerbishop == true && dangerrook == true -> 3 //угроза и от слона, и от ладьи |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Такие условия записываются просто как dangerBishop && dangerRook
, запись == true
здесь избыточна
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson2.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 6 / 7 Example: 1 / 1 Succeeded:
Seed: -3386947621547262434 ownerElenaLaufeyson [] |
Сделана функция isNumberHappy.
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson2.task2Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 2 / 5 Example: 1 / 1 Succeeded:
Seed: 3188460160754680153 ownerElenaLaufeyson [] |
* Если такой треугольник не существует, вернуть -1. | ||
*/ | ||
fun triangleKind(a: Double, b: Double, c: Double): Int = TODO() | ||
fun triangleKind(a: Double, b: Double, c: Double): Int |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Здесь и далее -- по правилам форматирования кода, принятым в Котлине и Джаве, открывающая фигурная скобка ставится в конце предыдущей строки:
fun triangleKind(...): Int {
...
}
{ | ||
val sum1 = (number/1000 + (number/100)%10) | ||
val sum2 = ((number/10)%10 + number%10) | ||
if (sum1 == sum2) return true |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Лучше просто return sum1 == sum2
Доделан полностью.
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson2.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 7 / 7 Example: 1 / 1 Succeeded:
Seed: 4952497240925688625 ownerElenaLaufeyson [] |
Доделала полностью.
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson2.task2Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 5 / 5 Example: 1 / 1 Succeeded:
Seed: 3433128578214087946 ownerElenaLaufeyson [] |
Решила, но еще не полностью задания 3 урока.
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson3.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 11 / 18 Example: 4 / 4 Succeeded:
Failed:
Seed: -7984670626923526759 ownerElenaLaufeyson [] |
Исправлена функция fun digitNumber.
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson3.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 11 / 18 Example: 4 / 4 Succeeded:
Failed:
Seed: -3236048993605126349 ownerElenaLaufeyson [] |
Исправлена тривиальная задача.
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson3.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 12 / 18 Example: 4 / 4 Succeeded:
Failed:
Seed: -6487337881386781300 ownerElenaLaufeyson [] |
var cur = 0.0 | ||
var sinx = 0.0 | ||
var n = 1 | ||
while (true) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Весь цикл while нужно сдвинуть на 4 пробела назад
n += 2 | ||
} | ||
return sinx | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Подумайте, как поведёт себя это решение, если x = 20.0? А при x = 100.0? А при x = 1000.0? Сколько членов ряда потребуется, чтобы достичь требуемой точности? Как будет вести себя погрешность вычислений (помним, что она всегда присутствует при работе с Double)? Можно ли как-то избежать этих неприятных эффектов? Придумайте решение, и добавьте в тестовую функцию один или несколько тестов для подобных ситуаций (сравнивая результат вашей функции с результатом Math,sin с помощью assertEquals).
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Про то, как пишутся тестовые функции -- см. раздел chapter01 в tutorial.
Второй урок засчитан. Обратите внимание на замечание к функции sin в третьем уроке. |
Решила одну сложную задачу.
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson3.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 13 / 18 Example: 4 / 4 Succeeded:
Failed:
Seed: 4691404823435061465 ownerElenaLaufeyson [] |
Исправлена проблема с функцией sin и добавлена тестовая функция.
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson3.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 13 / 18 Example: 4 / 4 Succeeded:
Failed:
Seed: -2503733154380961846 ownerElenaLaufeyson [] |
src/lesson3/task1/Loop.kt
Outdated
cur = next | ||
} | ||
return when { | ||
str[n-1] == '0' -> 0 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Всё проще -- str[n - 1] - '0'
. Символы тоже можно вычитать (при этом вычитаются их коды), а цифровые символы идут в любой таблице кодировки по порядку от '0' до '9'.
assertEquals(1.0, sin(Math.PI / 2.0, 1e-5), 1e-5) | ||
assertEquals(0.0, sin(Math.PI, 1e-5), 1e-5) | ||
assertEquals(-1.0, sin(3.0 * Math.PI / 2.0, 1e-5), 1e-5) | ||
assertEquals(Math.sin(20.0), sin(20.0, 1e-5), 1e-5) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А что будет, если точность повысить хотя бы до 1e-10? Double, вообще-то, имеет точность в 13-14 десятичных знаков.
src/lesson3/task1/Loop.kt
Outdated
var next = 0 | ||
if (n == 1 || n == 2) return 1 | ||
while (str.length <= n) { | ||
str += cur.toString() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Здесь задам ещё такой вопрос (бонусный). Как поведёт себя ваша функция при достаточно больших значениях n? Какие факторы могут мешать ей работать правильно? Можно ли что-то сделать с этими факторами, и если можно -- как? Подумайте на эту тему, ответьте мне здесь в комментарии
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
При достаточно больших значениях n число Фибоначчи может выйти за границы типа Int и придется использовать тип Long.
Также можно столкнуться с проблемой переполнения строки или использование большого объема памяти, поэтому лучше рассматривать не всю последовательность целиком, а каждое отдельное число этой последовательности. При данном решении можно даже не использовать строки.
fun fibSequenceDigit(n: Int): Int {
var call = 0 //общая длина всех "проверенных" цифр
var ccur =0 //длина текущего числа
var cur = 0 //текущее число
var i=1 //номер текущего числа
var ab=0 //какая цифра(по счету) из текущего числа (при заходе числа за границу n)
//понадобится
var k=0 //последняя цифра текущего числа
while(true) {
cur = fib(i) //приравниваем текущему число число последовательности Фиб. с
//номером i
ccur = digitNumber(cur) //считаем длину текущего числа(сколько в нем цифр?)
call+=ccur //увеличиваем длину обработанной пос-ти на длину текущего числа
if(call==n) return cur%10 //если длина обраб. пос-ти равна n, то
// возвращаем последнюю цифру текущего числа
if(call > n) { //если обработанная длина "вышла за" n
ab=n-(call-ccur) //какая цифра данного числа под номером n?
while(cur>0) { //поиск нужной цифры текущего числа
k=cur%10
if(ccur==ab) return k
cur/=10
ccur--
}
}
i++
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, ответ верный
В целом с третьим уроком всё в порядке. Только вот решение проблемы с синусом вы так и не придумали. Плюс есть ещё бонусный вопрос про fibSequenceDigit. |
Доделала весь третий урок.
authorSidorina_Test1 [elena_petrova98@mail.ru] lesson3.task1Author: Sidorina_Test1 [elena_petrova98@mail.ru] Owner: ElenaLaufeyson [] Total: 15 / 18 Example: 4 / 4 Succeeded:
Failed:
Seed: 4968718745040624060 ownerElenaLaufeyson [] |
Елена, я сейчас этот Pull Request закрою, а проблему с sin / cos оставлю вам на подумать. Всё остальное решено верно. |
Решила первый урок.