diff --git a/.idea/.name b/.idea/.name new file mode 100644 index 0000000..4cae352 --- /dev/null +++ b/.idea/.name @@ -0,0 +1 @@ +subject-kotlin-programming-language-exercises \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..1cbcde6 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,17 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml new file mode 100644 index 0000000..8d81632 --- /dev/null +++ b/.idea/kotlinc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..f12d065 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/src/main/kotlin/exercise2/task1/FindPairOfHighestSum.kt b/src/main/kotlin/exercise2/task1/FindPairOfHighestSum.kt index ddf425b..65d5ead 100644 --- a/src/main/kotlin/exercise2/task1/FindPairOfHighestSum.kt +++ b/src/main/kotlin/exercise2/task1/FindPairOfHighestSum.kt @@ -18,7 +18,21 @@ import org.jetbrains.exercise2.task3.findPairWithBiggestDifference */ internal fun List.findHighestSumPair(): Pair { - TODO("Implement me!!") + + var first = this[0] + var second = Integer.MIN_VALUE + var nextNum = 0 + for (i in 0 ..< this.size -1){ + nextNum = i+1 + if (this[nextNum] >= first ){ + second = first + first = this[nextNum] + } + else if ((second < this[nextNum]) && second < first){ + second = this[nextNum] + } + } + return first to second } fun main() { diff --git a/src/main/kotlin/exercise2/task2/FindPairOfHighestSumFunctional.kt b/src/main/kotlin/exercise2/task2/FindPairOfHighestSumFunctional.kt index b1527fa..a7daba2 100644 --- a/src/main/kotlin/exercise2/task2/FindPairOfHighestSumFunctional.kt +++ b/src/main/kotlin/exercise2/task2/FindPairOfHighestSumFunctional.kt @@ -20,7 +20,7 @@ import org.jetbrains.exercise2.task3.findPairWithBiggestDifference */ internal fun List.findHighestSumPairFunctional(): Pair { - TODO("Implement me!!") + return this.sortedDescending().let { it[0] to it[1] } } fun main() { diff --git a/src/main/kotlin/exercise2/task3/ConvertMethodToFunctionalApproach.kt b/src/main/kotlin/exercise2/task3/ConvertMethodToFunctionalApproach.kt index 47f814b..f57ed21 100644 --- a/src/main/kotlin/exercise2/task3/ConvertMethodToFunctionalApproach.kt +++ b/src/main/kotlin/exercise2/task3/ConvertMethodToFunctionalApproach.kt @@ -17,24 +17,8 @@ import kotlin.math.abs */ internal fun List.findPairWithBiggestDifference(): Pair { - // TODO refactor me to functional approach and make tests pass!!! - var resultPair: Pair? = 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 this.sorted().let { it.first() to it[it.lastIndex] } } fun main() { diff --git a/src/main/kotlin/exercise2/task4/ProcessCountriesData.kt b/src/main/kotlin/exercise2/task4/ProcessCountriesData.kt index 291e558..cc75e41 100644 --- a/src/main/kotlin/exercise2/task4/ProcessCountriesData.kt +++ b/src/main/kotlin/exercise2/task4/ProcessCountriesData.kt @@ -59,27 +59,27 @@ internal val countries = listOf( */ internal fun List.findCountryWithBiggestTotalArea(): Country { - TODO("Implement me!!!") + return this.maxBy { it.totalAreaInSquareKilometers } } internal fun List.findCountryWithBiggestPopulation(): Country { - TODO("Implement me!!!") + return this.maxBy { it.population } } internal fun List.findCountryWithHighestPopulationDensity(): Country { - TODO("Implement me!!!") + return this.maxBy { it.population/it.totalAreaInSquareKilometers } } internal fun List.findCountryWithLowestPopulationDensity(): Country { - TODO("Implement me!!!") + return this.minBy { it.population/it.totalAreaInSquareKilometers } } internal fun List.findLanguageSpokenInMostCountries(): String { - TODO("Implement me!!!") + return this.flatMap { it.languages }.groupingBy { it }.eachCount().maxBy { it.value}.key } internal fun List.filterCountriesThatSpeakLanguage(language: String): List { - TODO("Implement me!!!") + return this.filter { it.languages.contains(language) } } diff --git a/src/main/kotlin/exercise2/task5/CreateUserDSL.kt b/src/main/kotlin/exercise2/task5/CreateUserDSL.kt index 855c0cb..6471402 100644 --- a/src/main/kotlin/exercise2/task5/CreateUserDSL.kt +++ b/src/main/kotlin/exercise2/task5/CreateUserDSL.kt @@ -49,11 +49,16 @@ internal data class Address( */ internal fun user(initUser: User.() -> Unit): User { - TODO("Implement me!!!") + val newUser = User() + newUser.initUser() + return newUser } internal fun User.address(initAddress: Address.() -> Unit): User { - TODO("Implement me!!!") + val newAddress = Address() + newAddress.initAddress() + address = newAddress + return this } fun main() { diff --git a/src/main/kotlin/exercise3/task1/BalancedBrackets.kt b/src/main/kotlin/exercise3/task1/BalancedBrackets.kt index 7a6958d..4f1bb54 100644 --- a/src/main/kotlin/exercise3/task1/BalancedBrackets.kt +++ b/src/main/kotlin/exercise3/task1/BalancedBrackets.kt @@ -1,5 +1,7 @@ package exercise3.task1 +import java.util.Stack + /** * Task1: Balanced Brackets (Parentheses) Problem * @@ -26,9 +28,41 @@ package exercise3.task1 internal fun isExpressionBalanced(expression: String): Boolean { - TODO("Implement me!!!") + + if (expression.length %2 == 1) return false + + val pair1 = '(' to ')' + val pair2 = '[' to ']' + val pair3 = '{' to '}' + val pairs = arrayOf(pair1, pair2, pair3) + + val open = listOf('(', '[', '{') + val stack = Stack() + + for (i in expression){ + if(i in open){ + stack.push(i) + } + else { + if (stack.isEmpty()) return false + val tmpPair = stack.pop() to i + if (tmpPair !in pairs) return false + } + } + if(stack.isNotEmpty()) return false + + return true } +/* + {[()]()} + + if i in isOpen add to stack + else is + else is i == sa prvim sa stacka + + */ + fun main() { val expressions = listOf( "{[()]}" to true, diff --git a/src/main/kotlin/exercise3/task2/ParenthesesClusters.kt b/src/main/kotlin/exercise3/task2/ParenthesesClusters.kt index 0e75083..2b94669 100644 --- a/src/main/kotlin/exercise3/task2/ParenthesesClusters.kt +++ b/src/main/kotlin/exercise3/task2/ParenthesesClusters.kt @@ -1,5 +1,7 @@ package exercise3.task2 +import java.util.* + /** * Task 2: Split Expression To Parentheses Clusters * @@ -24,7 +26,31 @@ package exercise3.task2 */ internal fun String.splitToBracketsClusters(): List { - TODO("Implement me!!!") + + if (this.length %2 == 1) return listOf() + + val open = listOf('(', '[', '{') + val stack = Stack() + + var tempString = "" + val returnList = mutableListOf() + + for (i in this){ + if(i in open){ + stack.push(i) + tempString += i + } + else { + if (stack.isEmpty()) return listOf() + tempString += i + stack.pop() + } + if (stack.isEmpty()){ + returnList += listOf(tempString) + tempString = "" + } + } + return returnList } fun main() { diff --git a/src/main/kotlin/exercise3/task3/SherlockValidatesString.kt b/src/main/kotlin/exercise3/task3/SherlockValidatesString.kt index 55680b8..07fcaa6 100644 --- a/src/main/kotlin/exercise3/task3/SherlockValidatesString.kt +++ b/src/main/kotlin/exercise3/task3/SherlockValidatesString.kt @@ -1,5 +1,7 @@ package exercise3.task3 +import kotlin.math.abs + /** * Task 3: Sherlock Validates the Words * @@ -29,11 +31,45 @@ package exercise3.task3 */ internal fun isSherlockValid(s: String): String { - TODO("Implement me!!!") + + val grpByChars = s.groupingBy { it }.eachCount() + + val valuesOfGrouping = grpByChars.values.groupingBy { it }.eachCount() + + if (valuesOfGrouping.size > 2) return "NO" + if (valuesOfGrouping.size == 1) return "YES" + + val firstKey = valuesOfGrouping.keys.first() + val firstValue = valuesOfGrouping.values.first() + val secondKey = valuesOfGrouping.keys.last() + val secondValue = valuesOfGrouping.values.last() + + if((secondValue == 1) and (secondKey== 1)) return "YES" + if((firstValue == 1) and (firstKey== 1)) return "YES" + + val minusKeys = abs(firstKey - secondKey) + val minusValues = abs(firstValue - secondValue) + +/* + Mislim da sa ovim ne pokrivam sve krajnje slucajeve + i da kod nije bas efikasan. Prolazi testove. + */ + if ( (minusKeys <=1) or (minusValues <= 1) ){ + + if( (firstKey > secondKey) and (firstValue > secondValue) ) return "NO" + if( (firstKey < secondKey) and (firstValue < secondValue) ) return "NO" + if(firstValue >=2 && secondValue >= 2) return "NO" + + return "YES" + } + else{ + return "NO" + } + } fun main() { - val stringsToValidityCatalog = mapOf("abc" to "YES", "abcc" to "YES", "abccc" to "NO") + val stringsToValidityCatalog = mapOf("abc" to "YES", "abcc" to "YES", "aabbccccc" to "NO") stringsToValidityCatalog.forEach { (string, expectedIsValid) -> val actualIsValid = isSherlockValid(string) diff --git a/src/main/kotlin/exercise3/task4/TaxiParkTask.kt b/src/main/kotlin/exercise3/task4/TaxiParkTask.kt index 0dfe831..0e0e8ab 100755 --- a/src/main/kotlin/exercise3/task4/TaxiParkTask.kt +++ b/src/main/kotlin/exercise3/task4/TaxiParkTask.kt @@ -1,5 +1,6 @@ package exercise3.task4 + /** * Task 4: Taxi park * @@ -10,7 +11,7 @@ package exercise3.task4 * Find all the drivers who performed no trips. */ internal fun TaxiPark.findFakeDrivers(): Set { - TODO("Implement me!!!") + return this.allDrivers.filter { driver -> trips.none { it.driver == driver } }.toSet() } /** @@ -18,7 +19,8 @@ internal fun TaxiPark.findFakeDrivers(): Set { * Find all the clients who completed at least the given number of trips. */ internal fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set { - TODO("Implement me!!!") + return this.allPassengers.filter { passenger -> + trips.count { it.passengers.contains(passenger) } >= minTrips }.toSet() } /** @@ -26,7 +28,8 @@ internal fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set { * Find all the passengers, who were taken by a given driver more than once. */ internal fun TaxiPark.findFrequentPassengers(driver: Driver): Set { - TODO("Implement me!!!") + return this.allPassengers.filter { passenger -> + trips.count { (it.driver == driver) and (it.passengers.contains(passenger)) } > 1 }.toSet() } /** @@ -34,5 +37,12 @@ internal fun TaxiPark.findFrequentPassengers(driver: Driver): Set { * Find the passengers who had a discount for the majority of their trips. */ internal fun TaxiPark.findSmartPassengers(): Set { - TODO("Implement me!!!") + /* + Kako bih mogao da recikliram kod "it.passengers.contains(passenger)", + da ne brojim dva puta? + */ + return this.allPassengers + .filter { passenger -> + trips.count { ( it.passengers.contains(passenger) ) and ( it.discount != null) } > + trips.count{ it.passengers.contains(passenger) } / 2 }.toSet() } diff --git a/src/main/kotlin/exercise5/BoardImpl.kt b/src/main/kotlin/exercise5/BoardImpl.kt index d0cd822..2af4127 100644 --- a/src/main/kotlin/exercise5/BoardImpl.kt +++ b/src/main/kotlin/exercise5/BoardImpl.kt @@ -1,13 +1,80 @@ package exercise5 -// TODO Instantiate SquareBoard -fun createSquareBoard(width: Int): SquareBoard = TODO("SquareBoardImpl(width)") +fun createSquareBoard(width: Int): SquareBoard = SquareBoardImpl(width) -// TODO Instantiate GameBoard -fun createGameBoard(width: Int): GameBoard = TODO("GameBoardImpl(width)") +fun createGameBoard(width: Int): GameBoard = GameBoardImpl(width) -// TODO Implement SquareBoard Interface -class SquareBoardImpl(size: Int) +open class SquareBoardImpl(size: Int) : SquareBoard{ + override val width: Int = size -// TODO extend SquareBoardImpl and implement GameBoard interface -class GameBoardImpl(size: Int) \ No newline at end of file + protected val board = List(size) { x -> + List(size) { y -> + Cell(x + 1, y + 1) + } + } + + override fun getCellOrNull(i: Int, j: Int): Cell? { + return board.getOrNull(i - 1)?.getOrNull(j - 1) + } + + override fun getCell(i: Int, j: Int): Cell { + return getCellOrNull(i, j) ?: throw IllegalArgumentException("Wrong parameter") + } + + override fun getAllCells(): Collection { + return board.flatten() + } + + override fun getRow(i: Int, jRange: IntProgression): List { + return jRange.mapNotNull { getCellOrNull(i, it) } + } + + override fun getColumn(iRange: IntProgression, j: Int): List { + return iRange.mapNotNull { getCellOrNull(it, j) } + } + + override fun Cell.getNeighbour(direction: Direction): Cell? { + return when(direction){ + Direction.UP -> getCellOrNull(i - 1, j) + Direction.DOWN -> getCellOrNull(i + 1, j) + Direction.LEFT -> getCellOrNull(i, j - 1) + Direction.RIGHT -> getCellOrNull(i, j + 1) + } + } +} + +class GameBoardImpl(size: Int) : SquareBoardImpl(size), GameBoard{ + + private val cells = mutableMapOf() + + init { + board.flatten().forEach { + cells[it] = null + } + } + + override fun get(cell: Cell): String? { + return cells[cell] + } + + override fun set(cell: Cell, value: String?) { + cells[cell] = value + } + + override fun filter(predicate: (String?) -> Boolean): Collection { + return cells.filter { predicate(it.value) }.keys + } + + override fun find(predicate: (String?) -> Boolean): Cell? { + return cells.entries.find { predicate(it.value) }?.key + } + + override fun any(predicate: (String?) -> Boolean): Boolean { + return cells.entries.any{ predicate(it.value)} + } + + override fun all(predicate: (String?) -> Boolean): Boolean { + return cells.entries.all { predicate(it.value) } + } + +} \ No newline at end of file diff --git a/src/main/kotlin/exercise6/task1/SimpleGenerics.kt b/src/main/kotlin/exercise6/task1/SimpleGenerics.kt index edf9790..86bc5b3 100644 --- a/src/main/kotlin/exercise6/task1/SimpleGenerics.kt +++ b/src/main/kotlin/exercise6/task1/SimpleGenerics.kt @@ -14,9 +14,9 @@ package exercise6.task1 /** * A binary tree node that holds some value. */ -private data class TreeNode(val value: Any) { - var left: TreeNode? = null - var right: TreeNode? = null +private data class TreeNode(val value: T) { + var left: TreeNode? = null + var right: TreeNode? = null } /** @@ -42,8 +42,8 @@ private fun printNodes(): String { val decisionI = Decision("Do you choose a red or a blue pill?", "Red", "Blue") val decisionTree = TreeNode(decisionI) - TODO("Uncomment code bellow and make the file compilable") -// return "${genealogyTree.value.name} ${decisionTree.value.answerLeft}" +// TODO("Uncomment code bellow and make the file compilable") + return "${genealogyTree.value.name} ${decisionTree.value.answerLeft}" } fun main() { diff --git a/src/main/kotlin/exercise6/task2/UpperBoundConstraints.kt b/src/main/kotlin/exercise6/task2/UpperBoundConstraints.kt index 53e84c0..49ba4b6 100644 --- a/src/main/kotlin/exercise6/task2/UpperBoundConstraints.kt +++ b/src/main/kotlin/exercise6/task2/UpperBoundConstraints.kt @@ -38,9 +38,9 @@ private data class SetIntersection(val size: Int): CostElement { * nodes. This code is not yet compilable, but it will become compilable as soon as you add an upper bound to the generic * type. */ -private fun calculateTreeCost(root: TreeNode): Double { - TODO("Uncomment code bellow and make the file compilable") -// return root.value.cost + -// (root.left?.let { calculateTreeCost(it) } ?: 0.0) + -// (root.right?.let { calculateTreeCost(it) } ?: 0.0) +private fun calculateTreeCost(root: TreeNode): Double { +// TODO("Uncomment code bellow and make the file compilable") + return root.value.cost + + (root.left?.let { calculateTreeCost(it) } ?: 0.0) + + (root.right?.let { calculateTreeCost(it) } ?: 0.0) } \ No newline at end of file diff --git a/src/main/kotlin/exercise6/task3/UpperBoundConstraintPartTwo.kt b/src/main/kotlin/exercise6/task3/UpperBoundConstraintPartTwo.kt index 72a660a..edd5032 100644 --- a/src/main/kotlin/exercise6/task3/UpperBoundConstraintPartTwo.kt +++ b/src/main/kotlin/exercise6/task3/UpperBoundConstraintPartTwo.kt @@ -49,7 +49,7 @@ private data class SetIntersection(val size: Int, val lowerBound: S?, val upp * no intersection at all. If the intersection is likely to be not empty, it estimates the intersection size as the mean * of the set sizes. */ -private fun estimateIntersectionSize(treeNode: TreeNode>): Int { +private fun > estimateIntersectionSize(treeNode: TreeNode>): Int { val leftNode = treeNode.left ?: return treeNode.value.size val rightNode = treeNode.right ?: return treeNode.value.size @@ -60,9 +60,8 @@ private fun estimateIntersectionSize(treeNode: TreeNode>) return 0 } - TODO("Uncomment code bellow and make the file compilable") -// if (leftNode.value.upperBound < rightNode.value.lowerBound || leftNode.value.lowerBound > rightNode.value.upperBound) { -// return 0 -// } -// return (leftNode.value.size + rightNode.value.size)/2 + if (leftNode.value.upperBound < rightNode.value.lowerBound || leftNode.value.lowerBound > rightNode.value.upperBound) { + return 0 + } + return (leftNode.value.size + rightNode.value.size)/2 } \ No newline at end of file diff --git a/src/main/kotlin/exercise6/task4/UpperBoundConstraintPartThree.kt b/src/main/kotlin/exercise6/task4/UpperBoundConstraintPartThree.kt index 4614d38..2198f2b 100644 --- a/src/main/kotlin/exercise6/task4/UpperBoundConstraintPartThree.kt +++ b/src/main/kotlin/exercise6/task4/UpperBoundConstraintPartThree.kt @@ -89,29 +89,29 @@ private data class SetIntersection>( * no intersection at all. If the intersection is likely to be not empty, it estimates the intersection size as the mean * of the set sizes. */ -private fun estimateIntersectionSize(treeNode: TreeNode) : Int { - TODO("Uncomment code bellow and make the file compilable") -// val leftNode = treeNode.left ?: return treeNode.value.size -// val rightNode = treeNode.right ?: return treeNode.value.size -// -// if (leftNode.value.lowerBound == null || rightNode.value.lowerBound == null) { -// return 0 -// } -// if (leftNode.value.upperBound == null || rightNode.value.upperBound == null) { -// return 0 -// } -// -// if (leftNode.value.upperBound!! < rightNode.value.lowerBound!! || leftNode.value.lowerBound!! > rightNode.value.upperBound!!) { -// return 0 -// } -// return (leftNode.value.size + rightNode.value.size)/2 +private fun estimateIntersectionSize(treeNode: TreeNode) : Int where T: Range, T:Measurable, S:Comparable { +// TODO("Uncomment code bellow and make the file compilable") + val leftNode = treeNode.left ?: return treeNode.value.size + val rightNode = treeNode.right ?: return treeNode.value.size + + if (leftNode.value.lowerBound == null || rightNode.value.lowerBound == null) { + return 0 + } + if (leftNode.value.upperBound == null || rightNode.value.upperBound == null) { + return 0 + } + + if (leftNode.value.upperBound!! < rightNode.value.lowerBound!! || leftNode.value.lowerBound!! > rightNode.value.upperBound!!) { + return 0 + } + return (leftNode.value.size + rightNode.value.size)/2 } -private fun printTree(treeNode: TreeNode) { - TODO("Uncomment code bellow and make the file compilable") -// println("${treeNode.value} cost:${treeNode.value.cost}") -// treeNode.left?.let { printTree(it) } -// treeNode.right?.let { printTree(it) } +private fun printTree(treeNode: TreeNode) { +// TODO("Uncomment code bellow and make the file compilable") + println("${treeNode.value} cost:${treeNode.value.cost}") + treeNode.left?.let { printTree(it) } + treeNode.right?.let { printTree(it) } } /** @@ -148,12 +148,12 @@ private fun run() { it.left = leftNode it.right = rightNode } - TODO("Uncomment code bellow and make the file compilable") -// val intersectionSize = estimateIntersectionSize(rootNode) -// println(intersectionSize) -// -// printTree(rootNode) -// printNodes() +// TODO("Uncomment code bellow and make the file compilable") + val intersectionSize = estimateIntersectionSize(rootNode) + println(intersectionSize) + + printTree(rootNode) + printNodes() } fun main() { diff --git a/src/main/kotlin/exercise6/taskProjections/task1/Task.kt b/src/main/kotlin/exercise6/taskProjections/task1/Task.kt index 7905d94..7fc218e 100644 --- a/src/main/kotlin/exercise6/taskProjections/task1/Task.kt +++ b/src/main/kotlin/exercise6/taskProjections/task1/Task.kt @@ -11,12 +11,12 @@ package exercise6.taskProjections.task1 **/ -interface Sender { - fun send(item: Any) +interface Sender { + fun send(item: T) } -class MailBox(private var box: Any? = null): Sender { - override fun send(item: Any) { +class MailBox(private var box: T? = null): Sender { + override fun send(item: T) { printCurrentBoxState() println("Sending the box: $item!") box = item @@ -32,8 +32,8 @@ class MailBox(private var box: Any? = null): Sender { } -class Postman(private val mailboxes: List): Sender { - override fun send(item: Any) { +class Postman(private val mailboxes: List>): Sender { + override fun send(item: T) { mailboxes.forEach { it.send(item) } } @@ -45,14 +45,18 @@ open class Postcard(open val origin: String) : Delivery data class ExpressPostcard(val priceEuro: Int, override val origin: String) : Postcard(origin) fun main() { - // TODO: This code should became compilable -// val postcardStorage = MailBox() -// val expressPostcardStorage = MailBox() + val postcardStorage = MailBox() + val expressPostcardStorage = MailBox() val expressPostcard = ExpressPostcard(15, "Serbia") val postcard = Postcard("Germany") - // TODO: add code to create topRatedPostman and juniorPostman. - // The topRatedPostman can send ONLY express postcards - // The juniorPostman can send both regular and express postcards + + val topRatedPostman = Postman(listOf(expressPostcardStorage)) + val juniorPostman = Postman(listOf(postcardStorage)) + + topRatedPostman.send(expressPostcard) + juniorPostman.send(expressPostcard) + juniorPostman.send(postcard) + } \ No newline at end of file diff --git a/src/main/kotlin/exercise6/taskProjections/task2/Task.kt b/src/main/kotlin/exercise6/taskProjections/task2/Task.kt index b28c6ae..2db83cb 100644 --- a/src/main/kotlin/exercise6/taskProjections/task2/Task.kt +++ b/src/main/kotlin/exercise6/taskProjections/task2/Task.kt @@ -17,17 +17,22 @@ class JvmLanguage(override val name: String) : ProgrammingLanguage class BlockBasedLanguage(override val name: String) : ProgrammingLanguage +class Programmer(){ + fun learn(language : T){ + println("I learned ${language.name}!"); + } +} + fun main() { - TODO("Uncomment this code when you finish the task") -// val programmer = Programmer() -// -// val jvmLanguages = listOf(JvmLanguage("Java"), JvmLanguage("Kotlin")) -// jvmLanguages.forEach{ programmer.learn(it) } // OK -// -// val blockBasedLanguages = listOf(BlockBasedLanguage("Scratch"), JvmLanguage("Snap")) -// blockBasedLanguages.forEach{ programmer.learn(it) } // OK -// -// (jvmLanguages + blockBasedLanguages).forEach{ programmer.learn(it) } // OK -// -//// val newLanguage: ProgrammingLanguage = programmer.create() // ERROR + val programmer = Programmer() + + val jvmLanguages = listOf(JvmLanguage("Java"), JvmLanguage("Kotlin")) + jvmLanguages.forEach{ programmer.learn(it) } // OK + + val blockBasedLanguages = listOf(BlockBasedLanguage("Scratch"), JvmLanguage("Snap")) + blockBasedLanguages.forEach{ programmer.learn(it) } // OK + + (jvmLanguages + blockBasedLanguages).forEach{ programmer.learn(it) } // OK + +// val newLanguage: ProgrammingLanguage = programmer.create() // ERROR } diff --git a/src/main/kotlin/exercise6/taskProjections/task3/Task.kt b/src/main/kotlin/exercise6/taskProjections/task3/Task.kt index 211a74f..ce9c988 100644 --- a/src/main/kotlin/exercise6/taskProjections/task3/Task.kt +++ b/src/main/kotlin/exercise6/taskProjections/task3/Task.kt @@ -36,11 +36,12 @@ class BlockBasedLanguageParser : LanguageParser { } fun main() { - TODO("Create a new HashMap and uncomment code bellow") -// parsersHashMap[JvmLanguage::class.java] = JvmLanguageParser() -// parsersHashMap[BlockBasedLanguage::class.java] = BlockBasedLanguageParser() -// -// val scratch = BlockBasedLanguage() -// val foundParser = parsersHashMap[scratch.javaClass] -// foundParser?.parse(scratch) + val parsersHashMap = HashMap, LanguageParser<*>>() + + parsersHashMap[JvmLanguage::class.java] = JvmLanguageParser() + parsersHashMap[BlockBasedLanguage::class.java] = BlockBasedLanguageParser() + + val scratch = BlockBasedLanguage() + val foundParser = parsersHashMap[scratch.javaClass] + foundParser?.parse(scratch) } diff --git a/src/main/kotlin/exercise6/taskProjections/task4/Task.kt b/src/main/kotlin/exercise6/taskProjections/task4/Task.kt index c2d86d9..08481be 100644 --- a/src/main/kotlin/exercise6/taskProjections/task4/Task.kt +++ b/src/main/kotlin/exercise6/taskProjections/task4/Task.kt @@ -7,6 +7,12 @@ package exercise6.taskProjections.task4 * that accepts two arrays with a generic type of Any and copy elements from the first array to the second one. **/ +fun copy(ints: Array, any: Array){ + for (i in ints.indices){ + any[i] = ints[i] + } +} + fun main() { val ints = arrayOf(1, 2, 3) val any = Array(3) { "" } @@ -17,8 +23,7 @@ fun main() { println("_______") println("_______") - // TODO: uncomment this code - // copy(ints, any) + copy(ints, any) ints.forEach{ print("$it ") } println() diff --git a/src/main/kotlin/exercise6/taskProjections/task5/Task.kt b/src/main/kotlin/exercise6/taskProjections/task5/Task.kt index 9123785..e53d4b0 100644 --- a/src/main/kotlin/exercise6/taskProjections/task5/Task.kt +++ b/src/main/kotlin/exercise6/taskProjections/task5/Task.kt @@ -14,20 +14,37 @@ package exercise6.taskProjections.task5 * Create a new class "IntegerBuilder", that implements Builder and can convert String to Int **/ +//[1] +class Printer{ + fun print(item : T){ + println(item) + } +} + +//[2] +abstract class Builder{ + abstract fun build(item : P) : T +} + +class IntegerBuilder : Builder() { + override fun build(item: String): Int { + return Integer.parseInt(item) + } + +} + fun main() { // [1] - // TODO: uncomment me -// val integerPrinter = Printer() -// val stringPrinter = Printer() -// -// integerPrinter.print(2) -// stringPrinter.print("Bla bla bla") + val integerPrinter = Printer() + val stringPrinter = Printer() + + integerPrinter.print(2) + stringPrinter.print("Bla bla bla") println("________") // [2] - // TODO: uncomment me -// val intBuilder = IntegerBuilder() -// val x = intBuilder.build("1") -// println("We build [ $x ]") + val intBuilder = IntegerBuilder() + val x = intBuilder.build("1") + println("We build [ $x ]") } diff --git a/src/main/kotlin/exercise6/taskProjections/task6/Task.kt b/src/main/kotlin/exercise6/taskProjections/task6/Task.kt index e897e4c..518fe1b 100644 --- a/src/main/kotlin/exercise6/taskProjections/task6/Task.kt +++ b/src/main/kotlin/exercise6/taskProjections/task6/Task.kt @@ -10,24 +10,22 @@ open class A class B : A() class C : A() { fun consume(other: A): C = this } -// TODO: uncomment and fix me -//fun funny( -// source: Iterator, -// target: MutableCollection, -// base: ??, -// how: ?? -//) { -// var result: R = base -// for (value in source) { -// result = how(result, value) -// target.add(result) -// } -//} +fun funny( + source: Iterator, + target: MutableCollection, + base: R, + how: (R, T) -> S +) { + var result: R = base + for (value in source) { + result = how(result, value) + target.add(result) + } +} fun main() { - // TODO: uncomment me, it should not produce any compilation errors -// val wtf = mutableListOf() -// val src = mapOf(3.14 to B(), 2 to B(), "Hello" to B()) -// val c = C() -// funny(src.values.iterator(), wtf, c) { r, t -> r.consume(t) } + val wtf = mutableListOf() + val src = mapOf(3.14 to B(), 2 to B(), "Hello" to B()) + val c = C() + funny(src.values.iterator(), wtf, c) { r, t -> r.consume(t) } } diff --git a/src/test/kotlin/exercise2/task1/FindPairOfHighestSumTest.kt b/src/test/kotlin/exercise2/task1/FindPairOfHighestSumTest.kt index 49b6d53..e423962 100644 --- a/src/test/kotlin/exercise2/task1/FindPairOfHighestSumTest.kt +++ b/src/test/kotlin/exercise2/task1/FindPairOfHighestSumTest.kt @@ -22,7 +22,8 @@ class HighestSumPairTest { TestEntry(listOf(227, 891, -41, 666, 906, 201, -121, -100, 268, -215, -746, -712), Pair(906, 891)), TestEntry(listOf(-46, 943, 572, 15, 996, 632, 997), Pair(996, 997)), TestEntry(listOf(-453, -214, -593, 315, 497, -90, -631, 706, -950, -666, -1000, -379), Pair(706, 497)), - TestEntry(listOf(3, 1, 2), Pair(3, 2)) + TestEntry(listOf(3, 1, 2), Pair(3, 2)) , + TestEntry(listOf(3, 2, 1), Pair(3, 2)) ) testData.forEach { (input: List, expected: Pair) ->