Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created March 25, 2014 00:48
Show Gist options
  • Save bennadel/9752986 to your computer and use it in GitHub Desktop.
Save bennadel/9752986 to your computer and use it in GitHub Desktop.
Ask Ben: Recursive Numeric Pyramid
<!--- Get the max height of the numeric pyramid. --->
<cfset intHeight = 4 />
<!---
Loop over the number of rows that we want to display
in our numeric pyramid. This will start at negative
*height* and go to positive *height*. This will give
us ((height * 2) + 1) rows.
--->
<cfloop
index="intRow"
from="#-intHeight#"
to="#intHeight#"
step="1">
<!---
Loop over the number of columns in this row,
starting at zero.
--->
<cfloop
index="intCol"
from="0"
to="#(intHeight - Abs( intRow ))#"
step="1">
#intCol#
</cfloop>
<!--- Line break. --->
<br />
</cfloop>
<cffunction
name="OutputPyramid"
access="public"
returntype="void"
output="true"
hint="Outputs the numeric pyramid.">
<!--- Define arguments. --->
<cfargument
name="TargetHeight"
type="numeric"
required="true"
hint="The max height of the numeric pyramid."
/>
<cfargument
name="CurrentHeight"
type="numeric"
required="false"
default="0"
hint="The current height of the output pyramid."
/>
<!--- Define the local scope. --->
<cfset var LOCAL = StructNew() />
<!---
Check to see if the current height is equal to the
target height. In that case, we are going to output
just one row.
--->
<cfif (ARGUMENTS.TargetHeight EQ ARGUMENTS.CurrentHeight)>
<!--- Simply output the row to max height. --->
<cfloop
index="LOCAL.Column"
from="0"
to="#ARGUMENTS.TargetHeight#"
step="1">
#LOCAL.Column#
</cfloop>
<br />
<cfelse>
<!---
Since we are not outputting the max height row, we
want to output TWO of the same column sets with a
recursive call in the middle.
--->
<!--- Output first row. --->
<cfloop
index="LOCAL.Column"
from="0"
to="#ARGUMENTS.CurrentHeight#"
step="1">
#LOCAL.Column#
</cfloop>
<br />
<!---
In between our two mirrow columns, we want to output
the middle content. These are the rows with heigher
columns (and eventually the one max row). To make
this recursive, make sure to re-call this method
with a larget current row.
--->
<cfset OutputPyramid(
TargetHeight = ARGUMENTS.TargetHeight,
CurrentHeight = (ARGUMENTS.CurrentHeight + 1)
) />
<!--- Output second row (same as first). --->
<cfloop
index="LOCAL.Column"
from="0"
to="#ARGUMENTS.CurrentHeight#"
step="1">
#LOCAL.Column#
</cfloop>
<br />
</cfif>
<!--- Return out. --->
<cfreturn />
</cffunction>
<!--- Output a numeric pyrmaid with max height of 4. --->
<cfset OutputPyramid( 4 ) />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment