• + 0 comments

    python3: pure math solution

    def bonetrousle(n, k, b):
        """Find b distinct integers in [0,...,k] that sum to n."""
        
        # Define these convenient variables:
        N = n - b*(b+1)//2
        d = k - b
        
        # For a solution to exist, n must lie between the sum of first b boxes and the last b boxes
        if (N < 0) or (N > b*d):
            return [-1]
        elif N == 0:  # edge case when d==0
            return [*range(1, b+1)]
        else:
            # Imagine starting with first b boxes. While keeping the sum below n, replace b->k, (b-1)->(k-1), .... Each shift adds d to the total. Finally add the missing balance to the "next" (b-i) term. (i.e. the largest value in [1,2,..b] that didn't get shifted.)
            q, r = N//d, N % d
            # Take care of edge case with b-q+r==0 
            mid = [] if (b == q-r) else [b-q+r]
            return [*range(1, b-q)] + mid + [*range(k, k-q, -1)]