Skip to content

Finished excercises 1 and 2 (Aleksa Martinović) #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
15 changes: 12 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,22 @@ import java.util.Scanner
*/

internal fun calculateGrade(score: Int): Int {
TODO("Implement me!!!")
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
9 changes: 6 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,11 @@ 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" }
val reversed = abs(x).toString().reversed()
return if (x < 0) ("-$reversed").toInt() else reversed.toInt()
}

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,8 @@ 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!!
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
18 changes: 12 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 }
.first()
.first
}

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


Expand Down
4 changes: 2 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,11 @@ internal data class Address(
*/

internal fun user(initUser: User.() -> Unit): User {
TODO("Implement me!!!")
return User().apply(initUser)
}

internal fun User.address(initAddress: Address.() -> Unit): User {
TODO("Implement me!!!")
return apply { address = Address().apply(initAddress) }
}

fun main() {
Expand Down
16 changes: 15 additions & 1 deletion src/main/kotlin/exercise3/task1/BalancedBrackets.kt
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,21 @@ package exercise3.task1


internal fun isExpressionBalanced(expression: String): Boolean {
TODO("Implement me!!!")
val openBrackets = listOf('(', '[', '{')
val closedBrackets = listOf(')', ']', '}')
var brackets = mutableListOf<Char>()


for(char in expression) {
when(char) {
in openBrackets -> brackets.add(char)
Copy link
Owner

Choose a reason for hiding this comment

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

The solution is correct. Readability can be improved by using the map as a data structure.

')' -> if(brackets.isEmpty() || brackets.removeAt(brackets.size - 1) != '(') return false
']' -> if(brackets.isEmpty() || brackets.removeAt(brackets.size - 1) != '[') return false
'}' -> if(brackets.isEmpty() || brackets.removeAt(brackets.size - 1) != '{') return false
}
}

return brackets.isEmpty()
}

fun main() {
Expand Down
28 changes: 27 additions & 1 deletion src/main/kotlin/exercise3/task2/ParenthesesClusters.kt
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,35 @@ package exercise3.task2
*/

internal fun String.splitToBracketsClusters(): List<String> {
TODO("Implement me!!!")
var clusters = mutableListOf<String>()
var open = 0
var builder = StringBuilder()
this.forEach {
when {
it == '(' -> {
open++
builder.append('(')
}
it == ')' -> {
open--
builder.append(')')
}
else -> throw IllegalArgumentException("Invalid character")
}

if(open == 0) {
clusters.add(builder.toString())
builder = StringBuilder()
}

if(open < 0) return emptyList()
}
if(open != 0) return emptyList() else return clusters
}

fun main() {
val expressionsToClustersCatalog = mapOf(
"()(" to listOf("()"),
Copy link
Owner

Choose a reason for hiding this comment

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

This actually should return the empty list since one cluster isn't closed.

"()()()" to listOf("()", "()", "()"),
"((()))" to listOf("((()))"),
"((()))(())()()(()())" to listOf("((()))", "(())", "()", "()", "(()())"),
Expand All @@ -41,4 +65,6 @@ fun main() {
"Expression $expression should be split to $expression clusters, but actual value was $actualClusters."
}
}


}
17 changes: 14 additions & 3 deletions src/main/kotlin/exercise3/task3/SherlockValidatesString.kt
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ package exercise3.task3
* s = abcc
* This is a valid string because we can remove one `c` and have `1` of each character in the remaining string.
*
* s = abccc
* s = abcc
* This string is not valid as we can only remove `1` occurrence of `c`. That leaves character frequencies of
* {`a`: 1, `b`: 1, `c`: 2}.
* ```
Expand All @@ -29,7 +29,19 @@ package exercise3.task3
*/

internal fun isSherlockValid(s: String): String {
TODO("Implement me!!!")
require(s.length in 1..100000) { "String length must be in range from 1 to 10^5" }
require(s.all{ it in 'a'..'z' }) { "String must only contain small letters (a..z)" }

val occurrences = s.groupingBy { it }.eachCount().map { it.value }
val cMin = occurrences.min()
val cMax = occurrences.max()

return when {
cMin == cMax -> "YES"
cMax - cMin == 1 && occurrences.count { it == cMax } == 1 -> "YES"
cMin == 1 && occurrences.count { it == cMin } == 1 && occurrences.count { it == cMax } == occurrences.size - 1 -> "YES"
Copy link
Owner

Choose a reason for hiding this comment

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

If I'm not mistaken, your solution isn't fully correct.
for the test case as, your function would return YES even though the expected result should be NO.

else -> "NO"
}
}

fun main() {
Expand All @@ -38,7 +50,6 @@ fun main() {
stringsToValidityCatalog.forEach { (string, expectedIsValid) ->
val actualIsValid = isSherlockValid(string)
val errorMessageFactory = { answer: String -> if (answer == "YES") "is valid" else "is not valid" }

require(expectedIsValid == actualIsValid) {
"String \"$string\" is ${errorMessageFactory(expectedIsValid)}," +
" but actual value was ${errorMessageFactory(actualIsValid)}."
Expand Down
Loading