I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

# Maximum difference between adjacent elements of list

Maximum difference between adjacent elements of list is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Find maximum difference between adjacent elements of list.

The list may have negative values, zero values, real numbers.

List   =   [1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3]

Output would be   (which could have more verbiage):

```  1,8 ==> 7
2,9 ==> 7
10,3 ==> 7
```

## 11l

Translation of: Python
`F maxDeltas(ns)   V pairs = zip(ns, ns[1..]).map((a, b) -> (abs(a - b), (a, b)))   V delta = max(pairs, key' ab -> ab[0])[0]   R pairs.filter(ab -> @delta == ab[0]) V maxPairs = maxDeltas([Float(1), 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3]) L(ab) maxPairs   print(ab)`
Output:
```(7, (1, 8))
(7, (2, 9))
(7, (10, 3))
```

## Action!

`INCLUDE "H6:REALMATH.ACT" DEFINE PTR="CARD" PTR FUNC GetPtr(BYTE ARRAY a INT index)RETURN (a+index*6) PROC MaxDifference(BYTE ARRAY a INT len REAL POINTER maxDiff)  INT i  REAL diff  REAL POINTER r1,r2   IntToReal(0,maxDiff)  FOR i=0 TO len-2  DO    r1=GetPtr(a,i)    r2=GetPtr(a,i+1)    RealAbsDiff(r1,r2,diff)    IF RealGreaterOrEqual(diff,maxDiff) THEN      RealAssign(diff,maxDiff)    FI  ODRETURN PROC PrintPairs(BYTE ARRAY a INT len,maxDiff)  INT i  REAL diff  REAL POINTER r1,r2   FOR i=0 TO len-2  DO    r1=GetPtr(a,i)    r2=GetPtr(a,i+1)    RealAbsDiff(r1,r2,diff)    IF RealEqual(diff,maxDiff) THEN      Print("  AbsDiff(") PrintR(r1)      Print(", ") PrintR(r2)      Print(") = ") PrintRE(maxDiff)    FI  ODRETURN PROC Decode(CHAR ARRAY s BYTE ARRAY a INT POINTER len)  BYTE i,start,length  CHAR ARRAY item,tmp(10)  REAL POINTER r   len^=0 i=1  WHILE i<=s(0)  DO    start=i    WHILE i<=s(0) AND s(i)#32    DO      i==+1    OD    length=i-start    SCopyS(tmp,s,start,i-1)    r=GetPtr(a,len^)    ValR(tmp,r)    len^==+1    i==+1  ODRETURN PROC Test(CHAR ARRAY s)  BYTE ARRAY a(200)  INT len  REAL maxDiff   PrintF("Max difference in [%S] is ",s)  Decode(s,a,@len)  MaxDifference(a,len,maxDiff)  PrintRE(maxDiff)  PrintPairs(a,len,maxDiff) PutE()RETURN PROC Main()  Put(125) PutE() ;clear the screen   Test("1 8 2 -3 0 1 1 -2.3 0 5.5 8 6 2 9 11 10 3")  Test("0.12 -0.04 0.34 0.72 0.34 0.27 -0.1")  Test("10E30 20E30 15E30 5E30 -5E30")RETURN`
Output:
```Max difference in [1 8 2 -3 0 1 1 -2.3 0 5.5 8 6 2 9 11 10 3] is 7
AbsDiff(1, 8) = 7
AbsDiff(2, 9) = 7
AbsDiff(10, 3) = 7

Max difference in [0.12 -0.04 0.34 0.72 0.34 0.27 -0.1] is .38
AbsDiff(-0.04, .34) = .38
AbsDiff(.34, .72) = .38
AbsDiff(.72, .34) = .38

Max difference in [10E30 20E30 15E30 5E30 -5E30] is 1.0E+31
AbsDiff(1.0E+31, 2.0E+31) = 1.0E+31
AbsDiff(1.5E+31, 5E+30) = 1.0E+31
AbsDiff(5E+30, -5E+30) = 1.0E+31
```

## ALGOL 68

`BEGIN # find the maximum difference between consecutive list elements         #    # returns the maximum difference between pairs of elements of list        #    OP   MAXDELTA = ( []REAL list )REAL:         BEGIN            REAL max diff := 0;            FOR i FROM LWB list TO UPB list - 1 DO                REAL delta = ABS ( list[ i ] - list[ i + 1 ] );                IF delta > max diff THEN                    max diff := delta # found a higher difference             #                FI            OD;            max diff         END; # MAXDELTA #    # returns r converted to a string with trailing 0 decimal places removed  #    OP   TOSTRING = ( REAL r )STRING:         BEGIN            STRING result  := fixed( r, 0, 10 );            IF result[ LWB result ] = "." THEN result := "0" + result FI;            INT    r end   := UPB result;            INT    r start := LWB result;            WHILE IF r end <= r start THEN FALSE ELSE result[ r end ] = "0" FI DO               r end -:= 1            OD;            IF r end > LWB result THEN                # if all decimal places were "0", remove the "." as well      #                IF result[ r end ] = "." THEN r end -:= 1 FI            FI;            result[ r start : r end ]         END; # TOSTRING #    # test the MAXDELTA operator                                              #    PROC test max delta = ( []REAL list )VOID:         BEGIN            REAL max diff = MAXDELTA list;            print( ( "Max difference [" ) );            FOR i FROM LWB list TO UPB list DO                print( ( " ", TOSTRING list[ i ] ) )            OD;            print( ( " ] is ", TOSTRING max diff, ":",  newline ) );            FOR i FROM LWB list TO UPB list - 1 DO                IF REAL diff = ABS ( list[ i ] - list[ i + 1 ] );                   diff = max diff                THEN                    print( ( "    ", TOSTRING list[ i ], ", ", TOSTRING list[ i + 1 ]                           , " ==> ", TOSTRING diff                           , newline                           )                         )                FI            OD         END; # test max delta #    # task test case                                                          #    test max delta( ( 1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3 ) );    # additional test cases                                                   #    test max delta( ( -1.1, -1.2 ) ); test max delta( ( pi, pi, pi ) );    test max delta( ( )            ); test max delta( ( 776.591 )    )END`
Output:
```Max difference [ 1 8 2 -3 0 1 1 -2.3 0 5.5 8 6 2 9 11 10 3 ] is 7:
1, 8 ==> 7
2, 9 ==> 7
10, 3 ==> 7
Max difference [ -1.1 -1.2 ] is 0.1:
-1.1, -1.2 ==> 0.1
Max difference [ 3.1415926536 3.1415926536 3.1415926536 ] is 0:
3.1415926536, 3.1415926536 ==> 0
3.1415926536, 3.1415926536 ==> 0
Max difference [ ] is 0:
Max difference [ 776.591 ] is 0:
```

## ALGOL W

`begin % find the maximum difference between consecutive list elements         %    % returns the maximum difference between pairs of elements of list        %    %         the lower and upper bounds of list must be specified in lb & ub %    real procedure maxDelta ( real    array list ( * )                            ; integer value lb, ub                            ) ;    begin        real maxDiff;        maxDiff := 0;        for i := lb until ub - 1 do begin            real delta;            delta := abs ( list( i ) - list( i + 1 ) );            if delta > maxDiff then maxDiff := delta % found a higher difference %        end for_i;        maxDiff    end maxDelta;    % test the maxDelta procedure                                             %    procedure testMaxDelta ( real    array list ( * )                           ; integer value lb, ub, rw, dp                           ) ;    begin        real maxDiff;        maxDiff := maxDelta( list, lb, ub );        write( s_w := 0, "Max difference [" );        for i := lb until ub do begin            writeon( r_format := "A", r_w := rw, r_d := dp, s_w := 0, " ", list( i ) );        end for_i;        writeon( r_format := "A", r_w := rw, r_d := dp, s_w := 0, " ] is ", maxDiff, ":" );        for i := lb until ub - 1 do begin            real diff;            diff := abs ( list( i ) - list( i + 1 ) );            if diff = maxDiff then begin                write( r_format := "A", r_w := rw, r_d := dp, s_w := 0, "    ", list( i ), ", ", list( i + 1 ), " ==> ", diff );            end if_diff_eq_maxDiff         end for_i    end testMaxDelta;    begin % task test case                                                    %        integer tPos;        real array tc( 1 :: 17 );        tPos := 0;        for i := 1, 8, 2, -3, 0, 1, 1, -23, 0, 55, 8, 6, 2, 9, 11, 10, 3 do begin            tPos       := tPos + 1;            tc( tPos ) := i        end for_i;        tc( 8 ) := -2.3; tc( 10 ) := 5.5;        testMaxDelta( tc, 1, 17, 4, 1 )    end;    begin % additional test cases                                             %        integer tPos;        real array tc( 1 :: 3 );        tc( 1 ) := -1.1; tc( 2 ) := -1.2; testMaxDelta( tc, 1, 2, 4, 1  );        for i := 1 until 3 do tc( i ) := pi;        testMaxDelta( tc, 1, 3, 6, 4 );        testMaxDelta( tc, 1, 0, 3, 1 );        tc( 1 ) := 776.591;        testMaxDelta( tc, 1, 1, 6, 3 )    endend.`
Output:
```Max difference [  1.0  8.0  2.0 -3.0  0.0  1.0  1.0 -2.3  0.0  5.5  8.0  6.0  2.0  9.0 11.0 10.0  3.0 ] is  7.0:
1.0,  8.0 ==>  7.0
2.0,  9.0 ==>  7.0
10.0,  3.0 ==>  7.0
Max difference [ -1.1 -1.2 ] is  0.1:
-1.1, -1.2 ==>  0.1
Max difference [ 3.1416 3.1416 3.1416 ] is 0.0000:
3.1416, 3.1416 ==> 0.0000
3.1416, 3.1416 ==> 0.0000
Max difference [ ] is 0.0:
Max difference [ 776.591 ] is  0.000:
```

## APL

Works with: Dyalog APL
`maxdiff ← (⊢((⌈/⊢),⊣(⌿⍨)⊢=(⌈/⊢))(|-)/)∘(↑2,/⊢)`
Output:
```      maxdiff 1 8 2 ¯3 0 1 1 ¯2.3 0 5.5 8 6 2 9 11 10 3
7  1 8
7  2 9
7 10 3```

## AutoHotkey

`List := [1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3]mxDiff := [] loop % List.Count() -1    mxDiff[d := Abs(list[A_Index+1] - list[A_Index])] .= list[A_Index] ", " list[A_Index+1] " ==> " d "`n" MsgBox % result := Trim(mxDiff[mxDiff.MaxIndex()], "`n")`
Output:
```1, 8 ==> 7
2, 9 ==> 7
10, 3 ==> 7```

## AWK

` # syntax: GAWK -f MAXIMUM_DIFFERENCE_BETWEEN_ADJACENT_ELEMENTS_OF_LIST.AWKBEGIN {    list = "1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3"    n = split(list,arr,",")    for (i=1; i<n; i++) {      a = arr[i]      b = arr[i+1]      if (abs(a-b) == highest) {        sets = sprintf("%s%s,%s  ",sets,a,b)      }      else if (abs(a-b) > highest) {        highest = abs(a-b)        sets = sprintf("%s,%s  ",a,b)      }    }    printf("%s: %s\n",highest,sets)    exit(0)}function abs(x) { if (x >= 0) { return x } else { return -x } } `
Output:
```7: 1,8  2,9  10,3
```

## BASIC

### QBasic

Works with: QBasic version 1.1
Works with: QuickBasic version 4.5
`maxdist = 0DIM lista(0 TO 16)FOR i = 0 TO UBOUND(lista)    READ lista(i)NEXT i PRINT "Maximum difference between adjacent elements of lista is:"FOR i = 0 TO UBOUND(lista) - 1    dist = ABS(lista(i) - lista(i + 1))    IF dist > maxdist THEN maxdist = distNEXT i FOR i = 0 TO UBOUND(lista) - 1    dist = ABS(lista(i) - lista(i + 1))    IF dist = maxdist THEN PRINT lista(i); ", "; lista(i + 1); " ==> "; maxdistNEXT i DATA 1., 8., 2., -3., 0., 1., 1., -2.3, 0., 5.5, 8., 6., 2., 9., 11., 10., 3.`
Output:
`Same as FreeBASIC entry.`

### BASIC256

`arraybase 1maxdist = 0dim lista = {1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3} print "Maximum difference between adjacent elements of lista is:"for i = 1 to lista[?]-1	dist = abs(lista[i] - lista[i+1])	if dist > maxdist then maxdist = distnext i for i = 1 to  lista[?]-1	dist = abs(lista[i] - lista[i+1])	if dist = maxdist then print lista[i] & ", " & lista[i+1] & " ==> " & maxdistnext i`
Output:
`Same as FreeBASIC entry.`

### True BASIC

`LET maxdist = 0DIM lista(0 TO 16)FOR i = 0 TO UBOUND(lista)    READ lista(i)NEXT iPRINT "Maximum difference between adjacent elements of lista is:"FOR i = 0 TO UBOUND(lista)-1    LET dist = ABS(lista(i)-lista(i+1))    IF dist > maxdist THEN LET maxdist = distNEXT iFOR i = 0 TO UBOUND(lista)-1    LET dist = ABS(lista(i)-lista(i+1))    IF dist = maxdist THEN PRINT lista(i); ", "; lista(i+1); " ==> "; maxdistNEXT iDATA 1., 8., 2., -3., 0., 1., 1., -2.3, 0., 5.5, 8., 6., 2., 9., 11., 10., 3.END`
Output:
`Same as FreeBASIC entry.`

### Yabasic

`maxdist = 0dim lista(16)lista(0) =  1  : lista(1)  = 8lista(2) =  2  : lista(3)  = -3lista(4) =  0  : lista(5)  = 1lista(6) =  1  : lista(7)  = -2.3lista(8) =  0  : lista(9)  = 5.5lista(10) = 8  : lista(11) = 6lista(12) = 2  : lista(13) = 9lista(14) = 11 : lista(15) = 10lista(16) = 3 print "Maximum difference between adjacent elements of lista is:"for i = 0 to arraysize(lista(),1)-1    dist = abs(lista(i) - lista(i+1))    if dist > maxdist  maxdist = distnext i for i = 0 to arraysize(lista(),1)-1    dist = abs(lista(i) - lista(i+1))    if dist = maxdist  print lista(i), ", ", lista(i+1), " ==> ", maxdistnext i`
Output:
`Same as FreeBASIC entry.`

## F#

` // Max diff 'twix adj elems. Nigel Galloway: July 18th., 2021let n,g=[1;8;2;-3;0;1;1;-2;3;0;5;5;8;6;2;9;11;10;3]|>List.pairwise|>List.groupBy(fun(n,g)->abs(n-g))|>List.maxBy fst in printfn "Pairs %A have the max diff of %d" g n `
Output:
```Pairs [(1, 8); (2, 9); (10, 3)] have the max diff of 7
```

## Factor

Works with: Factor version 0.99 2021-06-02
`USING: assocs grouping math prettyprint sequences ; : max-diff ( seq -- assoc )    2 clump [ first2 - abs ] collect-by >alist supremum ; { 1 8 2 -3 0 1 1 -2.3 0 5.5 8 6 2 9 11 10 3 } max-diff .`
Output:
```{ 7 V{ { 1 8 } { 2 9 } { 10 3 } } }
```

## Free Pascal

Translation of: Pascal
` program maximumDifferenceBetweenAdjacentElementsOfList(output);type  tmyReal = extended;  tmyList = array of tmyReal;const  input: tmyList = (1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3);  procedure  OutSameDistanceInList(Dist:tmyReal;const list: tmyList);  var    currentDistance : tmyReal;    i : integer;  begin    for i := 0 to High(List) - 1 do    begin      currentDistance := abs(list[i] - list[succ(i)]);      if currentDistance = dist then         writeln('idx : ',i:4,' values ',list[i],' ',list[i+1]);    end;    writeln;  end;   function internalDistance(const list: tmyList): tmyReal;  var    i: integer;    maximumDistance, currentDistance: tmyReal;  begin    maximumDistance := 0.0;    for i := 0 to High(List) - 1 do    begin      currentDistance := abs(list[i] - list[succ(i)]);      if currentDistance > maximumDistance then      begin        maximumDistance := currentDistance;      end;    end;    internalDistance := maximumDistance;  end; var  list: tmyList;  foundDistance : tmyReal;begin  list := input;  if length(list) > 0 then  Begin    foundDistance := internalDistance(list);    OutSameDistanceInList(foundDistance,list);  end;  {\$IFDEF WINDOWS}  readln;  {\$ENDIF}end.`
Output:
```idx :    0 values  1.0000000000000000E+000  8.0000000000000000E+000
idx :   12 values  2.0000000000000000E+000  9.0000000000000000E+000
idx :   15 values  1.0000000000000000E+001  3.0000000000000000E+000 ```

## FreeBASIC

`Dim As Single Dist, MaxDist = 0Dim As Single List(16) => {1., 8., 2., -3., 0., 1., 1., -2.3, 0., 5.5, 8., 6., 2., 9., 11., 10., 3.} Print !"Maximum difference between adjacent elements of list is:"For i As Integer = 0 To Ubound(List)    Dist = Abs(List(i) - List(i+1))    If Dist > MaxDist Then MaxDist = DistNext i For i As Integer = 0 To Ubound(List)    Dist = Abs(List(i) - List(i+1))    If Dist = MaxDist Then Print List(i) & ", " & List(i+1) & " ==> " & MaxDistNext i`
Output:
```Maximum difference between adjacent elements of lista is:
1, 8 ==> 7
2, 9 ==> 7
10, 3 ==> 7```

## Go

`package main import (    "fmt"    "math") func main() {    list := []float64{1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3}    maxDiff := -1.0    var maxPairs [][2]float64    for i := 1; i < len(list); i++ {        diff := math.Abs(list[i-1] - list[i])        if diff > maxDiff {            maxDiff = diff            maxPairs = [][2]float64{{list[i-1], list[i]}}        } else if diff == maxDiff {            maxPairs = append(maxPairs, [2]float64{list[i-1], list[i]})        }    }    fmt.Println("The maximum difference between adjacent pairs of the list is:", maxDiff)    fmt.Println("The pairs with this difference are:", maxPairs)}`
Output:
```The maximum difference between adjacent pairs of the list is: 7
The pairs with this difference are: [[1 8] [2 9] [10 3]]
```

`import Data.List (maximumBy)import Data.Ord (comparing) maxDeltas :: (Num a, Ord a) => [a] -> [(a, (a, a))]maxDeltas xs = filter ((delta ==) . fst) pairs  where    pairs =      zipWith        (\a b -> (abs (a - b), (a, b)))        xs        (tail xs)    delta = fst \$ maximumBy (comparing fst) pairs main :: IO ()main =  mapM_ print \$    maxDeltas [1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3]`
Output:
```(7.0,(1.0,8.0))
(7.0,(2.0,9.0))
(7.0,(10.0,3.0))```

## J

`maxdiff =: ([(([:>./]),.[#~]=[:>./])[:|@-/"1])@(2:,/\])`
Output:
```   maxdiff 1 8 2 _3 0 1 1 _2.3 0 5.5 8 6 2 9 11 10 3
7  1 8
7  2 9
7 10 3```

## jq

Works with: jq

Works with gojq, the Go implementation of jq

`def maximally_different_adjacent_pairs:  . as \$in  | reduce range(1; length) as \$i ({ maxDiff: -1};      ((\$in[\$i-1] - \$in[\$i])|length) as \$diff  # length being abs      | if \$diff > .maxDiff        then .maxDiff = \$diff        | .maxPairs = [[\$in[\$i-1], \$in[\$i]]]        elif \$diff == .maxDiff        then .maxPairs += [[\$in[\$i-1], \$in[\$i]]]	else .	end      ); # Example:[1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8,6, 2, 9, 11, 10, 3]| maximally_different_adjacent_pairs `
Output:
```{"maxDiff":7,"maxPairs":[[1,8],[2,9],[10,3]]}
```

## Julia

` function maxadjacentdiffs(list)    pairs, maxδ = Pair{eltype(list)}[], abs(zero(eltype(list)))    for i in eachindex(list[begin:end-1])        x, y = list[i], list[i + 1]        if (δ = abs(x - y)) == maxδ            push!(pairs, x => y)        elseif δ > maxδ            maxδ, pairs = δ, [x => y]        end    end    return maxδ, pairsend diff, pairs = maxadjacentdiffs([1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3]) foreach(p -> println(p[1], ", ", p[2], " ==> ", diff), pairs) `
Output:
```1.0, 8.0 ==> 7.0
2.0, 9.0 ==> 7.0
10.0, 3.0 ==> 7.0
```

## Mathematica/Wolfram Language

`l = {1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3};diff = [email protected][l];m = Max[diff];pos = Flatten[Position[diff, m]];Column[Part[l, # ;; # + 1] -> m & /@ pos]`
Output:
```{1,8}->7
{2,9}->7
{10,3}->7```

## Nim

`import strformat, strutils type Pair = (float, float) func `\$`(p: Pair): string = &"({p[0]:g}, {p[1]:g})" func maxdiff(list: openArray[float]): tuple[diff: float; list: seq[Pair]] =  assert list.len >= 2  result = (diff: -1.0, list: @[])  var prev = list[0]  for n in list[1..^1]:    let d = abs(n - prev)    if d > result.diff:      result.diff = d      result.list = @[(prev, n)]    elif d == result.diff:      result.list.add (prev, n)    prev = n let list = [float 1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3]let (diff, pairs) = list.maxdiff() echo &"The maximum difference between adjacent pairs of the list is: {diff:g}"echo "The pairs with this difference are: ", pairs.join(" ")`
Output:
```The maximum difference between adjacent pairs of the list is: 7
The pairs with this difference are: (1, 8) (2, 9) (10, 3)```

## Pascal

The following program needs an ISO 7185 Standard “unextended” Pascal, level 1, compliant compiler.

`program maximumDifferenceBetweenAdjacentElementsOfList(output); function internalDistance(		list: array[indexMinimum..indexMaximum: integer] of real	): real;var	i: integer;	maximumDistance, currentDistance: real;begin	maximumDistance := 0.0; 	for i := indexMinimum to pred(indexMaximum) do	begin		currentDistance := abs(list[i] - list[succ(i)]); 		if currentDistance > maximumDistance then		begin			maximumDistance := currentDistance		end	end; 	internalDistance := maximumDistanceend; var	list: array[1..2] of real;begin	list[1] := 1.0; list[2] := 8.0;	writeLn(internalDistance(list));end.`

## Perl

`#!/usr/bin/perl use strict;use warnings;use List::Util qw( reduce max ); my @list = (1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3); my %diffs;reduce { \$diffs{ abs \$a - \$b } .= " \$a,\$b"; \$b } @list;my \$max = max keys %diffs;print "\$_ ==> \$max\n" for split ' ', \$diffs{ \$max };`
Output:
```1,8 ==> 7
2,9 ==> 7
10,3 ==> 7
```

## Phix

```procedure differences(sequence s)
sequence d, mx = {0,""}, mn = mx
atom av = 0
function fall(integer fn, sequence d, s)
atom m = fn(d)
sequence p = find_all(m,d)
for i=1 to length(p) do
integer pi = p[i], pj = pi+1
p[i] = sprintf("s[%d..%d]=%V",{pi,pj,s[pi..pj]})
end for
return {m,", occurring at "&join(p,", ")}
end function
if length(s)>=2 then
d = sq_abs(sq_sub(s[1..-2],s[2..-1]))
mx = fall(maxsq, d, s)
mn = fall(minsq, d, s)
av = sum(d)/length(d)
end if
printf(1,"sequence: %V\n",{s})
printf(1,"max difference is %g%s\n",mx)
printf(1,"min difference is %g%s\n",mn)
printf(1,"avg difference is %.7g\n\n",av)
end procedure
differences({1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3})
differences({-1.1,-1.2})
differences({})
differences({776.591})
```
Output:
```sequence: {1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3}
max difference is 7, occurring at s[1..2]={1,8}, s[13..14]={2,9}, s[16..17]={10,3}
min difference is 0, occurring at s[6..7]={1,1}
avg difference is 3.6625

sequence: {-1.1,-1.2}
max difference is 0.1, occurring at s[1..2]={-1.1,-1.2}
min difference is 0.1, occurring at s[1..2]={-1.1,-1.2}
avg difference is 0.1

sequence: {}
max difference is 0
min difference is 0
avg difference is 0

sequence: {776.591}
max difference is 0
min difference is 0
avg difference is 0
```

## Picat

`import util. main =>  L = [1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3],  Diffs = findall([Diff,A,B], (nextto(A,B,L), Diff = abs(A-B))),  MaxDiff = max([Diff : [Diff,_,_] in Diffs]),  println(MaxDiff=[[A,B] : [Diff,A,B] in Diffs, Diff == MaxDiff]),  nl.`
Output:
`7 = [[1,8],[2,9],[10,3]]`

Here is an alternative way to get the pairwise differences, using `zip/2`:

`  % ...  Diffs = [[abs(A-B),A,B] : {A,B} in zip(L.butlast,L.tail)],  % ... % Returns all element of L but the lastbutlast(L) = L[1..L.len-1].`

## Python

`'''Maximum difference between adjacent numbers in list'''  # maxDeltas [Float] -> [(Float, (Float, Float))]def maxDeltas(ns):    '''Each of the maximally differing successive pairs       in ns, each preceded by the value of the difference.    '''    pairs = [        (abs(a - b), (a, b)) for a, b        in zip(ns, ns[1:])    ]    delta = max(pairs, key=lambda ab: ab[0])[0]     return [        ab for ab in pairs        if delta == ab[0]    ]  # ------------------------- TEST -------------------------# main :: IO ()def main():    '''Each of the maximally differing pairs in a list'''     maxPairs = maxDeltas([        1, 8, 2, -3, 0, 1, 1, -2.3, 0,        5.5, 8, 6, 2, 9, 11, 10, 3    ])     for ab in maxPairs:        print(ab)  # MAIN ---if __name__ == '__main__':    main()`
Output:
```(7, (1, 8))
(7, (2, 9))
(7, (10, 3))```

## Raku

`sub max-diff (*@list) {   return 0 if +@list < 2;   my \$max = @list.rotor(2 => -1).max({ (.[0] - .[1]).abs }).map( (* - *).abs )[0];   "\$max @ elements { @list.rotor(2 => -1).grep( { (.[0] - .[1]).abs == \$max } ).gist }"}  sub min-diff (*@list) {   return 0 if +@list < 2;   my \$min = @list.rotor(2 => -1).min({ (.[0] - .[1]).abs }).map( (* - *).abs )[0];   "\$min @ elements { @list.rotor(2 => -1).grep( { (.[0] - .[1]).abs == \$min } ).gist }"}  sub avg-diff (*@list) { (+@list > 1) ?? (@list.sum / +@list) !! 0 }  # TESTING for (      [ 1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3 ]     ,[(rand × 1e6) xx 6]     ,[ e, i, τ, π, ∞ ]     ,[ 1.9+3.7i, 2.07-13.2i, 0.2+-2.2i, 4.6+0i ]     ,[ 6 ]     ,[]     ,[<One Two Three>]    )-> @list {    say 'List: ', ~ @list.raku;    for ('  Maximum', &max-diff ,'  Minimum', &min-diff, '  Average', &avg-diff)    -> \$which, &sub {        say "\$which distance between list elements: " ~ &sub(@list);    }    say '';}`
Output:
```List: [1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3]
Maximum distance between list elements: 7 @ elements ((1 8) (2 9) (10 3))
Minimum distance between list elements: 0 @ elements ((1 1))
Average distance between list elements: 3.658824

List: [480470.3324944039e0, 719954.3173377671e0, 648221.5674277907e0, 340053.78585537826e0, 540629.6741075241e0, 4336.700602958543e0]
Maximum distance between list elements: 536292.9735045655 @ elements ((540629.6741075241 4336.700602958543))
Minimum distance between list elements: 71732.74990997638 @ elements ((719954.3173377671 648221.5674277907))
Average distance between list elements: 455611.06297097047

List: [2.718281828459045e0, <0+1i>, 6.283185307179586e0, 3.141592653589793e0, Inf]
Maximum distance between list elements: Inf @ elements ((3.141592653589793 Inf))
Minimum distance between list elements: 2.896386731590008 @ elements ((2.718281828459045 0+1i))
Average distance between list elements: Inf+0.2i

List: [<1.9+3.7i>, <2.07-13.2i>, <0.2-2.2i>, <4.6+0i>]
Maximum distance between list elements: 16.900855007957436 @ elements ((1.9+3.7i 2.07-13.2i))
Minimum distance between list elements: 4.919349550499537 @ elements ((0.2-2.2i 4.6+0i))
Average distance between list elements: 2.1925-2.925i

List: [6]
Maximum distance between list elements: 0
Minimum distance between list elements: 0
Average distance between list elements: 0

List: []
Maximum distance between list elements: 0
Minimum distance between list elements: 0
Average distance between list elements: 0

List: ["One", "Two", "Three"]
Cannot convert string to number: base-10 number must begin with valid digits or '.' in '⏏Two' (indicated by ⏏)
in sub max-diff at listdiff.p6 line 3
in block  at listdiff.p6 line 33
in block <unit> at listdiff.p6 line 20
```

## REXX

Some basic error checking was made   (non─numeric element,   not enough elements).

This REXX version was optimized to handle very large lists.

`/*REXX program finds/displays the maximum difference between adjacent elements of a list*/parse arg \$                                      /*obtain optional arguments from the CL*/if \$='' | S==","  then \$= ,                      /*Not specified?  Then use the default.*/     '1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3' /*commas are optional;  blanks are OK. */w= 0                                             /*the maximum width of any element num.*/\$= translate(\$, , ',')                           /*elide optional commas between numbers*/#= words(\$)                                      /*number of elements in the  \$  list.  */             do i=1  for words(\$); x= word(\$, i) /*examine each element, ensure a number*/             @.i= x;     w= max(w, length(x) )   /*assign element #; find maximum width.*/             if datatype(x, 'N')  then iterate   /*Is it numeric?   Yes, then continue. */             say '***error***  element #'i    " isn't numeric: "    x             exit 13             end   /*i*/n= 0                                             /*N:   # sets of (difference) elements.*/if #<2  then do;   say '***error***  not enough elements were specified,  minimum is two.'                   exit 13             endsay '   list  of elements: '    space(\$)         /*show the  list  of  numbers  in list.*/say '  number of elements: '    #                /*show  "  number  "  elements  "   "  */d= -1;                                           /*d:  maximum difference found (so far)*/        do j=1  for #-1;   jp= j + 1;   a= @.j   /*obtain the  "A"  element.            */                                        b= @.jp  /*   "    "   "B"     "                */        newD= abs(a - b)                         /*obtain difference between 2 elements.*/        if newD<d  then iterate                  /*Is this  not  a new max difference ? */        d= newD                                  /*assign new maximum difference,  and  */        n= n + 1                                 /*bump the # of (difference) sets.     */        aa.n= a;        bb.n= b                  /*  the elements that had the max diff.*/        end   /*j*/saysay 'The maximum difference of the elements in the list is:  '     d        do k=1  for n        say 'and is between the elements: '   right(aa.k, w)    " and "     right(bb.k, w)        end   /*k*/exit 0                                           /*stick a fork in it,  we're all done. */`
output   when using the default input:
```   list  of elements:  1 8 2 -3 0 1 1 -2.3 0 5.5 8 6 2 9 11 10 3
number of elements:  17

The maximum difference of the elements in the list is:   7
and is between the elements:     1  and     8
and is between the elements:     2  and     9
and is between the elements:    10  and     3
```

## Ring

` see "working..." + nlstrList = "[1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3]"see "Maximum difference between adjacent elements of list is:" + nl + nlsee "Input list = " + strList + nl + nlsee "Output:" + nlsList = [1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3] sortList = [] for n = 1 to len(sList)-1    diff = fabs(sList[n]-sList[n+1])    oldDiff = diff    first = sList[n]    second = sList[n+1]    add(sortList,[oldDiff,first,second])next sortList = sort(sortlist,1)sortList = reverse(sortlist)flag = 1 for n=1 to len(sortList)-1    oldDiff1 = sortlist[n][1]    oldDiff2 = sortlist[n+1][1]     first1 = sortlist[n][2]    second1 = sortlist[n][3]    first2 = sortlist[n+1][2]    second2 = sortlist[n+1][3]    if n = 1 and oldDiff1 != oldDiff2       see "" + first1 + "," + second1 + " ==> " + oldDiff1 + nl     ok    if oldDiff1 = oldDiff2       if flag = 1          flag = 0          see "" + first1 + "," + second1 + " ==> " + oldDiff1 + nl             see "" + first2 + "," + second2 + " ==> " + oldDiff2 + nl       else          see "" + first2 + "," + second2 + " ==> " + oldDiff2 + nl       ok    else       exit    oknext see "done..." + nl `
Output:
```working...
Maximum difference between adjacent elements of list is:

Input list = [1,8,2,-3,0,1,1,-2.3,0,5.5,8,6,2,9,11,10,3]

Output:
2,9 ==> 7
1,8 ==> 7
10,3 ==> 7
done...
```

## Vlang

Translation of: go
`import math fn main() {    list := [1.0, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8, 6, 2, 9, 11, 10, 3]    mut max_diff := -1.0    mut max_pairs := [][2]f64{}    for i in 1..list.len {        diff := math.abs(list[i-1] - list[i])        if diff > max_diff {            max_diff = diff            max_pairs = [[list[i-1], list[i]]!]        } else if diff == max_diff {            max_pairs << [list[i-1], list[i]]!        }    }    println("The maximum difference between adjacent pairs of the list is: \$max_diff")    println("The pairs with this difference are: \$max_pairs")}`
Output:
```The maximum difference between adjacent pairs of the list is: 7
The pairs with this difference are: [[1, 8] [2, 9] [10, 3]]
```

## Wren

`var list = [1, 8, 2, -3, 0, 1, 1, -2.3, 0, 5.5, 8,6, 2, 9, 11, 10, 3]var maxDiff = -1var maxPairs = []for (i in 1...list.count) {    var diff = (list[i-1] - list[i]).abs    if (diff > maxDiff) {        maxDiff = diff        maxPairs = [[list[i-1], list[i]]]    } else if (diff == maxDiff) {        maxPairs.add([list[i-1], list[i]])    }}System.print("The maximum difference between adjacent pairs of the list is: %(maxDiff)")System.print("The pairs with this difference are: %(maxPairs)")`
Output:
```The maximum difference between adjacent pairs of the list is: 7
The pairs with this difference are: [[1, 8], [2, 9], [10, 3]]
```

## XPL0

`real List, Dist, MaxDist;int  I;[List:= [1., 8., 2., -3., 0., 1., 1., -2.3, 0., 5.5, 8., 6., 2., 9., 11., 10., 3.];MaxDist:= 0.;for I:= 0 to 17-2 do    [Dist:= abs(List(I) - List(I+1));    if Dist > MaxDist then        MaxDist:= Dist;    ];Format(1, 0);for I:= 0 to 17-2 do    [Dist:= abs(List(I) - List(I+1));    if Dist = MaxDist then        [RlOut(0, List(I));  Text(0, ", ");  RlOut(0, List(I+1));        Text(0, " ==> ");  RlOut(0, MaxDist);  CrLf(0);        ];    ];]`
Output:
```1, 8 ==> 7
2, 9 ==> 7
10, 3 ==> 7
```