Skip to content

Instantly share code, notes, and snippets.

@maasg
maasg / Expr.scala
Last active December 18, 2015 01:29
Generates all productions of a given length for a regex-defined grammar. e.g. a*(a|b)b* -> val expr = Concat(Star(Literal('a')),Concat(Or(Literal('a'),Literal('b')), Star(Literal('b')))) expr.produce(5) = Set[String] = Set(abbbb, aaaab, bbbbb, aaabb, aaaaa, aabbb) The regex parser to generate the expression is a TODO for the reader :-)
package com.gm.exer.regex
case class Limit(start:Int, end:Int) {
def union(r2:Limit) = new Limit(start.min(r2.start), end.max(r2.end))
def concat(r2:Limit) = new Limit(start.max(r2.start), end + r2.end)
def toRange = start until end inclusive
}
abstract class Expr {
def range(limit: Int): Limit
// Code exercise for http://community.topcoder.com/stat?c=problem_statement&pm=4464&rd=7219
object DialPad {
val dial = Array(Array("1","2","3"),Array("4","5","6"),Array("7","8","9"),Array("*","0","#"))
// creates a map of a dial key and its coordinates. e.g 1 -> (0,0)
val dialCoords = for {indexedRow <- (dial.indices zip dial)
row <- indexedRow._2.indices zip indexedRow._2
elem <- row._2 } yield (elem -> (indexedRow._1, row._1))
val dialCoordMap = dialCoords.toMap
// for each key creates a lookup map to all other keys in the form (dialKey -> map(dialKey -> distance value))
val dialLookup = dialCoordMap.map({case (key, (x1,y1)) => key -> dialCoordMap.map({case (k2, (x2,y2)) => (k2, math.abs(x2-x1)+math.abs(y2-y1))})})
@maasg
maasg / Decipher.scala
Last active December 18, 2015 18:39
Scala solution to TopCoder practice problem "Decipher": http://community.topcoder.com/stat?c=problem_statement&pm=4674&rd=7227
import scala.collection.SortedSet
import scala.collection.SortedMap
// Attempts to decipher an encripted message by matching the frequency of letters in the message vs an ordered frequency key
object Decipher {
// calculates a decoding table in the form (encoded->decoded)
def codex(encoded:String, freq: String):Map[Char,Char] = {
// Transforms the encoded string in a frequency map char->frequecy(int). Note that white spaces are removed
val charFreqMap = encoded.filter(_!=' ').foldLeft(Map[Char,Int]())((x,y) => {val freq = x.getOrElse(y,0)+1; x + ((y,freq))})
@maasg
maasg / ListerningIn.scala
Last active April 25, 2016 07:47
Scala Solution to Top Coder problem: http://community.topcoder.com/stat?c=problem_statement&pm=4670&rd=8006 #Learning Scala
import scala.collection.immutable.StringOps
// Solution to Top Coder problem: http://community.topcoder.com/stat?c=problem_statement&pm=4670&rd=8006
object ListeningIn {
def probableMatch(typed:String , phrase:String ): String = {
// recursively consumes both char sequences finding matches. Accumulates the elements in phraseSeq that do not match typeSeq
// not tail rec
def matcher(typeSeq:Seq[Char], phraseSeq:Seq[Char]): Option[Seq[Char]] = (typeSeq, phraseSeq) match {
case (Seq(), Seq()) => Some("")
case (Seq(), Seq(xs@_*)) => Some(xs)
@maasg
maasg / WorldCompositionGame.scala
Last active December 18, 2015 21:28
Solution to TopCoder problem 'WordCompositionGame' http://community.topcoder.com/stat?c=problem_statement&pm=4483&rd=7228 #ScalaPractice
object WordCompositionGame {
def score(listA:Array[String] , listB:Array[String], listC:Array[String]): String = {
// turn those arrays into some useful Sets
val a = listA.toSet
val b = listB.toSet
val c = listC.toSet
val all = Set(a,b,c)
// calculates the intersection of a,b and c
val abc = all.reduceLeft(_.intersect(_))
@maasg
maasg / PrimeStatistics.scala
Last active December 18, 2015 23:39
Scala solution to TopCoder problem 'PrimeStatistics': #LearningScala
object PrimeStatistics {
def isPrime(x:Int):Boolean = {
if (x==1 || x==2 || x==3) return true
if (x % 2 == 0) return false
(3 to math.sqrt(x).toInt by 2).forall(y=>x % y != 0)
} //> isPrime: (x: Int)Boolean
def mostCommonRemainder(lowerBound:Int, upperBound:Int, modulo:Int):Int = {
val primesInRange = (lowerBound to upperBound).filter(isPrime)
val modulos = primesInRange.map(x => x % modulo)
@maasg
maasg / SortBooks.scala
Created June 29, 2013 22:54
Scala solution for TopCoder 'SortBooks' exercise: http://community.topcoder.com/stat?c=problem_statement&pm=4557&rd=7996 #LearningScala
object SortBooks {
val lexSeparators = Set("THE","AND","OF")
def isABook(s:String): Boolean = {
val words = s.split("\\s+")
if (words.size > 3) true else {
!words.map(_.toUpperCase).toSet.intersect(lexSeparators).isEmpty
}
}
@maasg
maasg / CmpdWords.scala
Created June 30, 2013 14:58
Scala solution to TopCoder exercise CmpdWords: http://community.topcoder.com/stat?c=problem_statement&pm=3490&rd=8001 #LearningScala
object CmpdWords {
def permutedPairs(elems:List[String]): List[String] = {
elems match {
case Nil => List()
case x::Nil => List()
case x::xs => {
for {x <- elems;
y <- elems-x} yield x+y
}
//http://community.topcoder.com/stat?c=problem_statement&pm=6477&rd=9988
object HuffMannDecode {
abstract class BinTree {
def add(repr: List[Char], c:Char): BinTree = {
def add(tree: BinTree, repr: List[Char], c:Char): BinTree = {
(repr, tree) match {
case (Nil, EmptyTree) => Leaf(c)
case ('0'::tail, EmptyTree) => Node(add(EmptyTree,tail,c),EmptyTree)
case ('1'::tail, EmptyTree) => Node(EmptyTree, add(EmptyTree,tail,c))
object ATower {
def lengthEncode(l: List[Int]):List[Tuple2[Int,Int]] = l match {
case Nil => List()
case n::Nil => List((n,1))
case n::tail => val (repeats, rest) = tail.span(x=>x==n); (n,repeats.length+1) :: lengthEncode(rest)
}
def towers(l1: String, l2:String):(Int,Int) = {
val lines = l1.toInt