6
$\begingroup$

I wrote a code for partitioning a list. I want to group them into two groups following the same pattern: 1. element added, then 2. and 3. are omitted, then 4. and 5. added and goes like this. Partitioning is easy, then I have to add the first element manually but the problem is when I partition the list, it omits the last element because then the list contains odd number of elements and I have to add it to the list manually also. I thought maybe someone can figure out a more elegant way. My list is as follow:

 vars= {c0r, c0i, c1r, c1i, c2r, c2i, c3r, c3i, c4r, c4i, c5r, c5i, c6r, \
 c6i, c7r, c7i, c8r, c8i, c9r, c9i, c10r, c10i, c11r, c11i, c12r, \
 c12i, c13r, c13i, c14r, c14i, c15r, c15i}

and here is my code;

 varr1 = Partition[vars[[2 ;;]], 2]

 {{c0i, c1r}, {c1i, c2r}, {c2i, c3r}, {c3i, c4r}, {c4i, c5r}, {c5i, 
 c6r}, {c6i, c7r}, {c7i, c8r}, {c8i, c9r}, {c9i, c10r}, {c10i, 
 c11r}, {c11i, c12r}, {c12i, c13r}, {c13i, c14r}, {c14i, c15r}}    

 Join[{vars[[1]]}, Flatten[varr1[[2 ;; ;;   2]]], {vars[[-1]]}]

  {c0r, c1i, c2r, c3i, c4r, c5i, c6r, c7i, c8r, c9i, c10r, c11i, c12r, \
 c13i, c14r, c15i}

and this is the list I want.

$\endgroup$
4
$\begingroup$

You can use the five-argument form of Partition:

Flatten[Partition[vars, 2, 4, {-1, 1}, {}]]

{c0r, c1i, c2r, c3i, c4r, c5i, c6r, c7i, c8r, c9i, c10r, c11i, c12r, c13i, c14r, c15i}

You can also use

Pick[#, Mod[Range @ Length @ #, 4], 1 | 0]& @ vars 
Flatten[Partition[vars, 4][[All, {1, -1}]]]

Note: The last one is much faster than the first two.

$\endgroup$
  • $\begingroup$ You find the more clever way of picking them as first and third. $\endgroup$ – user59583 Oct 10 '18 at 13:34

Your Answer

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