Text processing/1: Difference between revisions

Added Kotlin
(Added Kotlin)
Line 2,196:
The overall mean is 18.241666666666667
The largest run of bad values is 23, on 1991-03-31 beginning at 1:00 hours.
</pre>
 
=={{header|Kotlin}}==
As the link to the full data file is now broken, I've had to confine myself to the 6 lines shown in the task description for testing purposes.
<lang scala>// version 1.2.0
 
import java.io.File
 
fun main(args: Array<String>) {
val rx = Regex("""\s+""")
val file = File("readings.txt")
val fmt = "Line: %s Reject: %2d Accept: %2d Line_tot: %7.3f Line_avg: %7.3f"
var grandTotal = 0.0
var readings = 0
var date = ""
var run = 0
var maxRun = -1
var finishLine = ""
file.forEachLine { line ->
val fields = line.split(rx)
date = fields[0]
if (fields.size == 49) {
var accept = 0
var total = 0.0
for (i in 1 until fields.size step 2) {
if (fields[i + 1].toInt() >= 1) {
accept++
total += fields[i].toDouble()
if (run > maxRun) {
maxRun = run
finishLine = date
}
run = 0
}
else run++
}
grandTotal += total
readings += accept
println(fmt.format(date, 24 - accept, accept, total, total / accept))
}
else println("Line: $date does not have 49 fields and has been ignored")
}
 
if (run > maxRun) {
maxRun = run
finishLine = date
}
val average = grandTotal / readings
println("\nFile = ${file.name}")
println("Total = ${"%7.3f".format(grandTotal)}")
println("Readings = $readings")
println("Average = ${"%-7.3f".format(average)}")
println("\nMaximum run of $maxRun consecutive false readings")
println("ends at line starting with date: $finishLine")
}</lang>
 
{{out}}
<pre>
Line: 1991-03-30 Reject: 0 Accept: 24 Line_tot: 240.000 Line_avg: 10.000
Line: 1991-03-31 Reject: 0 Accept: 24 Line_tot: 565.000 Line_avg: 23.542
Line: 1991-03-31 Reject: 23 Accept: 1 Line_tot: 40.000 Line_avg: 40.000
Line: 1991-04-01 Reject: 1 Accept: 23 Line_tot: 534.000 Line_avg: 23.217
Line: 1991-04-02 Reject: 0 Accept: 24 Line_tot: 475.000 Line_avg: 19.792
Line: 1991-04-03 Reject: 0 Accept: 24 Line_tot: 335.000 Line_avg: 13.958
 
File = readings.txt
Total = 2189.000
Readings = 120
Average = 18.242
 
Maximum run of 24 consecutive false readings
ends at line starting with date: 1991-04-01
</pre>
 
9,476

edits