How to resolve the algorithm Forward difference step by step in the jq programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Forward difference step by step in the jq programming language
Table of Contents
Problem Statement
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: 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.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Forward difference step by step in the jq programming language
Source code in the jq programming language
# If n is a non-negative number and if input is
# a (possibly empty) array of numbers,
# emit an array, even if the input list is too short:
def ndiff(n):
if n==0 then .
elif n == 1 then . as $in | [range(1;length) | $in[.] - $in[.-1]]
else ndiff(1) | ndiff(n-1)
end;
def s: [90, 47, 58, 29, 22, 32, 55, 5, 55, 73];
range(0;12) as $i | (s|ndiff($i))
$ jq -c -n -f forward-difference.jq
[90,47,58,29,22,32,55,5,55,73]
[-43,11,-29,-7,10,23,-50,50,18]
[54,-40,22,17,13,-73,100,-32]
[-94,62,-5,-4,-86,173,-132]
[156,-67,1,-82,259,-305]
[-223,68,-83,341,-564]
[291,-151,424,-905]
[-442,575,-1329]
[1017,-1904]
[-2921]
[]
[]
You may also check:How to resolve the algorithm Comma quibbling step by step in the RPL programming language
You may also check:How to resolve the algorithm Strip control codes and extended characters from a string step by step in the Run BASIC programming language
You may also check:How to resolve the algorithm Reverse a string step by step in the Retro programming language
You may also check:How to resolve the algorithm Averages/Mode step by step in the BBC BASIC programming language
You may also check:How to resolve the algorithm Sorting algorithms/Quicksort step by step in the True BASIC programming language