1
$\begingroup$

I have a set of numbers like this

s = {a, b, c, d, e, f, ..., g, h}

and I would like to ask Mathematica to do the following operation (to sum the subtractions of adjacent numbers)

(a - b) + (c - d) + (e - f) + ... + (g - h)

Is it possible to do that?

$\endgroup$
2
  • 1
    $\begingroup$ s[[;; ;; 2]] - s[[2 ;; ;; 2]] // Total? Assumes the length is even $\endgroup$
    – Michael E2
    Commented Apr 27, 2021 at 23:28
  • $\begingroup$ @MichaelE2 Thank you very very much :), yes, it works. $\endgroup$
    – user67849
    Commented Apr 27, 2021 at 23:33

3 Answers 3

1
$\begingroup$

Some more options

Clear[a, b, c, d, e, f, g, h];
s = {a, b, c, d, e, f, g, h};
Total[Table[s[[n]] - s[[n + 1]], {n, 1, Length[s] - 1, 2}]]
Sum[s[[n]] - s[[n + 1]], {n, 1, Length[s] - 1, 2}]
Total[SequenceCases[s, {j_, k_} :> j - k]]
Total[Subtract @@@ Partition[s, 2]]

All give

a - b + c - d + e - f + g - h

$\endgroup$
1
$\begingroup$

A mathematical approach: $\sum_{k=1}^n (-1)^{k+1} s_k$ translates as follows

s = {a, b, c, d, e, f, g, h};
Sum[(-1)^(k+1) s[[k]], {k, 1, Length[s]}]
(* a - b + c - d + e - f + g - h *)
$\endgroup$
0
$\begingroup$
☺ = +## & @@ (#[[;; ;; 2]] - #[[2;; ;; 2]]) &;


☺ @ {a, b, c, d, e, f, g, h}
 a - b + c - d + e - f + g - h
$\endgroup$

Your Answer

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