4
$\begingroup$

I can generate a table:

Table[{i, If[i == 4, 1, i + 1]}, {i, 4}]

and the output is

{{1, 2}, {2, 3}, {3, 4}, {4, 1}}

however, if I want to make i>4 lets say 12

Table[{i, If[i == 4, 1, i + 1]}, {i, 12}]

the output is now

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

is there any way I can get the following output instead,

{{1, 2}, {2, 3}, {3, 4}, {4, 1}, {5, 6}, {6, 7}, {7, 8}, {8, 5}, {9, 
  10}, {10, 11}, {11, 12}, {12, 9}}
$\endgroup$
1
  • 2
    $\begingroup$ You leave us guessing what is the rule. What don't you spell it out? $\endgroup$
    – rhermans
    May 11, 2023 at 14:35

5 Answers 5

7
$\begingroup$

Looks like you want it to be i-3 when i is divisible by 4:

Table[{i, If[Mod[i, 4] == 0, i - 3, i + 1]}, {i, 12}]

$\endgroup$
8
$\begingroup$
Table[{i, If[Divisible[i, 4], i - 3, i + 1]}, {i, 1, 12}]

You might also think about this as a permutation.

Transpose[
  {Range@12, 
   Permute[Range@12, Cycles[{{1, 4, 3, 2}, {5, 8, 7, 6}, {9, 12, 11, 10}}]]}]

You could also see this as applying a transformation to sublists.

Transpose[
  {Range@12, 
   Flatten[BlockMap[RotateLeft, Range@12, 4]]}]

Or you could construct it from a base pattern.

Flatten[
  Table[
    k + SubsetMap[RotateLeft, Table[{i, i}, {i, 4}], {All, -1}], 
    {k, 0, 8, 4}], 
  1]
$\endgroup$
3
$\begingroup$

Many great answers already. I would say that this is a good case where you could use ReplaceAll and Condition together:

Table[{i, i + 1}, {i, 12}] /. {x_, y_} /; Mod[x, 4] == 0 -> {x, x - 3}

(*{{1, 2}, {2, 3}, {3, 4}, {4, 1}, {5, 6}, {6, 7}, {7, 8}, {8, 5}, {9, 
  10}, {10, 11}, {11, 12}, {12, 9}}*)

You can modify your rule easily as well to suit whatever you need.

$\endgroup$
3
$\begingroup$
Flatten[Partition[#, 2, 1, 1] & /@ Partition[Range[12], 4], 1]

{{1, 2}, {2, 3}, {3, 4}, {4, 1}, {5, 6}, {6, 7}, {7, 8}, {8, 5}, {9, 10}, {10, 11}, {11, 12}, {12, 9}}

$\endgroup$
2
$\begingroup$

One method among many is to use

Table[{i, 4*Quotient[i-1, 4] + Mod[i+1, 4, 1]}, {i, 12}]
(* {{1, 2}, {2, 3}, {3, 4}, {4, 1}, {5, 6}, {6, 7}, 
 {7, 8}, {8, 5}, {9, 10}, {10, 11}, {11, 12}, {12, 9}} *)
$\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.