Follow

Calling all programmers

Code a puzzle 4 Xmas

The Twelve Days of Christmas

According to the traditional song, on the first day of Christmas (25th December), my true love sent to me:

  • A partridge in a pear tree

On the second day of Christmas (26th December), my true love sent to me THREE presents:

  • Two turtle doves
  • A partridge in a pear tree

On the third day of Christmas (27th December and so on) my true love sent to me SIX presents:

  • Three French hens
  • Two turtle doves
  • A partridge in a pear tree

This carries on until the the twelfth day of Christmas, when my true love sends me:

  • Twelve drummers drumming
  • Eleven pipers piping
  • Ten lords a-leaping
  • Nine ladies dancing
  • Eight maids a-milking
  • Seven swans a-swimming
  • Six geese a-laying
  • Five gold rings
  • Four calling birds
  • Three French hens
  • Two turtle doves
  • A partridge in a pear tree

Puzzle Author: Stephen Froggatt

  1. Strict, hard coded, solution:
    ```
    function allgifts()
    dg = [] # daily gifts storage
    for d in 1:12
    d = sum(1:d) # daily gifts from day 1 to 12
    push!(dg, d) # storing each day gifts
    end
    print(sum(dg)) # showing total number of gifts in storage
    end

> allgifts()

364

2. Generalizing the function for any number of days:

I’ll put here my solution (in Julia) on the twelfth day

```
Meanwhile, I invite you all to post in the comments some solution coded in the programming language of your choice

(as )

2. Generalizing the function for any number of days:

function allgifts2(days)
dg = [] # daily gifts storage
for d in 1:days
d = sum(1:d) # daily gifts from day 1 to days
push!(dg, d) # storing each day gifts
end
print(sum(dg)) # showing total number of gifts in storage
end

There are actually 13 days from 25 Dec to 6 Jan

Let’s add to the list Thirteen puzzlers puzzling

> allgifts(13)

455

Did The Wise Men (Magi) Arrive 12 Days After Jesus’ Birth?
reasonsforhopejesus.com/did-th

Happy Three Kings Day

Show thread

@mc

The solution depends on whether or not the partridges know how to play the drums.

@Pat I assure you do not have to to go back to the 70s to write a solution. 😉

@mc

I first went to Mathlab, but then thought it would be more fun to use something completely unsuited to the task, like AWK or BASH.

Are you looking for code for a function similar to the hard-coded solution in your example, or are you looking for some kind of mathematical shortcut using factorials or calculus or something?

(I’m not a math gal but I’m sure this must be a well-known series in mathematics, with the name of some old mathematician tacked on to it.)

@Pat
You may find it hard to believe, but I’m making this for fun, in the spirit of the season.
As you’ve been so kind to offer me the choice, AWK please. 😃
(Yes, it’s similar to “a well known series in mathematics, with the name of some old mathematician…” 🤭 )

My Answer (spoilers) 

@mc

Here’s the solution in awk:

awk ‘n=0;{for (i=1; i<=$1; i++) n=n+(i^2+i)/2;print n}’

I don’t know if there is a mathematical shortcut for the whole function – I couldn’t figure one out. But I did figure out a shortcut for the summation of a sequence of numbers…

If you add the first and last numbers in the series, you get 1+n. The same for the second number plus second to last number, etc., because they increment/decrement respectively. If you keep going, you meet in the middle of the sequence – half way. So, the sum of all the numbers is the same as n+1 multiplied by half the number of numbers in the sequence, or (n+1)(n/2). I tested it and it works with an odd number also. A little algebra, (n+1)(n/2)=(n^2+n)/2. (I also found this on the internet, so I know it’s right.) If you write it using a language that doesn’t have an exponent function, you could just use (n+1)(n/2). (In fact, that might be more efficient/faster, I didn’t test it.)

So, using that shortcut, it’s just a simple loop to “sum the sums”. If you use a language with a summation function it would be even easier.

Without the shortcut you got to nest loops or use an array or something.

(ps - I’m not really a programmer, i.e., I don’t do it for a living, but I answered the “call” anyway.)

My Answer (spoilers) 

@Pat
I don’t use AWK. This said, the code seems legit, but I cannot replicate it. There must be some shenanigan I don’t know how to fix.
The thing is: when I execute the line it stalls indefinitely.

My Answer (spoilers) 

@mc

“when I execute the line it stalls indefinitely.”

AWK is designed to mostly process text, either from a file or from stdin (standard input). It’s a text stream processor.

If you specify a file name, it takes input from that file; if you don’t specify a file name, it takes input from stdin. As it’s presented in the toot, there is no file name so it takes input from stdin, in this case from the keyboard.

So when it “stalls” just enter numbers in your keyboard and it will spit out the answers.

You can also specify a list of numbers (one per line) for input in a file like this:

awk ‘n=0;{for (i=1; i<=$1; i++) n=n+(i^2+i)/2;print n}’ numbers.txt

and it will spit out the answers for all of the numbers from the file “numbers.txt”. The “$1” in the code is the parameter for the first input field of a line from the input – in this case just the one field, the number you input from stdin.

(For what AWK was designed for, I’m surprised it had an exponent function.)

My Answer (spoilers) 

@Pat
Brilliant solution.
With extra points because I laughed out loud when I read “I also found this on the internet, so I know it’s right.” 😆
Also, I’m a little reluctant to believe that you didn’t know already that this was an arithmetic progression. May I be forgiven if I’m wrong.
Once again thank you for taking the time to participate.
Wish you a good new year.

My Answer (spoilers) 

@mc

I guessed it was some kind of series that was likely well-known to mathematicians, but the term “arithmetic progression” didn’t come mind at all. Now that you’ve said it, yeah, it’s a progression and it’s additive (arithmetic), so it makes sense.

As I said, I’m not a math person. My last algebra class was when Nixon was still in office! I’m surprised I even remembered how to do the simple algebra in that solution.

You’re forgiven, of course.

Have a happy new year.

My Answer (spoilers) 

@mc

Just for fun here’s a solution in BASH…

n=0;for ((i=1;i<=1000;i++)); do n=$((n+(i*(i+1)/2)));echo “$i - $n”;done

Prints the solution for the first 1000 days.

BASH has exponentiation (**) but this shows to how it would be done without it – (n^2+n)/2 becomes n(n+1)/2.

Again, I’m sure there must be some shortcut for this, but I can’t figure one out.

Also, I looked up “arithmetic progression” and this doesn’t fit the definition (each number differs by a fixed amount). It looks like an exponential function or maybe an “arithmetico–geometric sequence”.

My Answer (spoilers) 

@Pat
Apparently this is the Unix sysadmin way, not using any shell math features ;)

for i in `seq 1 12`; do for j in `seq 1 $i`; do head -c $j /dev/zero; done; done | wc -c

My Answer (spoilers) 

@mc

OMG!

I wanted to do a really inefficient one using BASH string parameter expansion, but you already got me beat with that one.

My Answer (spoilers) 

@Pat

I looked up “arithmetic progression” and this doesn’t fit the definition

Of course it does not fit… Did I say it was an arithmetic progression? OG, what was I thinking?!

Sorry. Now I’m focused. It’s just a triangular numbers sequence with accumulation of all previous results.

My Answer (spoilers) 

@mc

My unconscious brain keeps interrupting my day with ideas on this…

When I first started working on this I wrote out the sequence graphically, like below. Your hint about triangles reminded me of those graphic notations I made, which lead me to this:

If you put those triangles on top of each other you get a tetrahedron, so the solution should be the formula for the volume of a tetrahedron. I tried the formula for a regular tet. – d^3/(6*sqr(2)) – and it didn’t work. (d = # of days)

The volume for any tet is: Ah/3
(where A is the area of the base triangle and h is the height)

Well, that doesn’t seem to work either. But I think the solution is in this line of reasoning somewhere. I think figuring out what the value of h would be for any given number days is the key to solving this.

Do you already know what the general formula is?

(by the way, this has some applications in certain quantum theories)

My Answer (spoilers) 

@Pat

My unconscious brain keeps interrupting my day with ideas on this…

OMG! What have I done? I’m sorry, really didn’t mean to… 😅

the solution should be the formula for the volume of a tetrahedron

Wouldn’t it be nice if it could be so simple? 😃

Do you already know what the general formula is?

Nope. But I trust you will find it. Some authors say that obsessive thinking is the start of the ‘Eureka’ moment. 🤭

My Answer (spoilers) 

@Pat
Perhaps you can find some relation between the heights of the successive tet.s? (If youhave the time and he will to do it, of course.) :blobcatsweat:

My Answer (spoilers) 

@mc

The tetrahedron approach didn’t pan out, I think because the series are discrete integers whereas the tet equations are (some) derived from calculus and trig.

I’ve generalized the sum function equation as (F+L)(N/I), where;
F=first number in sequence
L=last number in sequence
N=# of numbers in the sequence
I=the interval between numbers

I did this so I can solve it by looking at the differences between the daily sums; and then the differences between those differences - like this:

1 - 1 , 78 , 79
2 - 3 , 66 , 69
3 - 6 , 55 , 61
4 - 10 , 45 , 55
5 - 15 , 36 , 51
6 - 21 , 28 , 49
7 - 28 , 21 , 49
8 - 36 , 15 , 51
9 - 45 , 10 , 55
10 - 55 , 6 , 61
11 - 66 , 3 , 69
12 - 78 , 1 , 79
364, 364

Trying to apply the method to “sum the sums”. Notice that adding the first + last, 2nd + 2nd last, etc. yields a symmetric pattern. The differences between them are 2, 4, 6, 8 … which is a regular sequence that can be totaled using the generalized summing equation.

So a shortcut formula could count that sequence working from the “middle” day and I think the rest could be derived from that to get the final result.

I think it’s just grunt work now to put it all into an equation and algebra the shit out of it, in order to get the final shortcut equation.

Of course you could just use the summation symbol in an equation or the sum function in mathlab or julia, but the goal is to get something that only uses +,-,*,/ and maybe ^, without loops.

My Answer (spoilers) 

@Pat

Of course you could just use the summation symbol in an equation or the sum function in mathlab or julia

That’ll do, as long as I know how the sum function works. 😃

My Answer (spoilers) 

@mc

I looked up summation on wikipedia and there was a link in one of the footnotes to the article “Triangular number”. That article has a lot of the stuff I came up with while trying to discover the answer on my own. It talks about differences and also tetrahedrons! Very cool.

The answer is in the section: en.wikipedia.org/wiki/Triangul

Two summation symbols next to each other is kind of what I expected, except I would have ignorantly put the second sigma within parentheses, or shown it as two separate equations. That solution itself has a shortcut version of notation using something called binominal coefficient notation. Way above my head.

I didn’t think there would be a solution without using summation notation, but the article provides one:

(n(n+1)(n+2))/6

The product of the three numbers in (and beyond) the series; n, n+1, n+2; represent three dimensions of a rectangle, while the number 6 is the number of tetrahedrons that fit together to form that rectangle, which you can visualize with their peaks meeting in the middle of the rectangle.

So the tet method of solving this would have panned out after all. I just needed to intuit multiple tets in a rectangle, which I actually saw while looking up the tet volume equation, but just didn’t put the two together.

Isn’t learning fun…

My Answer (spoilers) 

@Pat

Isn’t learning fun…

absolutely fascinating… For approximately 1% of the world population.

So, in spite of being “not a math gal” you got it.

Well, I’m impressed.

I never thought that Wikipedia would have such good math articles.

You also seem very comfortable discussing physics.

My Answer (spoilers) 

@mc

A couple mistakes in my explanation…

The equation I posted has extra parenthesis. It should be

total = n(n+1)(n+2) / 6
where n=# of days

(I tried to post this here using LaTex, but it didn’t work.)

Also, I said that six tetrahedrons fit into a rectangle, but that should be six square pyramids, not six tets. But tets use the same formula to determine their volume: Ah / 3
(A=base area, h=height), so it still works, except the base area uses a different formula.

I also just noticed that factorials are, indeed, part of the solution because the equation can be written as:

((n+2)! / (n-1)!) / 6

My Answer (spoilers) 

@Pat
Okay lady… I’m puzzled now.

I’ve been trying to figure out how you got to the factorials formula.
Could not be empirically. (Could it?)

So, how did you get there? Please.

Show more

My Answer (spoilers) 

@Pat
Oh, and thank you for answering the “call”. 👍

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.