A magic sequence is a sequence of non-negative integers to such that there are exactly instances of , for all .
is a magic sequence of length since there are 2 0's, 0 1’s, 2 2’s and 0 3’s.
How many magic sequences of length 2015 exist?
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
This is a very popular constraint programming problem.
However, I like the following theorem from xnor on codegolf ):
This uses the fact, which I'll prove, that the only Magic sequences of length
n
are:[1, 2, 1, 0]
and[2, 0, 2, 0]
forn=4
[2, 1, 2, 0, 0]
forn=5
[n-4, 2, 1, 0, 0, ..., 0, 0, 1, 0, 0, 0]
forn>=7
So, for
n>=7
, one only needs to return a huge tuple. I can do this for up to roughlyn=10^8
on my laptop, which is likely limited by memory; any more and it freezes up. (Thanks to trichoplax for the idea of using tuples rather than lists.) Or, if one can instead print a dictionary of nonzero entries,{0:n-4, 1:2, 3:1, (n-4):1}
, one can do this for ginormousn
.I prove the uniqueness for
n>=7
; the other ones can be checked by brute force or casework.The sum of the entries of
l
is the total count of all numbers of the list, which is its lengthn
. The list hasl[0]
zeroes, and son-l[0]
nonzero entries. But by definitionl[0]
must be nonzero or we get a contradiction, and each of the other nonzero entries is at least 1. This already accounts for a sum ofl[0] + (n-l[0]-1)*1 = n-1
out of the overall sum ofn
. So not countingl[0]
, there can be at most one 2 and no entry bigger than 2.But that means the only nonzero entries are
l[0], l[1], l[2], and l[l[0]]
, whose values are at mostl[0]
and a permutation of1,1,2
, which gives a maximum sum ofl[0]+4
. Since this sum isn
, which is at least 7, we havel[0]>=3
, and sol[l[0]]=1
. Now, there's at least one1
, which meansl[1]>=1
, but ifl[1]==1
that's another1
, sol[1]>=2
, which impliesl[1]
is the lone2
. This givesl[2]=1
, and all the remaining entries are0
, sol[0]=n-4
, which completes the solution.