Polynomial extrapolation
Golfscript, 46 42 40 38 chars
~])\({[{.@-\}*])\}*;]-1%){0\{+.}/p]}*;
This uses a simple difference table approach, which is described in more detail on my GolfScript blog.
Maple, 41 chars
c:=(k,a,m)->interp([$1-k..0],a,x)$x=1..m;
For example, c(3, [1, 2, 4], 4)
returns 7, 11, 16, 22
.
This function interprets the spec literally, taking both k
and a
as separate arguments. If the list a
does not have exactly k
elements, an error occurs. For convenience, here's a 45-char version that omits k
from the argument list:
c:=(a,m)->interp([$1-nops(a)..0],a,x)$x=1..m;
I was first thinking of trying this in Perl, but hell, let's use the right tool for the job.
Jelly, 18 bytes, language postdates challenge
Iß;@Ḣ+\øṁ⁹µL?
çUḣU
Try it online!
Jelly's functions only support up to two arguments, so I don't take in k (which is redundant) as an argument. I hope that's acceptable. The program defines a function 2ŀ
that obeys the specification in the question.
Explanation
Helper function 1ŀ
(takes input λ, ρ, and expands λ by ρ elements):
Iß;@Ḣ+\øṁ⁹µL?
ø µ ? If
L {λ} is nonempty,
then:
I take differences of consecutive elements of {λ};
ß call 1ŀ recursively on this value and {ρ};
;@ prepend
Ḣ the first element of {λ};
+\ and take the cumulative sum {and return it}.
Otherwise:
ṁ⁹ {return} {0} repeated ρ times.
This is fairly magical in the way in which Jelly happens to pick out the exactly values I need it to operate on at every stage. Some of it is the result of me manipulating things; in particular, the unusual choice ø
for the separator (rather than the more usual µ
) means that all implicit arguments are set to 0, which is fairly handy in this case. However, I have no idea why ;@Ḣ
parses the way it does, but it seems to work…
Main function 2ŀ
(takes input λ, ρ, and returns the next ρ elements of λ):
çUḣU
ç Call 1ŀ on {λ} and {ρ};
U reverse it;
ḣ take the first {ρ} elements;
U and reverse it {and return that value}.
This is just massaging the output into the form requested (if we were allowed to return the terms we were already given, that would remove a whole 5 bytes). Jelly doesn't have a "last n elements" function; of the various ways to synthesize it out of other functions, UḣU
is convenient here because it happens to pick up ρ as a default argument.