8
$\begingroup$

I've been struggeling with the command riffle.

list = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}, {13,14, 15}}

How do I use riffle like this, but add 1 to "X", every time it gets inserted? So when it has inserted "X" 5 times, it would be X5, instead of just "X".

"X" is a string.

Riffle[list, "X", 3]

 {{1, 2, 3}, {4, 5, 6}, X, {7, 8, 9}, {10, 11, 12}, X, {13, 14, 15}}

The output I am looking for:

{{1, 2, 3}, {4, 5, 6}, X1, {7, 8, 9}, {10, 11, 12}, X2, {13, 14, 15}}

$\endgroup$
  • 3
    $\begingroup$ Why not spend some quality time with your previous riffle-related questions and learn from the comments/answers there? Once you get the hang of the basics, iterations on the insert-at-x-with-y become trivial. $\endgroup$ – Yves Klett Dec 7 '15 at 14:21
  • $\begingroup$ @EminemIsLife, do you think you will ever start to accept the answers according to the site charter? $\endgroup$ – garej Dec 8 '15 at 21:52
  • $\begingroup$ @EminemIsLife, I see I've managed it =)) You may just vote for all responses and add comments for those who might also deserved 'accept' check. $\endgroup$ – garej Dec 9 '15 at 16:38
  • $\begingroup$ @EminemIsLife, by the way, if you want your comment got seeing by addressee, type @<name>. I repeat those thing because see that you like to quickly ask a lot of questions =)) $\endgroup$ – garej Dec 9 '15 at 16:42
12
$\begingroup$

Create a list to riffle with,

Riffle[list, Table[StringJoin["X", ToString[i]], {i, 1, Length[list]}], 3]

{{1, 2, 3}, {4, 5, 6}, "X1", {7, 8, 9}, {10, 11, 12}, "X2", {13, 14, 
  15}}
$\endgroup$
10
$\begingroup$
Module[{i = 1}, Riffle[list, "X", 3] /. "X" :> "X" <> ToString[i++]]

{{1, 2, 3}, {4, 5, 6}, "X1", {7, 8, 9}, {10, 11, 12}, "X2", {13, 14, 15}}

$\endgroup$
7
$\begingroup$
Riffle[list, Table["X" <> ToString[i], {i, Ceiling[Length[list]/3]}],
  3]

{{1, 2, 3}, {4, 5, 6}, "X1", {7, 8, 9}, {10, 11, 12}, "X2", {13, 14, 15}}

$\endgroup$
1
$\begingroup$

A variation of eldo's method that allows "X" to be present in the list itself without conflict.

incRiffle[L_List, s_String, p_: 2] :=
  Module[{i = 1},
    Riffle[L, Unevaluated@Symbol[s <> ToString[i++]], p]
  ]

Question example:

incRiffle[list, "X", 3]
{{1, 2, 3}, {4, 5, 6}, X1, {7, 8, 9}, {10, 11, 12}, X2, {13, 14, 15}}

Other examples:

incRiffle[Range@5, "a"]

incRiffle[{"W", "X", "Y", "Z"}, "X"]
{1, a1, 2, a2, 3, a3, 4, a4, 5}

{"W", X1, "X", X2, "Y", X3, "Z"}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.