Floyd’s Triangle
May 22, 2018
I noticed the other day this list of the Top 75 Programming Interview Questions. I’m not sure of the origin of the list, and it does have a Java feel to it, but I was happy to see that we’ve covered almost all the questions on the list. One of the questions we missed is Number 57:
Write a program to print Floyd’s Triangle.
I wasn’t familiar with Floyd’s Triangle, so I had to peek at the solution. Floyd’s Triangle lists the numbers in order, in lines of increasing length, so a Floyd’s Triangle of size 5 looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Your task is to write two programs that print Floyd’s Triangle; you must write two different programs that use two fundamentally different methods. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
Golfing these in perl – the first one uses map to perform two loops..; the second a single loop – until we start drawing the “n+1″st row..
Perl6 solution using a single while loop and two variables to track state:
Alternative Perl6 solution that recursively works backward from the nth triangle number:
For most favoured languages try
Here’s a solution in C that uses a nested loop along with a counter.
Example:
Here’s a solution in C that uses a counter, printing a newline each time a triangular number is reached.
Example:
Here’s a solution in Python 3.
Output:
Prints the nth line of the triangle
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 5
Two solutions in Haskell.
The first one starts with the infinite list of successive integers and chops it up in increasingly larger chunks
The second solution generates increasingly long lists
The triangles can be printed using the following code:
If you don’t want to print an infinite triangle, you can cut it short as follows:
Racket
All three versions produce the same output. Here an example for n = 10
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
37 38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54 55
Code 👆 in Ruby.
Bash.
1 loop
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
2 loops
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Clojure/Script lazy streams
Test (try online at http://clojurescript.net):
[1]
[2 3]
[4 5 6]
[7 8 9 10]
[11 12 13 14 15]
Logically equivalent imperative Bash version using arrays
Test:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Haskell. Infinite list generator the first:
The second, using an unfold:
Either can then be pretty-printed to an arbitrary number of rows as follows: