Last active
August 29, 2015 13:57
-
-
Save inanna-malick/9553812 to your computer and use it in GitHub Desktop.
functional 2048
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
//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) = b.map(_.map(_.map(_.toString).getOrElse(".")).mkString("")).mkString("\n") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment