I'm trying to solve an old GCJ. It's a very simple puzzle, but I'm trying to sharpen my scala-fu.
Basically, you're getting a list of triple number srcLanguage dstLanguage, where number is an integer given in the numeral system of srcLanguage. You should translate it to the numeral system of `dstLanguage.
A numeral system is simply a string of all possible digits, in ascending order. The decimal numeral system is represented by 0123456789, the binary numeral system is 01, and the hexadecimal one 0123456789ABCDEF.
For example:
3 0123456789 01 -> 11
3 0123 AB -> BB
Here's how I implemented it in scala
case class Langs(num:String,srcLang:String,dstLang:String)
object Langs {def fromLine(line:String):Langs = {
val ar = line.split(" ");return Langs(ar(0),ar(1),ar(2))}}
object Translate {
def lang2int(lang:String,num:String):Long = {
var b = BigDecimal(0)
val dmap = (lang.toList.zipWithIndex).toMap
val digitsList = num map dmap
val valueList = digitsList.reverse.zipWithIndex map (
x => x._1 -> math.pow(dmap.size,x._2))
return valueList.map(x=>x._1*x._2).sum.toLong
}
def int2lang(lang:String,_num:Long):String = {
var num = _num
val dmap = (lang zip (0.toLong to lang.size)).map(_.swap).toMap
val sb = StringBuilder.newBuilder
while (num > 0) {
sb.append(dmap(num % dmap.size))
num = num/dmap.size
}
sb.reverse.toString
}
def lang2lang(l:Langs):String = int2lang(l.dstLang,lang2int(l.srcLang,l.num))
}
object mymain {
def main(args : Array[String]) : Unit = {
val s = "A-large-practice"
val basef = new java.io.FileInputStream("~/Downloads/"+s+".in")
val f = new java.util.Scanner(basef)
val out = new java.io.FileWriter(s+".out")
val n = f.nextInt
f.nextLine
for (i <- 1 to n) {
val nl = f.nextLine
val l = Langs.fromLine(nl)
out.write("Case #"+i+": "+Translate.lang2lang(l)+"\n")
}
out.close
}
}