The Problem

Suppose that you have the job of making a function called diamond() that produces diamond-shaped output in the console, like this:

##   a  
##  aba 
## abbba
##  aba 
##   a

The function is supposed to have two arguments:

  • outside: the character on the border of the diamond. The default value should be "x.
  • inside: the character in the interior of the diamond. The default value should be "o".

A typical example of use would be:

##   m  
##  m-m 
## m---m
##  m-m 
##   m

The Solution, Step-By-Step

Don’t try to write the function all at once. Instead build it up gradually in the following steps.

Step One: Make a Specific Diamond

Figure out how to make a diamond for two specific characters. For example, say that the outside character is a and the inside character is b. You could do this:

##   a  
##  aba 
## abbba
##  aba 
##   a

Step Two: Use Variables

Next, solve the same problem, but represent the desired characters with variables:

##   a  
##  aba 
## abbba
##  aba 
##   a

Note that you had to use sep ="" in order to stick together the pieces with no spaces between them.

You are now pretty close to having a function. If you want a different diamond, you only have to change the values of outside and inside, like this:

##   x  
##  xrx 
## xrrrx
##  xrx 
##   x

Step Four: Final Tweaks

Go back to the original directions and make sure that your function will perform exactly as specified.

When we revisit the directions, we recall that the parameters needed default values. So we add them:

Then perform a few final checks:

##   k  
##  khk 
## khhhk
##  khk 
##   k
##   h  
##  hoh 
## hoooh
##  hoh 
##   h
##   x  
##  xox 
## xooox
##  xox 
##   x

Everything seems to work as required. We are done.