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)
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)
I changed D to Dd:
MapAt[Dd, A, 2 ;; ;; 2]
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}
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} *)
Flatten, see this answer by Leonid Shifrin
– user1066
May 01 '22 at 09:26
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}*)
list = {1, 1, 1, 1, 1};
Using ReplaceAt (new in 13.1)
ReplaceAt[x_ :> x + 1, 2 ;; ;; 2] @ list
{1, 3, 3, 5, 5}
Dis a built-in Mathematica function. It's recommended to not use single letter with upper case function names. TryMapAt[# + 1 &, {1, 2, 3, 4, 5}, 2 ;; ;; 2]– Ben Izd Apr 30 '22 at 15:32