4
$\begingroup$

Is there a more effecient way to generate the sequence shown below.

createOrder[n_] := 
Which[OddQ[n],
    Join[Table[2 i - 1, {i, 1, (n + 1)/2}],Reverse@Table[2 i, {i, 1, (n + 1)/2}]], 
    EvenQ[n],
    Join[Table[2 i - 1, {i, 1, n/2 + 1}],Reverse@Table[2 i, {i, 1, n/2}]]]


createOrder[#] & /@ Range[8] // MatrixForm

table

$\endgroup$
4
$\begingroup$
cg = Compile[{{a, _Integer, 1}, {b, _Integer, 1}, {i, _Integer}},
   Join[a[[1 ;; Quotient[i + 1, 2]]], b[[-Quotient[i, 2] ;; -1]]],
   CompilationTarget -> "WVM",
   RuntimeAttributes -> {Listable},
   Parallelization -> True
   ];
g[n_Integer] := cg[Range[1, n + 1, 2], Range[n + Mod[n, 2], 2, -2], Range[2, n + 1]];
$\endgroup$
  • $\begingroup$ there's a little bug with g[n_?Integer], use g[n_Integer] or g[n_?IntegerQ] instead. $\endgroup$ – Jerry Jan 18 at 10:01
  • $\begingroup$ Good point, I added the pattern after posting... $\endgroup$ – Henrik Schumacher Jan 18 at 10:10
6
$\begingroup$
ClearAll[f]
f[n_Integer] := Join[Range[1, #, 2], Reverse[Range[2, #, 2]]] & /@ Range[2, n];
TeXForm @ MatrixForm @ f[8]

$\left( \begin{array}{c} \{1,2\} \\ \{1,3,2\} \\ \{1,3,4,2\} \\ \{1,3,5,4,2\} \\ \{1,3,5,6,4,2\} \\ \{1,3,5,7,6,4,2\} \\ \{1,3,5,7,8,6,4,2\} \\ \end{array} \right)$

Also

ClearAll[f2, f3]
f2[n_Integer] := SortBy[Range@#, {EvenQ, -# (-1 )^Mod[#, 2] &}] & /@ Range[2, n]
f3[n_] := Ordering[Transpose[{-Mod[#, 2], -# (-1 )^Mod[#, 2]} &@Range[#]]] & /@ Range[2, n]

f[8] == f2[8] == f3[8]

True

$\endgroup$
5
$\begingroup$
   fGetList[n_]:= (Select[Range[#], OddQ]~Join~Reverse@Select[Range[#], EvenQ]) & /@Range[n] // Rest

   fGetList[10] // MatrixForm // TeXForm

$ \left( \begin{array}{c} \{1,2\} \\ \{1,3,2\} \\ \{1,3,4,2\} \\ \{1,3,5,4,2\} \\ \{1,3,5,6,4,2\} \\ \{1,3,5,7,6,4,2\} \\ \{1,3,5,7,8,6,4,2\} \\ \{1,3,5,7,9,8,6,4,2\} \\ \{1,3,5,7,9,10,8,6,4,2\} \\ \end{array} \right)$

another version

fGetList2[n_?IntegerQ] := 
 Flatten@MapAt[Reverse, GatherBy[Range[#], OddQ], 2] & /@ Range[2, n]

fGetList2[10] // MatrixForm // TeXForm

$\left( \begin{array}{c} \{1,2\} \\ \{1,3,2\} \\ \{1,3,4,2\} \\ \{1,3,5,4,2\} \\ \{1,3,5,6,4,2\} \\ \{1,3,5,7,6,4,2\} \\ \{1,3,5,7,8,6,4,2\} \\ \{1,3,5,7,9,8,6,4,2\} \\ \{1,3,5,7,9,10,8,6,4,2\} \\ \end{array} \right)$

$\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.