# Selecting terms from a list based on certain pattern

I have the following table:

n = 3;

myTab = Flatten[Table[{i, j}, {i, -1, n}, {j, -1, n}], 1]

(*output:
{{-1,-1},{-1,0},{-1,1},{-1,2},{-1,3},{0,-1},{0,0},{0,1},{0,2},{0,3},
{1,-1},{1,0},{1,1},{1,2},{1,3},{2,-1},{2,0},{2,1},{2,2},{2,3},{3,-1},
{3,0},{3,1},{3,2},{3,3}}
*)


Now from myTab, I only want to select those elements {i,j} that matches the pattern {i,i+1} or {n,i}. What is the best way to achieve that in Mathematica? Any help is much appreciated!

Using patterns and Cases:

Cases[myTab, ({i_ ,j_} /; j == i + 1) | {n, _}]
Cases[myTab,  {i_, j_} /; j == i + 1 || i == n]

(* Out:
{{-1, 0}, {0, 1}, {1, 2}, {2, 3},
{3, -1}, { 3, 0}, {3, 1}, {3, 2}, {3, 3}} *)


Using Select with a selector function:

Select[myTab, Last[#] == First[#] + 1 || First[#] == n &]

(* Same output *)


In case it helps, note also that your myTab can be generated directly with Tuples:

myTab == Tuples[Range[-1, n], 2]
(* True *)

• This is a great answer, thanks @MarcoB
– TDH
Jun 21, 2022 at 11:47
• @TDH Glad it helped! Jun 21, 2022 at 11:52
• The Tuples code is very nice, thanks @MarcoB!
– TDH
Jun 21, 2022 at 12:39
• Came to the same solution: Cases[myTab, {a_, b_} /; a + 1 == b || b == n] Jun 21, 2022 at 13:46
• @Valacar Great minds think alike :-) Jun 21, 2022 at 13:47
n = 3;
run = n - (-1) + 1;
sel = Flatten@
Normal@SparseArray[{Band[{1, 2}] -> 1, {run, _} -> 1}, {run, run}];
res = Pick[myTab, sel, 1]


{{-1, 0}, {0, 1}, {1, 2}, {2, 3}, {3, -1}, {3, 0}, {3, 1}, {3, 2}, {3, 3}}