Last active
December 23, 2015 08:29
-
-
Save AKST/6608550 to your computer and use it in GitHub Desktop.
Recursively Generate Pascals Triangle
This file contains 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 | |
object PascalsTriangle { | |
type Triangle = Map[(Int, Int), Int] | |
type TriangleResult = (Triangle, Int, Int) => Triangle | |
def generateTriangle(colMax: Int, rowMax: Int, generateResult: TriangleResult): Triangle = { | |
@tailrec | |
def recLoop(triangle: Triangle, colIt: Int, rowIt: Int): Triangle = | |
if (rowIt > rowMax + 1) | |
triangle | |
else if (colIt < rowIt) | |
recLoop(generateResult(triangle, colIt, rowIt), colIt + 1, rowIt) | |
else | |
recLoop(generateResult(triangle, colIt, rowIt), 0, rowIt + 1) | |
recLoop(TreeMap[(Int, Int), Int](), 0, 0) | |
} | |
private def calcPascalsTriangleCell(tri: Triangle, col: Int, row: Int): Triangle = | |
if (col == 0 || col == row) | |
tri ++ TreeMap((col, row) -> 1) | |
else | |
tri ++ TreeMap((col, row) -> (tri(col - 1, row - 1) + tri(col, row - 1))) | |
def pascalsTriangle(col: Int, row: Int): Int = | |
generateTriangle(col, row, calcPascalsTriangleCell)((col, row)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment