5
$\begingroup$

If I have a list of numbers as (the number of elements in this list is even)

list={1,23,32,54,65,76,87,98,109,110,...}

How can I ask Mathematica to subtract each adjacent pair, and then, sum them, i.e. compute this value

$sum=(...)+(110-109)+(98-87)+(76-65)+(54-32)+(23-1)$

$\endgroup$
2
  • 2
    $\begingroup$ Total@BlockMap[Subtract @@ # &, Reverse@list, 2]? $\endgroup$
    – kglr
    Commented Aug 11, 2021 at 22:45
  • 2
    $\begingroup$ ... or Total[#[[2 ;; ;; 2]] - #[[;; ;; 2]]] &@list, or Total@Differences[list][[;; ;; 2]]? $\endgroup$
    – kglr
    Commented Aug 11, 2021 at 22:46

5 Answers 5

6
$\begingroup$
list = {1, 23, 32, 54, 65, 76, 87, 98, 109, 110};

Total @ Differences[list][[;; ;; 2]]
67

Also

(-1)^Range[Length @ #]. # & @ list
67
$\endgroup$
3
$\begingroup$

Just to add other ways:

Total[(#[[2]] - #[[1]]) & /@ Partition[list, 2]]

(* 67 *)

Total@Flatten[Differences /@ Partition[list, 2]]
$\endgroup$
2
  • 1
    $\begingroup$ similar to your first answer you can write Total[(#2 - #1) & @@@ Partition[list, 2]] $\endgroup$
    – Jason B.
    Commented Aug 12, 2021 at 2:17
  • 1
    $\begingroup$ Even simpler: Total[-Subtract @@@ Partition[list, 2]] $\endgroup$ Commented Aug 12, 2021 at 14:52
2
$\begingroup$
list = {1, 23, 32, 54, 65, 76, 87, 98, 109, 110};
PadRight[{-1, 1}, Length@list, {-1, 1}] . list

67

$\endgroup$
2
  • $\begingroup$ For my own learning: if you add 111 to the end of the list, the result is -44. Is this the standard way of padding such a list or the choice of {-1,1} is arbitrary? $\endgroup$
    – Syed
    Commented Aug 12, 2021 at 11:09
  • $\begingroup$ @Syed Since the sequence is -1,1,-1,1,…,-1,1,-1 for the new case, the last term is 111*(-1),so the result become 67+111*(-1)=-44 $\endgroup$
    – cvgmt
    Commented Aug 12, 2021 at 13:22
2
$\begingroup$
list = {1, 23, 32, 54, 65, 76, 87, 98, 109, 110};

Using SequenceCases

Total @ SequenceCases[list, {a_, b_} :> b - a]

67

$\endgroup$
1
$\begingroup$
list = {1, 23, 32, 54, 65, 76, 87, 98, 109, 110};

Using MovingMap:

Total@(#2 - #1 & @@@ MovingMap[# &, list, 1][[1 ;; -1 ;; 2]])

(*67*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.