Winnable Solitaire Mancala Boards
Python, 42 41 bytes
m=lambda n,i=2:n*[1]and[n%i]+m(n-n%i,i+1)
CJam (21 bytes)
M{_0+0#_Wa*\)+.+}ri*`
Online demo
Explanation
I independently derived the "unplaying" technique mentioned in this paper. We prove by induction that there is exactly one winning board for a given number of beads.
Base case: with 0 beads, the only winning board is the empty one.
Inductive step: if we sow from cup k
then at the next move cup k
will be empty and every cup nearer the basket will contain at least one bead. Therefore we can find the unique winning board with n
beads from the winning board with n-1
beads by looking for the lowest numbered empty cup, taking one bead from the basket and one from each cup below that empty cup, and placing them all in the empty cup.
Dissection
M e# Start with an empty board
{ e# Loop
_0+0# e# Find position of first 0 (appending to ensure that there is one)
_Wa* e# Make array of that many [-1]s
\)+ e# Append the index plus 1 (since board is 1-indexed)
.+ e# Pointwise addition
}
ri* e# Read integer from stdin and execute loop that many times
` e# Format for display
JavaScript (ES6), 63 37 bytes
f=(n,d=2)=>n?[n%d,...f(n-n%d,d+1)]:[]
Port of @orlp's Python answer. Explanation: Consider the total number of beads in the i
th and higher cups. Each play from one of these cups will remove i
beads from that total. (For instance, if i
is 3, and you play from the fifth cup, you reduce the number of beads in that cup by five, but you also add one to both the fourth and the third cups.) The total must therefore be a multiple of i
. Now the i-1
th cup cannot contain i
or more beads, so in order for it to leave a multiple of i
it must contain the remainder of the beads modulo i
.
Previous explanation (from @xnor's link): The naive approach is the "reverse playing" technique. This uses the observation that making a play empties a cup, so reverse playing collects a bead from each cup and puts them in the first empty cup, like so (63 bytes):
f=n=>n?[...a=f(n-1),0].some((m,i)=>(m?a[i]--:a[i]=i+1)>m)&&a:[]
Now, just consider the first i
cups. In the case that one of them is empty, reverse playing will add 1
to the total number of beads in those cups, while in the case that none of them is empty, reverse playing will subtract i
from the total, however this is equivalent to adding 1
modulo i+1
. After n
reverse plays the sum of the beads in the first i
cups will therefore be equivalent to n
modulo i+1
, or put it another way, the number of beads in the i
th cup will be equivalent to n
minus the sum of the beads in the preceding cups, modulo i+1
. Now for the i
th cup to be playable the number of beads cannot exceed i
, so in fact it will equal the number of remaining beads modulo i+1
. (Note that I use d=i+1
as it uses fewer bytes.)