PDA

View Full Version : Triangle calculation


DavidSnider
Dec30-09, 01:54 PM
Let's say you have a triangle like:
1
2 3
4 5 6
7 8 9 10

The children of each element in the triangle are those directly adjacent on the next row. For example the children of 4 are 7 and 8. The children of 5 are 8 and 9.

Now let's say we flatten it to: [1,2,3,4,5,6,7,8,9,10]

Is there a way to compose a function that takes the index of the parent and returns a tuple containing the indexes of the children? (Assume 0 based indexes. The 1 through 10 are values, not indexes)

LCKurtz
Dec30-09, 02:40 PM
Is 7 a child of 5?

DavidSnider
Dec30-09, 03:00 PM
No.

1: 2,3
2: 4,5
3: 5,6
4: 7,8
5: 8,9
6: 9,10

It's easier to picture when you draw the triangle as a pyramid shape, but I couldn't get the forum to format it that way.

tiny-tim
Dec30-09, 03:44 PM
Hi DavidSnider! :smile:

Use the CODE tag :wink: …
1
2 3
4 5 6
7 8 9 10

Hint: the kth element in the nth row is parent to the kth and k+1th elements in the n+1th row, and the index of the first element in the nth row is … ? :smile:

DavidSnider
Dec30-09, 06:29 PM
Ah, thanks. I think I got it.

First element in nth row is the same as the triangle number:
\frac{n^2 + n}{2}

What I needed was the Triangle root:
\frac{-1\pm\sqrt{8n+1}}{2}

so the index would be:
n+\frac{1+\sqrt{8n + 1}}{2}