Last active
November 29, 2023 19:40
-
-
Save evilthreads669966/5f4f5326e38e5d67d09311bed817e728 to your computer and use it in GitHub Desktop.
Five number summary calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.io.StdIn.readLine | |
import scala.util.Sorting | |
import scala.math.floor | |
import scala.util.control.Breaks.{break, breakable} | |
@main | |
def main(): Unit = { | |
while true | |
do | |
breakable{ | |
println("Enter a set of numbers separated by commas") | |
var numbers = readLine() | |
if numbers == null then break | |
val parts = numbers.split(",") | |
val list = parts.map(_.trim.toInt) | |
list.toList.toFiveNumberSummary() match | |
case Some(summary) => { | |
println(s"Q1 = ${summary.quartiles.q1} Q2 = ${summary.quartiles.q2} Q3 = ${summary.quartiles.q3}") | |
println(s"MIN = ${summary.min} MAX = ${summary.max}") | |
} | |
case None => println("Please enter more than one number") | |
} | |
} | |
case class FiveNumberSummary(quartiles: Quartiles, min: Int, max: Int) | |
case class Quartiles(q1: Double, q2: Double, q3: Double) | |
extension (list: Iterable[Int]) | |
def toFiveNumberSummary(): Option[FiveNumberSummary] = { | |
if list.size == 1 then return None | |
val sortedList = Sorting.stableSort(list.toSeq) | |
val min = sortedList(0) | |
val max = sortedList.last | |
if sortedList.size % 2 == 0 then | |
val left = ((sortedList.size - 1)/ 2) - 1 | |
val right = left + 2 | |
val q2 = (sortedList(left + 1) + sortedList(left + 2)) / 2.0 | |
var q1 = 0.0 | |
var q3 = 0.0 | |
if (sortedList.size / 2) % 2 == 0 then | |
q1 = (sortedList(left / 2) + sortedList((left / 2) + 1)) / 2.0 | |
q3 = (sortedList((right + sortedList.size - 1) / 2) + sortedList((right + sortedList.size) / 2)) / 2.0 | |
else | |
q3 = sortedList((right + sortedList.size - 1) / 2) | |
q1 = sortedList((left + 1) / 2) | |
Some(FiveNumberSummary(Quartiles(q1,q2,q3), min, max)) | |
else | |
val left = floor((sortedList.size / 2.0) - 1).toInt | |
val right = left + 2 | |
val middle = left + 1 | |
val q2 = sortedList(middle) | |
var q1 = 0.0 | |
var q3 = 0.0 | |
if ((sortedList.size - 1) / 2) % 2 == 0 then | |
q1 = (sortedList(left / 2) + sortedList(left / 2 + 1)) / 2.0 | |
q3 = (sortedList((right + sortedList.size - 1) / 2) + sortedList((right + sortedList.size - 1) / 2 + 1)) / 2.0 | |
else | |
q1 = sortedList((left + 1) / 2) | |
q3 = sortedList((right + (sortedList.size - 1)) / 2) | |
Some(FiveNumberSummary(Quartiles(q1,q2,q3), min, max)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment