Given that I have a list $\{P_0,P_1,P_2,\cdots,P_7\}$, where, $P_i$ is a real number or a list like {x,y}/{x,y,z}. Now I would like to double some elements according to given index(i) and interval(p). For instance,
$i=1,p=2$, the elements that will be doubled is $\{i-p-1,i,i+p+1\}=\{-2,1,4\}$. Namely, $P_1,P_4$ (delete $-2$ since $P_{-2}$ is non-existent)
$i=3,p=2$, the elements that will be doubled is $\{i-p-1,i,i+p+1\}=\{0,3,6\}$. Namely, $P_0,P_3,P_6$
My trial
Firstly, I find the positions of the elements that need to be doubled, then applying ReplacePart[]
elemAdjust1[elems_, deg_, i_] :=
Module[{idx, n = Length[elems] - 1, new},
idx = Select[{i - deg - 1, i, i + deg + 1}, 0 <= # <= n &] + 1;
new = {#, #} & /@ elems[[idx]];
ReplacePart[elems, Thread[idx -> new] /. {x_, x_} :> Sequence[x, x]]
]
Another method came form J.M., i.e., with the help of Partition[]
elemAdjust2[elems_, deg_, i_] :=
Module[{idx, n = Length[elems] - 1, left, mid, right},
idx = Select[{i - deg - 1, i, i + deg + 1}, 0 <= # <= n &] + 1;
left = Take[elems, {1, idx[[1]] - 1}];
right = Take[elems, {idx[[-1]] + 1, n + 1}];
mid = Take[elems, {idx[[1]], idx[[-1]]}];
mid = Flatten[Partition[mid, deg + 2, deg + 1, {-1, 1}, {}], 1];
Join[left, mid, right]
]
Test
pts = {P0, P1, P2, P3, P4, P5, P6, P7};
elemAdjust1[pts, 2, 1]
elemAdjust2[pts, 2, 1]
(*==> {P0, P1, P1, P2, P3, P4, P4, P5, P6, P7}*)
elemAdjust1[pts, 2, 2]
elemAdjust2[pts, 2, 2]
(*==> {P0, P1, P2, P2, P3, P4, P5, P5, P6, P7}*)
elemAdjust1[pts, 2, 3]
elemAdjust2[pts, 2, 3]
(*==> {P0, P0, P1, P2, P3, P3, P4, P5, P6, P6, P7}*)
elemAdjust[{{0, 0}, {1, 1}, {2, -1}, {3, 0}, {4, -2}, {5, 1}}, 2, 2]
(*==> {{0, 0}, {1, 1}, {2, -1}, {2, -1}, {3, 0}, {4, -2}, {5, 1}, {5, 1}}*)
Question
- Is there more better to deal with this problem?
doubleElements[lst, postions]
doubleElements[{a1,a2,a3,a4,a5,a6,a7,a8,a9}, {1,7,9}]==>
{a1,a1,a2,a3,a4,a5,a6,a7,a7,a8,a9,a9}


Range@Length@list /. Map[# -> Sequence[#, #] &, indices + 1],/.could avoid the invalid indices automatically, rather than usingSelect[]to achieve the valid indices. – xyz Jun 16 '16 at 07:31MapAtinstead ofReplacePartin your code too. – Kuba Jun 16 '16 at 07:32MapIndexed[If[MemberQ[indices + 1, First@#2], ## &[#, #], #] &, list]– Mr.Wizard Jun 16 '16 at 07:51