Skip to content

Solutions for exercise6 taskProjections #23

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 11 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
16 changes: 16 additions & 0 deletions .idea/checkstyle-idea.xml

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

17 changes: 11 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,32 @@ 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()
.also { println("catalog: $it") }
.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
5 changes: 3 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,12 @@ 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!!!")
this.address = Address().apply(initAddress)
return this
}

fun main() {
Expand Down
29 changes: 27 additions & 2 deletions src/main/kotlin/exercise3/task1/BalancedBrackets.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package exercise3.task1

import java.util.Stack

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


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

fun isCorrectPop(bracket: Char): Boolean {
return !stack.isEmpty() && stack.pop() == bracket
}

for(bracket in expression) {
when(bracket) {
'{', '[', '(' -> stack.push(bracket)

'}' -> {
if(!isCorrectPop('{'))
return false
}
']' -> {
if(!isCorrectPop('['))
return false
}
')' -> {
if(!isCorrectPop('('))
return false
}
}
}
return stack.isEmpty()
}

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

internal fun String.splitToBracketsClusters(): List<String> {
TODO("Implement me!!!")
val clusters = mutableListOf<String>()
var numOfBrackets = 0
var clusterStartIndex = 0

for ((index, char) in this.withIndex()) {
when (char) {
'(' -> numOfBrackets++

')' -> {
numOfBrackets--
if (numOfBrackets == 0) {
clusters.add(this.substring(clusterStartIndex, index + 1))
clusterStartIndex = index + 1
} else if (numOfBrackets < 0) {
return emptyList() // Unbalanced expression
}
}
}
}
return if (numOfBrackets == 0) clusters else emptyList()
}

fun main() {
Expand Down
21 changes: 20 additions & 1 deletion src/main/kotlin/exercise3/task3/SherlockValidatesString.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,26 @@ package exercise3.task3
*/

internal fun isSherlockValid(s: String): String {
TODO("Implement me!!!")
val charCount = s.groupingBy { it }.eachCount()
val frequencies = charCount.values.toList()

if (frequencies.toSet().size == 1) {
return "YES"
}

if (frequencies.toSet().size == 2) {
val minFreq = frequencies.minOrNull()!!
val maxFreq = frequencies.maxOrNull()!!

if (frequencies.count { it == minFreq } == 1 && minFreq == 1) {
return "YES"
}

if (maxFreq - minFreq == 1 && frequencies.count { it == maxFreq } == 1) {
return "YES"
}
}
return "NO"
}

fun main() {
Expand Down
13 changes: 10 additions & 3 deletions src/main/kotlin/exercise3/task4/TaxiParkTask.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,30 @@ package exercise3.task4
* Find all the drivers who performed no trips.
*/
internal fun TaxiPark.findFakeDrivers(): Set<Driver> {
TODO("Implement me!!!")
return allDrivers - trips.map { it.driver }.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!!!")
return allPassengers.filter { passenger ->
trips.count { passenger in it.passengers } >= minTrips
}.toSet()
}

/**
* 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!!!")
return trips.filter { it.driver == driver }
.flatMap { it.passengers }
.groupingBy { it }
.eachCount()
.filterValues { it > 1 }
.keys
}

/**
Expand Down
43 changes: 37 additions & 6 deletions src/main/kotlin/exercise4/task1/BankAccount.kt
Original file line number Diff line number Diff line change
Expand Up @@ -32,21 +32,52 @@ package exercise4.task1
* The initial balance for this constructor should always be set to 0.
*/

open class BankAccount(
private val accountNumber: String,
private val accHolderName: String,
private var balance: Double
) {
constructor(accountNumber: String, accHolderName: String): this(accountNumber, accHolderName, 0.0)

open fun deposit(amount: Double): Boolean {
balance += amount
return true
}

open fun withdraw(amount: Double): Boolean {
if (amount <= balance) {
balance -= amount
return true
}
return false
}

fun getBalance(): Double {
return balance
}

open fun displayAccountInfo() {
println("Account Holder: $accHolderName")
println("Account Number: $accountNumber")
println("Balance: $balance")
println()
}
}

fun main() {
TODO("Uncomment the lines above after the Bank Account class is implemented.")

// Creating a Bank Account
// val account = BankAccount("123456789", "John Doe")
val account = BankAccount("123456789", "John Doe")

// Displaying account information
// account.displayAccountInfo()
account.displayAccountInfo()

// Depositing some money
// account.deposit(1000.0)
account.deposit(1000.0)

// Withdrawing some money
// account.withdraw(500.0)
account.withdraw(500.0)

// Displaying updated account information
// account.displayAccountInfo()
account.displayAccountInfo()
}
107 changes: 102 additions & 5 deletions src/main/kotlin/exercise4/task2/TransactionalBankAccount.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package exercise4.task2

import exercise4.task1.BankAccount
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
Expand Down Expand Up @@ -78,8 +79,104 @@ import java.util.*
* ```
*/

enum class TType {
DEPOSIT, WITHDRAWAL
}

enum class TStatus {
SUCCESS, FAILURE
}

data class Transaction(
val transactionDate: LocalDateTime,
val transactionType: TType,
val amount: Double,
val oldBalance: Double,
val newBalance: Double,
val transactionStatus: TStatus
)

class TransactionalBankAccount(
accountNumber: String,
accHolderName: String,
balance: Double,
) : BankAccount(accountNumber, accHolderName, balance) {

private val transactions: MutableList<Transaction> = mutableListOf()

override fun deposit(amount: Double): Boolean {
val oldBalance = getBalance()
super.deposit(amount)
val newBalance = getBalance()

transactions.add(Transaction(currentTime, TType.DEPOSIT, amount, oldBalance, newBalance, TStatus.SUCCESS))
return true
}

override fun withdraw(amount: Double): Boolean {
val oldBalance = getBalance()
val success = super.withdraw(amount)
val newBalance = getBalance()
val status = if (success) TStatus.SUCCESS else TStatus.FAILURE

transactions.add(Transaction(currentTime, TType.WITHDRAWAL, amount, oldBalance, newBalance, status))
return success
}

fun getAllTransactions(): List<Transaction> {
return transactions.sortedByDescending { it.transactionDate }
}

fun getAllTransactionsBy(predicate: (Transaction) -> Boolean): List<Transaction> {
return getAllTransactions().filter(predicate)
}

fun getTransactionsBetween(startDate: LocalDateTime, endDate: LocalDateTime): List<Transaction> {
return getAllTransactionsBy { it.transactionDate in startDate..endDate }
}

fun getAllFailedTransactions(): List<Transaction> {
return getAllTransactionsBy { it.transactionStatus == TStatus.FAILURE }
}

fun getAllSuccessfulTransaction(): List<Transaction> {
return getAllTransactionsBy { it.transactionStatus == TStatus.SUCCESS }
}

fun getAllFailedDeposits(): List<Transaction> {
return getAllTransactionsBy {it.transactionType == TType.DEPOSIT && it.transactionStatus == TStatus.FAILURE }
}

fun getAllFailedWithdrawals(): List<Transaction> {
return getAllTransactionsBy {it.transactionType == TType.WITHDRAWAL && it.transactionStatus == TStatus.FAILURE }
}

fun getAllSuccessfulDeposits(): List<Transaction> {
return getAllTransactionsBy { it.transactionType == TType.DEPOSIT && it.transactionStatus == TStatus.SUCCESS }
}

fun getAllSuccessfulWithdrawals(): List<Transaction> {
return getAllTransactionsBy { it.transactionType == TType.WITHDRAWAL && it.transactionStatus == TStatus.SUCCESS}
}

override fun displayAccountInfo() {
super.displayAccountInfo()
println("Transactions:\n")
if (transactions.isEmpty()) {
println("No transactions recorded\n")
} else {
transactions.forEach {
println("Transaction Date: ${it.transactionDate.prettyPrint()}")
println("Transaction Type: ${it.transactionType}")
println("Amount: ${it.amount}")
println("Old Balance: ${it.oldBalance}")
println("New Balance: ${it.newBalance}")
println("Status ${it.transactionStatus}")
println()
}
}
}
}

private val currentTime: LocalDateTime get() = LocalDateTime.now()

Expand All @@ -91,17 +188,17 @@ private fun LocalDateTime.prettyPrint(): String {
fun main() {
println(currentTime.prettyPrint())
// Creating a Transactional Bank Account
// val account = TransactionalBankAccount("123456789", "John Doe")
val account = TransactionalBankAccount("123456789", "John Doe", 0.0)

// Displaying account information
// account.displayAccountInfo()
account.displayAccountInfo()

// Depositing some money
// account.deposit(1000.0)
account.deposit(1000.0)

// Withdrawing some money
// account.withdraw(500.0)
account.withdraw(500.0)

// Displaying updated account information
// account.displayAccountInfo()
account.displayAccountInfo()
}
Loading