Skip to content

Instantly share code, notes, and snippets.

@expersso
Last active March 2, 2017 16:06
Show Gist options
  • Save expersso/f56e2e112bb86f41615007763f9cf3d2 to your computer and use it in GitHub Desktop.
Save expersso/f56e2e112bb86f41615007763f9cf3d2 to your computer and use it in GitHub Desktop.
Generate Pascal's triangle using purrr
library(tidyverse)
library(stringr)
pascal_triangle <- function(n) {
df <- data_frame(N = 0:n, k = map(N, seq, from = 0)) %>%
unnest() %>%
mutate(c = choose(N, k)) %>%
group_by(N) %>%
summarise(c = paste(c, collapse = " "))
df$c %>%
str_pad(5 * (n + 1), "both") %>%
paste(collapse = "\n") %>%
cat()
}
pascal_triangle(15)
@expersso
Copy link
Author

expersso commented Mar 2, 2017

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment