Task

Provide code that produces a list of numbers which is the   nth  order forward difference, given a non-negative integer (specifying the order) and a list of numbers.



The first-order forward difference of a list of numbers   A   is a new list   B,   where   Bn = An+1 - An.

List   B   should have one fewer element as a result.

The second-order forward difference of   A   will be:

tdefmodule Diff do
	def forward(arr,i\\1) do
		forward(arr,[],i)
	end

	def forward([_|[]],diffs,i) do
		if i == 1 do
			IO.inspect diffs
		else 
			forward(diffs,[],i-1)
		end
	end

	def forward([val1|[val2|vals]],diffs,i) do
		forward([val2|vals],diffs++[val2-val1],i) 
	end
end 

The same as the first-order forward difference of   B.

That new list will have two fewer elements than   A   and one less than   B.

The goal of this task is to repeat this process up to the desired order.

For a more formal description, see the related   Mathworld article.



Algorithmic options

 Iterate through all previous forward differences and re-calculate a new array each time.
 Use this formula (from Wikipedia):


 




Δ

n


[
f
]
(
x
)
=

∑

k
=
0


n





(


n
k


)



(
−
1

)

n
−
k


f
(
x
+
k
)


{\displaystyle \Delta ^{n}[f](x)=\sum _{k=0}^{n}{n \choose k}(-1)^{n-k}f(x+k)}




 (Pascal's Triangle   may be useful for this option.)


<?php
 
function forwardDiff($anArray, $times = 1) {
  if ($times <= 0) { return $anArray; }
  for ($accumilation = array(), $i = 1, $j = count($anArray); $i < $j; ++$i) { 
    $accumilation[] = $anArray[$i] - $anArray[$i - 1];
  }
  if ($times === 1) { return $accumilation; }
  return forwardDiff($accumilation, $times - 1);
}
 
class ForwardDiffExample extends PweExample {
 
  function _should_run_empty_array_for_single_elem() {
    $expected = array($this->rand()->int());
    $this->spec(forwardDiff($expected))->shouldEqual(array());
  }
 
  function _should_give_diff_of_two_elem_as_single_elem() {
    $twoNums = array($this->rand()->int(), $this->rand()->int());
    $expected = array($twoNums[1] - $twoNums[0]);
    $this->spec(forwardDiff($twoNums))->shouldEqual($expected);
  }
 
  function _should_compute_correct_forward_diff_for_longer_arrays() {
    $diffInput = array(10, 2, 9, 6, 5);
    $expected  = array(-8, 7, -3, -1);
    $this->spec(forwardDiff($diffInput))->shouldEqual($expected);
  }
 
  function _should_apply_more_than_once_if_specified() {
    $diffInput = array(4, 6, 9, 3, 4);
    $expectedAfter1 = array(2, 3, -6, 1);
    $expectedAfter2 = array(1, -9, 7);
    $this->spec(forwardDiff($diffInput, 1))->shouldEqual($expectedAfter1);
    $this->spec(forwardDiff($diffInput, 2))->shouldEqual($expectedAfter2);
  }
 
  function _should_return_array_unaltered_if_no_times() {
    $this->spec(forwardDiff($expected = array(1,2,3), 0))->shouldEqual($expected);
  }
 
}