Created
January 30, 2019 05:18
-
-
Save grosscol/c44549f99aac390a248a058e8c250d52 to your computer and use it in GitHub Desktop.
R homework help: monospace ascii art
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
# DrawShape | |
#' @title Draw Shape | |
#' @param n height of shape in number of rows | |
#' @description If n is odd, draw a diamond pattern. | |
#' If n is even, draw an hourglass pattern. | |
#' @note e.g. n = 6 | |
#' ##### | |
#' ### | |
#' # | |
#' # | |
#' ### | |
#' ##### | |
#' | |
#' e.g n = 5 | |
#' # | |
#' ### | |
#' ##### | |
#' ### | |
#' # | |
#' | |
draw_shape <- function(n){ | |
if(n %% 2 == 1){ | |
shape_width <-n | |
procession <- odd_procession(n) | |
} else { | |
shape_width <- n - 1 | |
procession <- even_procession(n) | |
} | |
result <- sapply(X=procession, FUN=line_of_symbols, line_length=shape_width) | |
cat(result, sep="\n") | |
} | |
#' @title Line of Symbols | |
#' @param num Number of shape symbols on the line | |
#' @param line_length Length of the line (width of shape) | |
#' @return A left padded character vector centering the shape symbols. | |
line_of_symbols <- function(num, line_length){ | |
padding_char <- ' ' | |
printed_char <- '#' | |
padding_count <- (line_length-num)/2 | |
character_array <- c(rep(padding_char, padding_count), rep(printed_char, num)) | |
paste0(character_array, collapse='') | |
} | |
#' @title Even Procession | |
#' @param x even integer height of shape | |
#' @return A vector of integers of number of symbols per line of shape | |
#' @note e.g. even_procession(6) #=> 5 3 1 1 3 5 | |
#' e.g. even_procession(8) #=> 7 5 3 1 1 3 5 7 | |
even_procession <- function(x){ | |
# YOUR IMPLEMENTATION HERE | |
# e.g. return( c(5,3,1,1,3,5) ) | |
} | |
#' @title Odd Procession | |
#' @param x odd integer height of shape | |
#' @return A vector of integers of number of symbols per line of shape | |
#' @note e.g. odd_procession(5) #=> 1 3 5 3 1 | |
#' e.g. odd_procession(7) #=> 1 3 5 7 5 3 1 | |
odd_procession <- function(x){ | |
# YOUR IMPLEMENTATION HERE | |
# e.g. return( c(1,3,5,3,1) ) | |
} | |
### Demo ### | |
draw_shape(4) | |
### | |
# | |
# | |
### | |
draw_shape(5) | |
# | |
### | |
##### | |
### | |
# | |
draw_shape(6) | |
##### | |
### | |
# | |
# | |
### | |
##### | |
draw_shape(7) | |
# | |
### | |
##### | |
####### | |
##### | |
### | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment