Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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: 15 additions & 3 deletions src/main/kotlin/exercise1/task1/GradeCalculator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,25 @@ import java.util.Scanner
*/

internal fun calculateGrade(score: Int): Int {
TODO("Implement me!!!")
// require(score in 0..100) {
Copy link
Owner

Choose a reason for hiding this comment

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

nit: Please remove the commented-out code before pushing the changes.

// "Score is out of range 0-100!"
// }
return when {
score in 0..50 -> 5
score in 51..60 -> 6
score in 61..70 -> 7
score in 71..80 -> 8
score in 81..90 -> 9
score in 91..100 -> 10
else -> throw IllegalArgumentException("Score out of range 0-100")
}
}

fun main() {
print("Enter student score: ")
val scanner = Scanner(System.`in`)
val score = scanner.nextInt()

calculateGrade(score)
val grade = calculateGrade(score)
val msg = if(grade != 5) "Student's grade is: $grade" else "Student didn't pass the exam"
println(msg)
}
9 changes: 8 additions & 1 deletion src/main/kotlin/exercise1/task2/PrintPyramid.kt
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,14 @@ package org.jetbrains.exercise1.task2
*/

internal fun printPyramid(level: Int) {
TODO("Implement me!!!")
require (level in 3..15) {
"Level is out of range"
}
for(i in 1..level) {
val spaces = " ".repeat(level - i)
val stars = "*".repeat(2 * i - 1)
println("$spaces$stars$spaces")
}
}

fun main() {
Expand Down
12 changes: 11 additions & 1 deletion src/main/kotlin/exercise1/task3/ScrabbleWordScoreCalculator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,18 @@ package org.jetbrains.exercise1.task3
*
*/

val charMap = mapOf(
'A' to 1, 'E' to 1, 'I' to 1, 'O' to 1, 'U' to 1, 'L' to 1, 'N' to 1, 'R' to 1, 'S' to 1, 'T' to 1,
'D' to 2, 'G' to 2,
'B' to 3, 'C' to 3, 'M' to 3, 'P' to 3,
'F' to 4, 'H' to 4, 'V' to 4, 'W' to 4, 'Y' to 4,
'K' to 5,
'J' to 8, 'X' to 8,
'Q' to 10, 'Z' to 10,
)

internal fun calculateWordScrabbleScore(word: String): Int {
TODO("Implement me!!!")
return word.sumOf { charMap.getOrDefault(it.uppercaseChar(), 0) }
Copy link
Owner

Choose a reason for hiding this comment

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

Very nice usage of Map#getOrDefault function. Great job!

}

fun main() {
Expand Down
12 changes: 10 additions & 2 deletions src/main/kotlin/exercise1/task4/PalindromeNumber.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,19 @@ package org.jetbrains.exercise1.task4
*/

internal fun isPalindrome(x: Int): Boolean {
TODO("Implement me!!!")
require(x in -1000000..1000000) {
"Number must be in range -1000000..1000000"
}
return when {
x < 0 -> false
x.toString().length == 1 -> true
x.toString() == x.toString().reversed() -> true
else -> false
}
}

fun main() {
val number = 121
val number = 56465
if (isPalindrome(number)) {
println("Number $number is a palindrome.")
} else {
Expand Down
8 changes: 5 additions & 3 deletions src/main/kotlin/exercise1/task5/ReverseInteger.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.jetbrains.exercise1.task5

import kotlin.math.abs

/**
* Task 5: Given an integer x, return x with its digits reversed.
*
Expand Down Expand Up @@ -27,10 +29,10 @@ package org.jetbrains.exercise1.task5
*/

internal fun reverseInteger(x: Int): Int {
TODO("Implement me!!!")
require(x in -1000000..1000000) { "Number must be integer in range -1000000..1000000" }
return if (x < 0) ("-" + abs(x).toString().reversed()).toInt() else x.toString().reversed().toInt()
Copy link
Owner

Choose a reason for hiding this comment

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

In this particular case,
abs(x).toString().reversed()).toInt() and x.toString().reversed().toInt() expressions always provide the same result, so it's a safe to store a abs(x).toString().reversed()).toInt() value to a variable and only prefix the - sign in case number is negative.

}

fun main() {
val integer = -321
val integer = -78952
println("Reverse integer of number $integer is ${reverseInteger(integer)}")
}
16 changes: 15 additions & 1 deletion src/main/kotlin/exercise2/task1/FindPairOfHighestSum.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package exercise2.task1

import exercise2.task2.findHighestSumPairFunctional
import org.jetbrains.exercise2.common.isEqualsTo
import org.jetbrains.exercise2.task3.findPairWithBiggestDifference

Expand All @@ -18,7 +19,20 @@ import org.jetbrains.exercise2.task3.findPairWithBiggestDifference
*/

internal fun List<Int>.findHighestSumPair(): Pair<Int, Int> {
TODO("Implement me!!")
require(this.size >= 2) { "List must have at least two integers." }
require(this.all { it in -1000..1000 })
var maxSum = Integer.MIN_VALUE
var pair: Pair<Int, Int>? = null
for((index, item) in this.dropLast(1).withIndex()) {
Copy link
Owner

Choose a reason for hiding this comment

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

Well-used withIndex extension function. Good job!

for(j in (index + 1) until this.size) {
val sum = item + this[j]
if(sum >= maxSum) {
maxSum = sum
pair = Pair(item, this[j])
}
}
}
return pair!!
}

fun main() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package exercise2.task2

import exercise2.task1.findHighestSumPair
import org.jetbrains.exercise2.common.isEqualsTo
import org.jetbrains.exercise2.task3.findPairWithBiggestDifference

Expand All @@ -20,7 +21,9 @@ import org.jetbrains.exercise2.task3.findPairWithBiggestDifference
*/

internal fun List<Int>.findHighestSumPairFunctional(): Pair<Int, Int> {
TODO("Implement me!!")
require(this.size >= 2) { "List must have at least two integers." }
require(this.all { it in -1000..1000 })
return this.sortedDescending().let { sortedList -> sortedList.first() to sortedList[1] }
}

fun main() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.jetbrains.exercise2.task3

import exercise2.task2.findHighestSumPairFunctional
import org.jetbrains.exercise2.common.isEqualsTo
import kotlin.math.abs

Expand All @@ -17,24 +18,26 @@ import kotlin.math.abs
*/

internal fun List<Int>.findPairWithBiggestDifference(): Pair<Int, Int> {
// TODO refactor me to functional approach and make tests pass!!!
var resultPair: Pair<Int, Int>? = null
var biggestDifference = Int.MIN_VALUE

for (i in this.indices) {
for (j in (i + 1) until this.size) {
val first = this[i]
val second = this[j]
val absDifference = abs(first - second)

if (absDifference >= biggestDifference) {
biggestDifference = absDifference
resultPair = Pair(first, second)
}
}
}

return resultPair!!
// STANDARD WAY:
Copy link
Owner

Choose a reason for hiding this comment

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

nit: Same thing a in the first task, please keep your code clean and do not push commented out code :)

// var resultPair: Pair<Int, Int>? = null
// var biggestDifference = Int.MIN_VALUE
//
// for (i in this.indices) {
// for (j in (i + 1) until this.size) {
// val first = this[i]
// val second = this[j]
// val absDifference = abs(first - second)
//
// if (absDifference >= biggestDifference) {
// biggestDifference = absDifference
// resultPair = Pair(first, second)
// }
// }
// }
//
// FUNCTIONAL APPROACH:
require(this.size >= 2) { "List must have at least two integers." }
return this.sortedDescending().let { sortedList -> sortedList.first() to sortedList.last() }
}

fun main() {
Expand Down
19 changes: 13 additions & 6 deletions src/main/kotlin/exercise2/task4/ProcessCountriesData.kt
Original file line number Diff line number Diff line change
Expand Up @@ -59,27 +59,33 @@ internal val countries = listOf(
*/

internal fun List<Country>.findCountryWithBiggestTotalArea(): Country {
TODO("Implement me!!!")
return this.maxBy { it.totalAreaInSquareKilometers }
}

internal fun List<Country>.findCountryWithBiggestPopulation(): Country {
TODO("Implement me!!!")
return this.maxBy { it.population }
}

internal fun List<Country>.findCountryWithHighestPopulationDensity(): Country {
TODO("Implement me!!!")
return this.maxBy { it.population / it.totalAreaInSquareKilometers }
}

internal fun List<Country>.findCountryWithLowestPopulationDensity(): Country {
TODO("Implement me!!!")
return this.minBy { it.population / it.totalAreaInSquareKilometers }
}

internal fun List<Country>.findLanguageSpokenInMostCountries(): String {
TODO("Implement me!!!")
return this.flatMap { it.languages }
Copy link
Owner

Choose a reason for hiding this comment

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

Good job! 👏🏻

.groupingBy { it }
.eachCount()
.toList()
.sortedByDescending { it.second }
.map{ it -> it.first }
.first()
Copy link
Owner

Choose a reason for hiding this comment

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

Here, we can apply a small optimization and avoid unnecessary map calls that operate over the entire collection. Since we are only interested in the single language that is used in most countries, instead of map { ... }.first() call, we can do the following:

Suggested change
.map{ it -> it.first }
.first()
.first()
.first

Copy link
Owner

Choose a reason for hiding this comment

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

Also please note that first() function call will throw an exception if the receiver list object is empty.

}

internal fun List<Country>.filterCountriesThatSpeakLanguage(language: String): List<Country> {
TODO("Implement me!!!")
return this.filter { it.languages.contains(language) }
}


Expand All @@ -91,4 +97,5 @@ fun main() {
println("Language spoken in most countries is a ${countries.findLanguageSpokenInMostCountries()}")
val countriesThatSpeakEnglish = countries.filterCountriesThatSpeakLanguage("English")
println("Countries that speak English language are ${countriesThatSpeakEnglish.joinToString { it.name }}")
//println(countries.flatMap { it.languages }.groupingBy { it }.eachCount().toList().sortedByDescending { it.second }.map{ it -> it.first }.first())
}
9 changes: 7 additions & 2 deletions src/main/kotlin/exercise2/task5/CreateUserDSL.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,16 @@ internal data class Address(
*/

internal fun user(initUser: User.() -> Unit): User {
TODO("Implement me!!!")
val user = User()
Copy link
Owner

Choose a reason for hiding this comment

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

That is it! We can also write this with the scoped functions:

Suggested change
val user = User()
return User().apply(initUser)

user.initUser()
return user
}

internal fun User.address(initAddress: Address.() -> Unit): User {
TODO("Implement me!!!")
val address = Address()
Copy link
Owner

Choose a reason for hiding this comment

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

Same as in an exemple above, we can use scoped functions.

Suggested change
val address = Address()
return apply { address = Address().apply(initAddress) }

address.initAddress()
this.address = address
return this
}

fun main() {
Expand Down