How to resolve the algorithm Forward difference step by step in the Erlang programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Forward difference step by step in the Erlang 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 Erlang programming language

Source code in the erlang programming language

-module(forward_difference).
-export([difference/1, difference/2]).

-export([task/0]).
-define(TEST_DATA,[90, 47, 58, 29, 22, 32, 55, 5, 55, 73]).

difference([X|Xs]) ->
    {Result,_} = lists:mapfoldl(fun (N_2,N_1) -> {N_2 - N_1, N_2} end, X, Xs),
    Result.

difference([],_) -> [];
difference(List,0) -> List;
difference(List,Order) -> difference(difference(List),Order-1).

task() ->
    io:format("Initial: ~p~n",[?TEST_DATA]),
    [io:format("~3b: ~p~n",[N,difference(?TEST_DATA,N)]) || N <- lists:seq(0,length(?TEST_DATA))],
    ok.


  

You may also check:How to resolve the algorithm Multiplication tables step by step in the AArch64 Assembly programming language
You may also check:How to resolve the algorithm Singly-linked list/Traversal step by step in the Retro programming language
You may also check:How to resolve the algorithm Sierpinski carpet step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Padovan n-step number sequences step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm O'Halloran numbers step by step in the Wren programming language