Last active
August 25, 2017 13:52
-
-
Save iamthiago/41ee3f31aa658881486434a9d4074cb3 to your computer and use it in GitHub Desktop.
This file contains hidden or 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.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