A Triangular Sequence
August 9, 2019
Consider the triangle:
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 ...
When the triangle is flattened, it produces the sequence (1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 …).
Your task is to write a program to generate the flattened sequence, and a second program to calculate the nth item in the sequence. 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.
Here is something hackish I came up with in standard R7RS Scheme and a
few SRFI helpers. It uses only exact math in Scheme (no sqrt, etc.).
No proof yet, so usual caveat applies.
Output:
Rust version using an iterator to generate the sequence:
Link to playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6e91a92e70d95cd7f0aa9294194095d0
num = int(input(‘pleas enter rows number:’))
row = 0
while row < num :
n = row + 1
p = 1
while n > 0 :
while p < n :
print (p , end = ”)
p = p + 1
n = n – 1
row = row +1
print()
if row == 9:
plus = 0
for i in range (0 ,10):
plus = plus + i
print (‘The sum of the row 9 is : ‘ , plus)
Here’s a solution in Python.
Output:
A slightly different unrank function, arithmetic using doubles for maximum range – not sure at what point numeric error spoils things, good up to 10^11 or so at least.
Mathematical, the crucial fact is that if sqrt(2m) = n-1/2, then m = n(n-1)/2 + 1/8, ie. when doing the round(sqrt(2m)), the cutoff point between rows of the triangle are just above the triangular numbers (which is why unrank runs for 1, not 0):