So, for example, n=10, k=5, a valid sequence would be:
1, 4, 5, 8, because the difference between any number and the next is either 1 or 3, while the following sequence is invalid:
1, 4, 5, 9, because the difference between any two numbers is any of {1, 3, 4}, which is a set with more than 2 numbers?
Well, then your examples are definitely badly chosen. Why bother with the k = 3 case?
Any combination for k = 3 will have at most 2 different differences, because there are only 2 differences.
For any k > 3, the problem becomes a bit harder.
a) The first number is still free between [1, n-k].
b) The second number is free between [T(1), n-k+1].
c) The third number is free between [T(2), n-k+2].
d) For any number beyond the 3rd, it depends:
d1) If ANY (j, y) exists such that (T(j)-T(j-1) != T(y) - T(y-1)), then T(i) is limited to T(i-1) + (T(j)-T(j-1) OR T(i-1) + (T(y)-T(y-1)).
d2) Else, T(i) is limited between [T(i-1), n-k+i]. |
You'll have to keep track of whether there are 2 different differences already. This isn't too hard; just keep an array of 2 initially set to 0 (error value, as the difference can never be 0). Set the first difference to T(2)-T(1). Each time a number is chosen, see if T(i)-T(i-1) == D[0]. If not, set D1 := T(i) - T(i-1), and from that point on the sequence is strongly limited in options.
The real problem is knowing when to
unset the value D[1]. At some point, the earlier numbers in the sequence will change and at some point, the 2nd (and first, but that one is easy to check) difference will change, making the range completely open again.
So, in summary:
a) Starting from the algorithm in my previous post,
b) Use the recursion until two unique differences are set,
c) Keep track of the differences, as well as the terms that set the difference.
d) Use a slightly adapted version of the algorithm: rather than ]min, max[, you now have {option1, option2}, calculated as T(i-1) + D[0] and T(i-1) + D[1].
e) Make sure that the loop that set the differences will also unset (or change) the difference when its branch has ended.
Not
too difficult, but it'll take some work to get it somewhat clean and readable.