Skip to content

Instantly share code, notes, and snippets.

@iamthiago
Last active August 25, 2017 13:52
Show Gist options
  • Save iamthiago/41ee3f31aa658881486434a9d4074cb3 to your computer and use it in GitHub Desktop.
Save iamthiago/41ee3f31aa658881486434a9d4074cb3 to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
import scala.collection.immutable.ListMap
object WeightSorting extends App {
def sortWeight(str: String): String = {
val map = str
.split(" ") //split by empty space
.map(s => (sumTailRecursive(s), s)) //let's create a tuple of (weight, string)
.groupBy(_._1) //group it by weight
.mapValues(s => s.map(_._2).sorted.mkString(" ")) //convert the values to a list, sort it by string
//sort the current map in a new one, take the values and return a string
ListMap(map.toSeq.sortBy(_._1): _*).values.mkString(" ")
}
def sumTailRecursive(s: String): Long = {
val init = s.toLong
@tailrec
def go(value: Long, acc: Long): Long = {
if (value == 0) acc else {
val lastDigit = value % 10
val headTail = value / 10
go(headTail, acc + lastDigit)
}
}
go(init, 0)
}
def sumRecursive(digit: Long): Long = {
if (digit == 0) 0
else digit % 10 + sumRecursive(digit / 10)
}
//2000 103 123 4444 99
println(sortWeight("103 123 4444 99 2000"))
//11 11 2000 10003 22 123 1234000 44444444 9999
println(sortWeight("2000 10003 1234000 44444444 9999 11 11 22 123"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment