Last active
December 27, 2015 18:09
-
-
Save animatedlew/7367138 to your computer and use it in GitHub Desktop.
A little program that uses recursion, and uses combinations to draw out Pascal's 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
object Main extends App { | |
// Find any place in the triangle using n choose k | |
def pascal2(r: Int, c: Int): Int = { | |
def factorial(n: Int): Int = | |
if (n < 1) 1 else n * factorial(n - 1) | |
factorial(r) / (factorial(c) * factorial(r - c)) | |
} | |
def pascal(r: Int, c: Int): Int = { | |
if (c == 0 || c == r) 1 | |
else pascal(r - 1, c - 1) + pascal(r - 1, c) | |
} | |
def triangle(totalRows: Int, op: (Int, Int) => Int) = { | |
var list: String = "" | |
(0 to totalRows).foreach(row => { | |
(0 until totalRows - row).foreach(space => list += " ") | |
(0 to row).foreach(col => { | |
list += op(row, col).toString.padTo(4, ' ') | |
}) | |
list += "\n" | |
}) | |
list | |
} | |
print(triangle(6, pascal)) | |
print(triangle(6, pascal2)) | |
} | |
/* | |
1 | |
1 1 | |
1 2 1 | |
1 3 3 1 | |
1 4 6 4 1 | |
1 5 10 10 5 1 | |
1 6 15 20 15 6 1 | |
1 | |
1 1 | |
1 2 1 | |
1 3 3 1 | |
1 4 6 4 1 | |
1 5 10 10 5 1 | |
1 6 15 20 15 6 1 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment