Skip to content

Partial solution for Exercise 3 #13

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
1 change: 1 addition & 0 deletions .idea/.name

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

17 changes: 17 additions & 0 deletions .idea/gradle.xml

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

6 changes: 6 additions & 0 deletions .idea/kotlinc.xml

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

4 changes: 4 additions & 0 deletions .idea/misc.xml

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

6 changes: 6 additions & 0 deletions .idea/vcs.xml

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

19 changes: 18 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,24 @@ import org.jetbrains.exercise2.task3.findPairWithBiggestDifference
*/

internal fun List<Int>.findHighestSumPair(): Pair<Int, Int> {
TODO("Implement me!!")
var firstMaximal = this[0]
var maximalIndex = -1

for((index, num) in this.withIndex()) {
if(num > firstMaximal) {
firstMaximal = num
maximalIndex = index
}
}

var secondMaximal = this[0]
for((index, num) in this.withIndex()) {
if(num in (secondMaximal + 1)..firstMaximal && index != maximalIndex) {
secondMaximal = num
}
}

return firstMaximal to secondMaximal
}

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

internal fun List<Int>.findHighestSumPairFunctional(): Pair<Int, Int> {
TODO("Implement me!!")
return this.sortedDescending().let { it.first() to it[1] }
}

fun main() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,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
return this.sorted().let { it.first() to it.last() }
/*var resultPair: Pair<Int, Int>? = null
var biggestDifference = Int.MIN_VALUE

for (i in this.indices) {
Expand All @@ -34,7 +34,7 @@ internal fun List<Int>.findPairWithBiggestDifference(): Pair<Int, Int> {
}
}

return resultPair!!
return resultPair!!*/
}

fun main() {
Expand Down
16 changes: 10 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,31 @@ 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 }
.groupingBy { it }
.eachCount()
.maxBy { it.value }
.key
}

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


Expand Down
20 changes: 19 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,25 @@ package exercise3.task1


internal fun isExpressionBalanced(expression: String): Boolean {
TODO("Implement me!!!")
val stack = mutableListOf<Char>()

for (char in expression) {
Copy link
Owner

Choose a reason for hiding this comment

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

Well done! For practice, try solving it with a functional approach. :)

when (char) {
'(', '{', '[' -> stack.add(char)
')', '}', ']' -> {
if (stack.isEmpty()) return false
val last = stack.removeAt(stack.size - 1)
if ((char == ')' && last != '(') ||
(char == '}' && last != '{') ||
(char == ']' && last != '[')
) {
return false
}
}
}
}

return stack.isEmpty()
}

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

internal fun String.splitToBracketsClusters(): List<String> {
TODO("Implement me!!!")
val stack = mutableListOf<Char>()
val clusters = mutableListOf<String>()
var currentCluster = ""

for (char in this) {
when (char) {
'(' -> {
stack.add(char)
currentCluster += char
}
')' -> {
if (stack.isEmpty())
return emptyList()
val last = stack.removeAt(stack.size - 1)
if (last == '(')
currentCluster += char
else
return emptyList()
if (stack.isEmpty()) {
clusters.add(currentCluster)
currentCluster = ""
}
}
}
}
if (stack.isNotEmpty())
return emptyList()

return clusters

}


fun main() {
val expressionsToClustersCatalog = mapOf(
"()()()" to listOf("()", "()", "()"),
Expand Down
37 changes: 32 additions & 5 deletions src/main/kotlin/exercise3/task4/TaxiParkTask.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,56 @@ package exercise3.task4
* Find all the drivers who performed no trips.
*/
internal fun TaxiPark.findFakeDrivers(): Set<Driver> {
TODO("Implement me!!!")
return allDrivers.filter { driver -> trips.none { it.driver == driver } }
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 a correct solution, but its performance is not great because we'll have to do D * T iterations, where D is the number of drivers, and T is the number of trips.

The same solution can be done by mapping all the drivers from trips and then deducting all drivers from the list of drivers present in trips.

allDrivers - trips.map { it.driver }
This way we only once iterate over the trips list.

.toSet()
}

/**
* Subtask 2:
* Find all the clients who completed at least the given number of trips.
*/
internal fun TaxiPark.findFaithfulPassengers(minTrips: Int): Set<Passenger> {
TODO("Implement me!!!")
}
val passengerTripsCount = trips
.flatMap { it.passengers }
.groupingBy { it }
.eachCount()

return passengerTripsCount
.filter { it.value >= minTrips }
.keys}

/**
* Subtask 3:
* Find all the passengers, who were taken by a given driver more than once.
*/
internal fun TaxiPark.findFrequentPassengers(driver: Driver): Set<Passenger> {
TODO("Implement me!!!")
val frequentPassengers = trips
.filter { it.driver == driver }
.flatMap { it.passengers }
.groupingBy { it }
.eachCount()
.filter { it.value > 1 }

return frequentPassengers.keys
}

/**
* Subtask 4:
* Find the passengers who had a discount for the majority of their trips.
*/
internal fun TaxiPark.findSmartPassengers(): Set<Passenger> {
TODO("Implement me!!!")
val passengerDiscountTripsCount = trips
.flatMap { trip ->
trip.passengers.map { passenger ->
passenger to (if (trip.discount != null && trip.discount > 0) 1 else 0)
}
}
.groupBy({ it.first }, { it.second })
.mapValues { (_, discounts) -> discounts.sum() }

return passengerDiscountTripsCount
.filter { (_, discounts) ->
discounts >= trips.size / 2
Copy link
Owner

@vuksa vuksa Apr 6, 2024

Choose a reason for hiding this comment

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

Why are we comparing this with half of all trips? Shouldn't we compare against half of the trips this user made?

}
.keys
}