4
$\begingroup$

Given

 t1 = {{{{3}, {2, 5}}, 1}, {{{3}, {2, 7}}, 5}, {{{2, 7}, {3, 7}}, 7}, {{{2, 7}, {3, 5}}, 1}}

I want to double the first part if only one number is present and then switch the first two parts of the sublists. I can do it by splitting:

t2 = Cases[t1, {{{a_}, {c_, d_}}, e_} -> {{c, d}, {a, a}, e}]
t3 = Cases[t1, {{{a_, b_}, {c_, d_}}, e_} -> {{c, d}, {a, b}, e}]
Join[t2, t3]

resulting in:

{{{2, 5}, {3, 3}, 1}, {{2, 7}, {3, 3}, 5}, {{3, 7}, {2, 7}, 7}, {{3, 5}, {2, 7}, 1}}

How can I do it in one go using conditions in Cases?

$\endgroup$
1
  • 6
    $\begingroup$ Replace[t1, { {{{a_}, {c_, d_}}, e_} :> {{c, d}, {a, a}, e}, {{{a_, b_}, {c_, d_}}, e_} :> {{c, d}, {a, b}, e} } , 1 ] $\endgroup$
    – march
    Jan 21, 2022 at 3:48

4 Answers 4

3
$\begingroup$

You may use PadRight.

With t1 in OP

Cases[t1, {{a_, b_}, c_} :> {b, PadRight[a, 2, First@a], c}]
{{{2, 5}, {3, 3}, 1}, {{2, 7}, {3, 3}, 5}, {{3, 7}, {2, 7}, 7}, {{3, 5}, {2, 7}, 1}}

Hope this helps.

$\endgroup$
1
  • $\begingroup$ Good idea! Great! Thanks! $\endgroup$
    – user57467
    Jan 22, 2022 at 10:10
2
$\begingroup$
list =
  {{{{3}, {2, 5}}, 1},
   {{{3}, {2, 7}}, 5},
   {{{2, 7}, {3, 7}}, 7},
   {{{2, 7}, {3, 5}}, 1}};

ReplaceAll[{a_} :> {a, a}] @ MapAt[Splice @* Reverse, {All, 1}] @ list

returns

{{{2, 5}, {3, 3}, 1}, 
 {{2, 7}, {3, 3}, 5}, 
 {{3, 7}, {2, 7}, 7}, 
 {{3, 5}, {2, 7}, 1}}
$\endgroup$
2
$\begingroup$
t1 = {{{{3}, {2, 5}}, 1}, {{{3}, {2, 7}}, 5}, {{{2, 7}, {3, 7}}, 
    7}, {{{2, 7}, {3, 5}}, 1}};

Using SequenceReplace (or SequenceCases):

SequenceReplace[t1, {{{{a_, b___}, {c_, d_}}, e_}} :> {{c, d}, {a, 
    If[b === {}, a, b]}, e}]

Using Cases:

Cases[t1, {{{a_, b___}, {c_, d_}}, 
   e_} :> {{c, d}, {a, If[b === {}, a, b]}, e}]

Result:

{{{2, 5}, {3, 3}, 1}, {{2, 7}, {3, 3}, 5}, {{3, 7}, {2, 7}, 7}, {{3, 5}, {2, 7}, 1}}

$\endgroup$
1
$\begingroup$
t1 = {{{{3}, {2, 5}}, 1}, {{{3}, {2, 7}}, 5},
     {{{2, 7}, {3, 7}}, 7}, {{{2, 7}, {3, 5}}, 1}};

Using Replace from level 1 through depth of t1 with the following rules:

rules = {
        {{a_}, {b__}} :> Splice@{{b}, {a, a}},
        {{c__}, {d__}} :> Splice@{{d}, {c}}
        };

Replace[#, rules, {1, Depth@#}] &@t1

Result:

{{{2, 5}, {3, 3}, 1}, {{2, 7}, {3, 3}, 5}, {{3, 7}, {2, 7}, 7}, {{3, 5}, {2, 7}, 1}}

$\endgroup$

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.