7

A = {1, 2, 3, 4, 5} and, Dd[P_] := P + 1

How can I map "Dd" into "A" such that the outcome is: {1, 3, 3, 5, 5}?

(Dd is only applied to the elements that its indexes are even)

Ito
  • 71
  • 2
  • 4
    Welcome to the community. D is a built-in Mathematica function. It's recommended to not use single letter with upper case function names. Try MapAt[# + 1 &, {1, 2, 3, 4, 5}, 2 ;; ;; 2] – Ben Izd Apr 30 '22 at 15:32
  • Thank you so much! :) – Ito Apr 30 '22 at 15:38

6 Answers6

12

I changed D to Dd:

MapAt[Dd, A, 2 ;; ;; 2]
lericr
  • 27,668
  • 1
  • 18
  • 64
  • Thank you so much! But just to see if I got all of it, the "2 ;; ;; 2" thing translates exacly to: "All even indexes"? – Ito Apr 30 '22 at 15:48
  • 1
    @MatheusMantovaniMeneghel lookup Span in docs. – Kuba Apr 30 '22 at 15:52
11

You can use the new ApplyTo:

A = {1, 2, 3, 4, 5};
Dd[P_] := P + 1

A[[2 ;; ;; 2]] //= Dd; A (* {1, 3, 3, 5, 5} *)

Roman
  • 47,322
  • 2
  • 55
  • 121
9
alist = {1, 2, 3, 4, 5}

Using MapIndexed:

MapIndexed[If[EvenQ @@ #2, #1 + 1, #] &, alist]

Using addition:

Generate {0,1,0,1..} array

blist = (Flatten@ConstantArray[{0, 1}, Ceiling[Length@alist/2]])[[1 ;;
     Length@alist]]

{0, 1, 0, 1, 0}

alist + blist

Using ReplacePart:

evenrange = Range[2, Length@alist, 2];

ReplacePart[alist, Thread[evenrange -> alist[[evenrange]] + 1]]


Result:

{1, 3, 3, 5, 5}
Syed
  • 52,495
  • 4
  • 30
  • 85
8
SubsetMap[dd, arr, 2 ;; -1 ;; 2]

(* {1, 3, 3, 5, 5} *)

where:

arr = {1, 2, 3, 4, 5};
dd[p_] := p + 1

Just for fun

{arr[[1;;-1;;2]], dd@arr[[2;;-1;;2]]} // Flatten[#, {{2,1}}]&

(* {1, 3, 3, 5, 5} *)

MapIndexed[#1+Boole@EvenQ[#2][[1]]&, arr]

(* {1, 3, 3, 5, 5} *)

user1066
  • 17,923
  • 3
  • 31
  • 49
7

Using Position and Map:

Map[If[EvenQ[Det[Position[A, #]]] === True, # + 1, #] &, A]
(*{1, 3, 3, 5, 5}*)

Using Outer, Range and MapAt:

MapAt[# + 1 &, A, Outer[List, Range[2, Length[A], 2]]]
(*{1, 3, 3, 5, 5}*)

Using Position and Map:

Plus[Map[If[EvenQ[Det[Position[A, #]]] === True, 1, 0] &, A], A]
(*{1, 3, 3, 5, 5}*)
E. Chan-López
  • 23,117
  • 3
  • 21
  • 44
4
list = {1, 1, 1, 1, 1};

Using ReplaceAt (new in 13.1)

ReplaceAt[x_ :> x + 1, 2 ;; ;; 2] @ list

{1, 3, 3, 5, 5}

eldo
  • 67,911
  • 5
  • 60
  • 168