Skip to content

Instantly share code, notes, and snippets.

@juan-medina
Created December 3, 2019 10:48
Show Gist options
  • Select an option

  • Save juan-medina/043276f1b1a05a4182300007112b2018 to your computer and use it in GitHub Desktop.

Select an option

Save juan-medina/043276f1b1a05a4182300007112b2018 to your computer and use it in GitHub Desktop.
Kata04: Data Munging
import java.io.File
open class CombineData(private val fileName: String) {
private fun getColumnValue(line: String, column: Pair<Int, Int>): String {
return line.substring(column.first, column.first + column.second - 1).trim().replace("*", "")
}
fun calculate(
value: Pair<Int, Int>,
columnA: Pair<Int, Int>,
columnB: Pair<Int, Int>, diffFunction: (Float, Float) -> Float
): String {
with(File(fileName)) {
if (this.exists()) {
val lines = this.readLines()
var minTeam = ""
var minDiff = Float.MAX_VALUE
var first = true
lines.forEach { line ->
if (!first) {
if (line.length > 15) {
val valueColumn = getColumnValue(line, value)
if (valueColumn != "----------------") {
val a = getColumnValue(line, columnA).toFloat()
val b = getColumnValue(line, columnB).toFloat()
val diff = diffFunction(a, b)
if (diff < minDiff) {
minDiff = diff
minTeam = valueColumn
}
println("$valueColumn $a $b $diff")
}
}
} else {
first = false
}
}
return minTeam;
}
}
return ""
}
}
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.junit.jupiter.api.Test
//http://codekata.com/kata/kata04-data-munging/
class CombineDataTests {
companion object {
fun getDataFilePath(file: String): String = {}.javaClass.getResource(file).file
}
@Test
fun `we can read the football data`() {
val footballData = FootballDataWithCombine(getDataFilePath("football.dat"))
val teamSmallDifference = footballData.smallDifference()
assertThat(teamSmallDifference, equalTo("Arsenal"))
}
@Test
fun `we can read the weather data`() {
val weatherData = WeatherDataWithCombine(getDataFilePath("weather.dat"))
val dayWithMimSpread = weatherData.minSpreadDay()
assertThat(dayWithMimSpread, equalTo(14))
}
}
class FootballDataWithCombine(private val fileName: String) : CombineData(fileName) {
fun smallDifference() = calculate(7 to 17, 43 to 3, 50 to 3) { a, b -> b - a }
}
import kotlin.math.absoluteValue
class WeatherDataWithCombine(private val fileName: String) : CombineData(fileName) {
fun minSpreadDay() = calculate(2 to 3, 6 to 4, 11 to 4) { a, b -> (a - b).absoluteValue }.toInt()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment