Skip to content
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
26 changes: 26 additions & 0 deletions .idea/runConfigurations/Run_All_tests_in_Execise_5.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions .idea/runConfigurations/Run_All_tests_in_Execise_7.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions .idea/runConfigurations/Run_All_tests_in_Execise_8.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions .idea/runConfigurations/Run_Task_1__Test_TestSquareBoard.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions .idea/runConfigurations/Run_Task_2__Test_GameBoard.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 1 addition & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1 @@
# Kotlin Programming Language Course - Faculty of Sciences, Novi Sad

Welcome to the Kotlin Programming Language Course at the Faculty of Sciences, Novi Sad!

## Project Overview

This project contains a set of exercises designed to help you learn Kotlin programming concepts. Each exercise is provided with instructions and corresponding Kotlin files where you can implement your solutions.

## How to Load Project from GitHub in IntelliJ IDEA

### 1. Clone the Repository

- Open IntelliJ IDEA.
- Go to `File` > `New` > `Project from Version Control` > `Git`.
- In the `URL` field, enter the URL of the GitHub repository: https://github.com/vuksa/kotlin-programming-language-course.git
- Click `Clone` to clone the repository to your local machine.
bojan ludajic
1 change: 1 addition & 0 deletions build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ repositories {

dependencies {
testImplementation(kotlin("test"))
testImplementation("junit:junit:4.13")
testImplementation("org.junit.jupiter:junit-jupiter-params:5.8.1")
}

Expand Down
22 changes: 22 additions & 0 deletions src/main/kotlin/common/FileReader.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package common

import java.nio.file.Path
import java.nio.file.Paths
import kotlin.io.path.readLines
import kotlin.io.path.toPath

object FileReader {
/**
* Reads the contents of a file located at the specified path.
*
* @param path The path of the file to read.
* @return A list of strings representing the lines of the file.
* @throws NullPointerException if the resource at the specified path is null.
*/
fun readFileInResources(path: String): List<String> {
val normalizedPath = path.takeIf { it.startsWith("/") } ?: "/$path"
return requireNotNull(this.javaClass.getResource(normalizedPath.toString())?.toURI()?.toPath()) {
"Unresolved path."
}.readLines()
}
}
5 changes: 4 additions & 1 deletion src/main/kotlin/exercise2/task1/FindPairOfHighestSum.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ import org.jetbrains.exercise2.task3.findPairWithBiggestDifference
*/

internal fun List<Int>.findHighestSumPair(): Pair<Int, Int> {
TODO("Implement me!!")
val prvi = this.sorted().get(this.lastIndex)
val drugi = this.sorted().get(this.lastIndex-1)
Comment on lines +21 to +22
Copy link
Owner

Choose a reason for hiding this comment

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

There is no need to sort the array twice. Please name the variables in English, as that is a widely accepted convention.


return Pair(prvi, drugi)
}

fun main() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ import org.jetbrains.exercise2.task3.findPairWithBiggestDifference
*/

internal fun List<Int>.findHighestSumPairFunctional(): Pair<Int, Int> {
TODO("Implement me!!")
return Pair(
this.sorted().get(this.lastIndex), this.sorted().get(this.lastIndex-1)
Copy link
Owner

Choose a reason for hiding this comment

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

This is not a functional approach :)

The idea of the functional approach is that you compose function calls that operate on data to get the desired result.

Functional approach would be following:

Suggested change
this.sorted().get(this.lastIndex), this.sorted().get(this.lastIndex-1)
return this.sorted().let { sortedList -> Pair(this.lastIndex, this.lastIndex-1) }

In this case, we are using the result of the sorted function invocation, and we are providing it as an input of the let function invocation. Hence, we are composing function calls to get the result.

)
}

fun main() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,24 +17,29 @@ 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!!
return Pair(
this.sorted().get(this.size-1), this.sorted().get(0)
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, but it is written in Java-style code. Please consider my suggestion above to implement it in a Kotlin, functional style. :)

Also, this.size - 1 has a Kotlin equivalent in this.lastIndex, and get(0) has an equivalent in a first() function.

)


// var resultPair: Pair<Int, Int>? = null
Copy link
Owner

Choose a reason for hiding this comment

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

Please clean up the code before pushing the changes.

// 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!!
}

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

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

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

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

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

internal fun List<Country>.findLanguageSpokenInMostCountries(): String {
TODO("Implement me!!!")
return countries.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.

Very nice solution!

.groupingBy { it }
.eachCount()
.maxBy { it.value }
.key
}

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


Expand All @@ -88,7 +96,7 @@ fun main() {
println("Country with a biggest population is a ${countries.findCountryWithBiggestPopulation().name}")
println("Country with a biggest population density is a ${countries.findCountryWithHighestPopulationDensity().name}")
println("Country with a lowest population density is a ${countries.findCountryWithLowestPopulationDensity().name}")
println("Language spoken in most countries is a ${countries.findLanguageSpokenInMostCountries()}")
println("Language spoken in most countries is ${countries.findLanguageSpokenInMostCountries()}")
val countriesThatSpeakEnglish = countries.filterCountriesThatSpeakLanguage("English")
println("Countries that speak English language are ${countriesThatSpeakEnglish.joinToString { it.name }}")
}
10 changes: 7 additions & 3 deletions src/main/kotlin/exercise2/task5/CreateUserDSL.kt
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,15 @@ internal data class Address(
*/

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

Choose a reason for hiding this comment

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

nit: this can be a one-line expression :)

}

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

Choose a reason for hiding this comment

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

That's it! Why not using apply scoped function here as well?

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

fun main() {
Expand Down
26 changes: 25 additions & 1 deletion src/main/kotlin/exercise3/task1/BalancedBrackets.kt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
package exercise3.task1
import java.util.Stack

/**
* Task1: Balanced Brackets (Parentheses) Problem
Expand Down Expand Up @@ -26,9 +27,32 @@ package exercise3.task1


internal fun isExpressionBalanced(expression: String): Boolean {
TODO("Implement me!!!")
val chars = Stack<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. 👏🏻
Please now try solving it in the functional way. :)

val opening = "({["
val closing = ")}]"

for(char in expression) {
when {
char in opening -> chars.add(char)
char in closing -> {
if(chars.isEmpty() || !valid(chars.lastElement(), char)) {
return false
}
chars.removeLast()
}
}
}
return chars.isEmpty()
}

fun valid(opening: Char, closing: Char): Boolean {
return (opening == '(' && closing == ')') ||
(opening == '[' && closing == ']') ||
(opening == '{' && closing == '}')
}



fun main() {
val expressions = listOf(
"{[()]}" to true,
Expand Down
Loading