Cases with condition and two different outcomes

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?

• Replace[t1, { {{{a_}, {c_, d_}}, e_} :> {{c, d}, {a, a}, e}, {{{a_, b_}, {c_, d_}}, e_} :> {{c, d}, {a, b}, e} } , 1 ] Jan 21, 2022 at 3:48

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.

• Good idea! Great! Thanks! Jan 22, 2022 at 10:10
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}}

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}}

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}}