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 Apr 27 at 23:28
  • $\begingroup$ @MichaelE2 Thank you very very much :), yes, it works. $\endgroup$ – user67849 Apr 27 at 23:33
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, privacy policy and cookie policy