Skip to content
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

Add Sleep Sort in Scala #4495

Draft
wants to merge 15 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 12 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
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,7 @@ package-lock.json

# F#
Program.fs

# scala
.metals
.scala-build
54 changes: 54 additions & 0 deletions archive/s/scala/SleepSort.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import scala.collection.mutable.ListBuffer
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.concurrent.duration._

object SleepSort {
def main(args: Array[String]): Unit = {
var result = invalidChecker(args)

if(!result){ // After going through checker, it will output result to procede with SleepSort or not
// println(result)
println("Error with Input")
} else {
val numbers = args.flatMap(_.split(",")).map(_.trim).filter(_.nonEmpty).map(_.toInt)
println("Usage: please provide a list of at least two integers to sort in the format \"" + sleepSort(numbers)+"\"")
}
}


// Checking for formating, empty array, and Non-numeric values
def invalidChecker(args: Array[String]): Boolean = args match {
case null | Array() => false // "No Input"
case arr if arr.forall(_.isEmpty) => false //"Empty Input"
case arr if arr.forall(_.length == 1) && arr.length == 1 => false //"Invalid Input: Not A List"
case arr if !arr.exists(_.contains(",")) => false //"Invalid Input: Wrong Format"
case _ => {
val numbers = args.flatMap(_.split(",")).map(_.trim).filter(_.nonEmpty)

if (numbers.forall(n => n.forall(_.isDigit))) {
true //"true" // <- passing true to procede with SleepSort
} else {
false //"Invalid Input: Non-numeric Values"
}
}
}

// delaying time to add a value to list base on it weight
def sleepSort(args: Array[Int]): String = {
val delayTimer: Long = 1000L
val outputArray = ListBuffer[String]()

val futures = args.map { num =>
Future {
Thread.sleep(num * delayTimer)
synchronized { // Ensure thread safety
outputArray += num.toString
}
}
}

Await.result(Future.sequence(futures), Duration.Inf) // intializing the data into outputArray
outputArray.mkString(", ")
}
}