Skip to content

Instantly share code, notes, and snippets.

@zyuiop
Last active November 19, 2017 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zyuiop/1a5707b6e3cdae8ad6eedd06f9e3f3ef to your computer and use it in GitHub Desktop.
Save zyuiop/1a5707b6e3cdae8ad6eedd06f9e3f3ef to your computer and use it in GitHub Desktop.
A script to sort a list of elements according to the user input
/**
* @author Louis Vialar
*/
import java.io.File
import scala.collection.immutable.Stack
import scala.io.{Source, StdIn}
object Tempo {
def prompt(elem: String, head: String): Int = {
print(elem + " vs " + head + " => (1) ou (2) [0 to go back] ? ")
try {
val selected = StdIn.readInt()
if (selected >= 0 && selected <= 2) return selected
} catch {
case e: NumberFormatException => println("Pas un nombre :x")
}
prompt(elem, head)
}
def insertionSort(toSort: List[String], sorted: List[String], states: List[(List[String], List[String])]): List[String] = {
def insertElement(elem: String, sorted: List[String]): List[String] = {
if (sorted.isEmpty) return List(elem)
val head = sorted.head
val selected = prompt(elem, head)
if (selected == 1) elem :: sorted
else if (selected == 0) null
else head :: insertElement(elem, sorted.tail)
}
if (toSort.isEmpty) sorted
else {
val sort = toSort.head
val nSorted = insertElement(sort, sorted)
if (nSorted == null) {
if (states.isEmpty || states.tail.isEmpty) {
println("Erreur fatale : liste d'états vide.")
List()
} else {
val state = states.tail.head
insertionSort(state._1, state._2, states.tail)
}
} else insertionSort(toSort.tail, nSorted, (toSort.tail, nSorted) :: states)
}
}
def main(args: Array[String]): Unit = {
print("Chemin du fichier : ")
val path = StdIn.readLine()
val file = new File(path)
if (!file.exists()) {
println(s"Le fichier ${file.getAbsolutePath} n'existe pas")
}
println("Lecture...")
val data = Source.fromFile(file).getLines().toList
val sorted = insertionSort(data, List(), (data, List()) :: Nil)
println("Terminé !")
println("------------------------------")
val numbers = 1 to data.size
numbers.zip(sorted).foreach({
case (num, v) => println(s"#$num : $v")
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment