6
$\begingroup$

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)

$\endgroup$
2
  • 3
    $\begingroup$ 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] $\endgroup$
    – Ben Izd
    Apr 30, 2022 at 15:32
  • $\begingroup$ Thank you so much! :) $\endgroup$
    – Ito
    Apr 30, 2022 at 15:38

5 Answers 5

11
$\begingroup$

I changed D to Dd:

MapAt[Dd, A, 2 ;; ;; 2]
$\endgroup$
2
  • $\begingroup$ Thank you so much! But just to see if I got all of it, the "2 ;; ;; 2" thing translates exacly to: "All even indexes"? $\endgroup$
    – Ito
    Apr 30, 2022 at 15:48
  • 1
    $\begingroup$ @MatheusMantovaniMeneghel lookup Span in docs. $\endgroup$
    – Kuba
    Apr 30, 2022 at 15:52
10
$\begingroup$

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}    *)
$\endgroup$
8
$\begingroup$
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}
$\endgroup$
6
$\begingroup$

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}*)
$\endgroup$
1
  • 1
    $\begingroup$ A very nice use of Det, too $\endgroup$
    – user1066
    May 2, 2022 at 8:37
6
$\begingroup$
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} *) 
$\endgroup$
1

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.