5
$\begingroup$

Floyd's triangle is an arrangement of the positive integers into a triangle such that the $n$th line contains $n$ integers. To illustrate, here are the first 4 lines of Floyd's triangle:

 1
 2  3
 4  5  6
 7  8  9 10

I am trying to design a function that takes as input an integer n, and returns a list of all the ways to select 3 elements from n rows of Floyd's triangle such that they lie consecutively in a horizontal, vertical, or diagonal line within the triangle. For example, for an input of 4 (corresponding to the triangle shown above) the expected output would be

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

I have a boring and clunky procedural implementation currently, which I post below as an answer, but I expect there exist pithier solutions that make better use of Mathematica's powers. In particular, I might expect that there would be a solution that does not require me to explicitly generate the triangle.

$\endgroup$

2 Answers 2

4
$\begingroup$

My current solution is to explicitly construct the triangle as a list of lists, then loop through it to find each horizontal, vertical, and diagonal triple:

triples[n_] := With[{triangle = TakeList[Range[Total[#]], #]& @ Range[n]},
  Table[{
    (* horizontal *) triangle[[i+2, j;;j+2]],
    (* vertical *)   triangle[[i;;i+2, j]],
    (* diagonal *)   triangle[[i;;i+2, -j]]
  }, {i, n-2}, {j, i}] ~Flatten~ 2

triples[4]
(* {{4,5,6}, {1,2,4}, {1,3,6}, {7,8,9}, {2,4,7}, {3,6,10}, {8,9,10}, {3,5,8}, {2,5,9}} *)

But I am hoping y'all have smarter approaches.

$\endgroup$
1
$\begingroup$

If the triangle is given as

tri = {{1}, {2, 3}, {4, 5, 6}, {7, 8, 9, 10}}

and one wants to select k consecutive elements, then you can do this:

With[{k = 3}, 
     Sort[Flatten[If[Length[#] >= k, Partition[#, k, 1], Nothing] & /@ 
                  Join[tri, Flatten[tri, {{2}, {1}}],
                       Array[Diagonal[tri, 1 - #] &, Length[tri]]], 1]]]
   {{1, 2, 4}, {1, 3, 6}, {2, 4, 7}, {2, 5, 9}, {3, 5, 8}, {3, 6, 10}, {4, 5, 6},
    {7, 8, 9}, {8, 9, 10}}
$\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.