Make a one sequence
JavaScript (E6) 79 82
F=(n,t,
d=n+n*~-n/4-t/2,
l=1,
q=[for(x of Array(n))d<n--?++l:(d+=~n,--l)]
)=>d?[]:q
No need of brute force or enumeration of all tuples.
See a sequence of length n as n-1 steps, each step being increment or decrement.
Note, you can only swap an increment for a decrement, sum varies by 2, so for any given length the sum is always even or always odd.
Having all increments, the sequence is 0, 1, 2, 3, ..., n-1 and we know the sum is (n-1)*n/2
Changing the last step, the sum changes by 2, so the last step weighs 2.
Changing the next to last step, the sum changes by 4, so the last step weighs 4. That's because the successive step builds upon the partial sum so far.
Changing the previous step, the sum changes by 6, so the last step weighs 6 (not 8, it's not binary numbers).
...
Changing the first step weighs (n-1)*2
Algorithm
Find the max sum (all increments)
Find the difference with the target sum (if it's not even, no solution)
Seq[0] is 0
For each step
Compare current difference with the step weight
if is less
we have an increment here, seq[i] = seq[i-1]+1
else
we have a decrement here, seq[i] = seq[i-1]-1.
Subtract we current weight from the current diff.
If remaining diff == 0, solution is Seq[]. Else no solution
Ungolfed code
F=(len,target)=>{
max=(len-1)*len/2
delta = max-target
seq = [last=0]
sum = 0
weight=(len-1)*2
while (--len > 0)
{
if (delta >= weight)
{
--last
delta -= weight;
}
else
{
++last
}
sum += last
seq.push(last);
weight -= 2;
}
if (delta) return [];
console.log(sum) // to verify
return seq
}
Test In Firefox / FireBug console
F(8,4)
Output
[0, -1, 0, -1, 0, 1, 2, 3]
CJam, 56 47 44 34 bytes
A lot of scope for improvement here, but here goes the first attempt at this:
L0aa{{[~_(]_)2++}%}l~:N;(*{:+N=}=p
Credits to Dennis for efficient way of doing the { ... }%
part.
Prints the array representation if possible, otherwise ""
Try it online here
GolfScript (41 39 bytes)
[][1,]@~:^;({{.-1=(+.)))+}%}*{{+}*^=}?`
Online demo
Thanks to Dennis for 41->39.