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

Published on 12 May 2024 09:40 PM

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

Source code in the purebasic programming language

Procedure forward_difference(List a())
  If ListSize(a()) <= 1
    ClearList(a()): ProcedureReturn
  EndIf
  Protected NewList b()
  CopyList(a(), b())
  LastElement(a()): DeleteElement(a())
  SelectElement(b(), 1)
  ForEach a()
    a() - b(): NextElement(b())
  Next 
EndProcedure
  
Procedure nth_difference(List a(), List b(), n)
  Protected i
  CopyList(a(), b())
  For i = 1 To n
    forward_difference(b())
  Next 
EndProcedure

Procedure.s display(List a())
  Protected output.s
  ForEach a()
    output + Str(a()) + ","
  Next
  ProcedureReturn RTrim(output,",")
EndProcedure

DataSection
  ;list data
  Data.i 10 ;element count
  Data.i 90, 47, 58, 29, 22, 32, 55, 5, 55, 73
EndDataSection

;create and fill list
Define i
NewList a()
Read.i i
While i > 0
  AddElement(a()): Read.i a(): i - 1
Wend

If OpenConsole()
  NewList b()
  For i = 1 To 10
    nth_difference(a(), b(), i)
    PrintN(Str(i) + "   [" + display(b()) + "]")
  Next
  
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf

  

You may also check:How to resolve the algorithm Color wheel step by step in the Fōrmulæ programming language
You may also check:How to resolve the algorithm Pragmatic directives step by step in the Perl programming language
You may also check:How to resolve the algorithm Roman numerals/Decode step by step in the FALSE programming language
You may also check:How to resolve the algorithm Range consolidation step by step in the Prolog programming language
You may also check:How to resolve the algorithm Unicode variable names step by step in the VBA programming language