Skip to content

Instantly share code, notes, and snippets.

@pkinsky pkinsky/f2048
Last active Aug 29, 2015

What would you like to do?
functional 2048
//todo: use vector, scala 2:10 generic extractors. Currently using 2.9, so List has better pattern matching support
type Row = List[Option[Int]]
def shiftR(r: Row): Row = r.foldRight(Nil: Row){
case (None, acc) => acc
case (Some(x), Some(a)::as) if a == x => Some(a + x)::as
case (Some(x), acc) => Some(x)::acc
}.padTo(4, None)
def shiftL(r: Row): Row = r.foldLeft(Nil: Row){
case (acc, None) => acc
case (Some(a)::as, Some(x)) if a == x => Some(a + x)::as
case (acc, Some(x)) => Some(x)::acc
}.reverse.padTo(4, None)
use transpose to get at columns (need to ensure all dimensions are same somehow)
scala> val x = List(List(1,2,3), List(4,5,6), List(7,8,9))
x: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
scala> x.transpose
res13: List[List[Int]] = List(List(1, 4, 7), List(2, 5, 8), List(3, 6, 9))
scala> x.transpose.transpose == x
res15: Boolean = true
use padTo(n, elem) to pad out lists to size n by appending elem
//also, command line interface!
def print(b: Board) =".")).mkString("")).mkString("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.