Skip to content

Commit

Permalink
Solve 'Help the bookseller !' kata
Browse files Browse the repository at this point in the history
  • Loading branch information
borisskert committed Oct 30, 2022
1 parent e02ba56 commit 0659b33
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<artifactId>kotlin-stdlib</artifactId>
<version>${kotlin.language.version}</version>
</dependency>

Expand Down
43 changes: 43 additions & 0 deletions src/main/kotlin/helpthebookseller/StockList.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package solution

/**
* https://www.codewars.com/kata/54dc6f5a224c26032800005c/train/kotlin
*/
object StockList {
fun stockSummary(lstOfArt: Array<String>, lstOfCat: Array<String>): String {
if (lstOfArt.isEmpty()) {
return ""
}

val stock = lstOfArt
.map(::readOne)
.groupBy { it.category }
.map { (key, value) ->
StockItem(key, value.sumOf { it.quantity })
}
.associateBy { it.category }

return lstOfCat
.map {
stock[it] ?: StockItem(it, 0)
}
.joinToString(" - ") {
"(${it.category} : ${it.quantity})"
}
}
}

data class StockItem(val category: String, val quantity: Int) {
}

val stockItemPattern = """([A-Z][A-Z0-9]+) ([0-9]+)""".toRegex()

fun readOne(input: String): StockItem {
val match = stockItemPattern.matchEntire(input)
val groups = match!!.groups

val category = groups[1]!!.value
val quantity = groups[2]!!.value

return StockItem(category.take(1), quantity.toInt())
}
53 changes: 53 additions & 0 deletions src/test/kotlin/helpthebookseller/StockListTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package solution

import org.junit.Test
import kotlin.test.assertEquals

class StockListTest {

private fun testing(lstOfArt: Array<String>, lstOfCat: Array<String>, expect: String) {
val actual: String = StockList.stockSummary(lstOfArt, lstOfCat)
assertEquals(expect, actual)
}

@Test
fun basicTest1() {
val b = arrayOf("BBAR 150", "CDXE 515", "BKWR 250", "BTSQ 890", "DRTY 600")
val c = arrayOf("A", "B", "C", "D")
val res = "(A : 0) - (B : 1290) - (C : 515) - (D : 600)"
testing(b, c, res)
}

@Test
fun basicTest2() {
val b = arrayOf("ABAR 200", "CDXE 500", "BKWR 250", "BTSQ 890", "DRTY 600")
val c = arrayOf("A", "B")
val res = "(A : 200) - (B : 1140)"
testing(b, c, res)
}

@Test
fun basicTest3() {
val b = arrayOf(
"ROXANNE 102",
"RHODODE 123",
"BKWRKAA 125",
"BTSQZFG 239",
"DRTYMKH 060",
"RHIB 1230",
"R0 530",
"XILO 32"
)
val c = arrayOf("U", "V", "R")
val res = "(U : 0) - (V : 0) - (R : 1985)"
testing(b, c, res)
}

@Test
fun emptyTest() {
val b = emptyArray<String>()
val c = arrayOf("A", "B", "C", "D")
val res = ""
testing(b, c, res)
}
}

0 comments on commit 0659b33

Please sign in to comment.