Reader Challenge: Write a Formula to Calculate Gift Totals in "The Twelve Days of Christmas"
It's almost Christmas and my 10-year-old and 17-year-old both informed me that one's true love delivers 364 total gifts throughout the entirety of the song, "The Twelve Days of Christmas."
My fifth-grade son thought this was interesting, but my high school senior-daughter wanted to come up with an algebraic formula that would take as input the song verse and produce as output the total number of gifts delivered to that point in the song. We both underestimated the challenge.
We set out to solve the problem without googling a solution. I'm sure many exist; it's the internet after all. Heck, there's probably an entire subreddit out there dedicated to just this one math problem. On the internet, even the niches have niches.
Test-Driven Development
In keeping with my recent theme here, I started by creating a set of doc tests. I used some simple Excel formulas to generate the solutions as shown above. Here are the twelve doc tests I started with:
'>>> GiftsByXmasDay(1)
' 1
'>>> GiftsByXmasDay(2)
' 4
'>>> GiftsByXmasDay(3)
' 10
'>>> GiftsByXmasDay(4)
' 20
'>>> GiftsByXmasDay(5)
' 35
'>>> GiftsByXmasDay(6)
' 56
'>>> GiftsByXmasDay(7)
' 84
'>>> GiftsByXmasDay(8)
' 120
'>>> GiftsByXmasDay(9)
' 165
'>>> GiftsByXmasDay(10)
' 220
'>>> GiftsByXmasDay(11)
' 286
'>>> GiftsByXmasDay(12)
' 364
Function GiftsByXmasDay(DayOfXmas As Long) As Long
'--== Your code goes here ==--
End Function
Reader Challenge
How would you solve this problem?
To verify your solution, start by grabbing my DocTests function from here. Then copy the above code comments and function definition and paste them into a blank code module. Run DocTests
in the immediate window and confirm all 12 tests fail. Then fill in the function until all tests pass.
In the next couple of days, I will post at least two different solutions: one using a traditional function and another that uses recursion.
Please refrain from posting your solutions in the comments of this article. Save them for one of the follow-up articles so that we don't have any spoilers here. Have fun!
Referenced articles
Cover image created with Microsoft Designer