Ask coding questions

← Back to all posts
##### To shape an addition triangle

Hello, i'm very new to TypeScript, and i would ask something because i'm stumped looking for tutorials and still doesn't get the idea.

Basically i am tasked to create a triangle that shows a tree from the original number to its addition.
Example the addition from [1, 2, 3]

 (notice how 8 was from 3 + 5, the 5 came from 2 + 3)
[3, 5]

Though i could call factorials, i don't know how to make it into an addition and shape it into a triangle like above. Any explanation on the code would be very helpful, thanks :)

Answered by Coder100 (16958) [earned 5 cycles]
View Answer
##### Comments
hotnewtop
Coder100 (16958)

??
So:

``[1, 2, 3]``

becomes:

````

whattt where does the `8` come from?

JaneFrenceees (0)

@Coder100 Sorry for not clarifying the messy post. It's basically an addition triangle, where 1, 2, and 3 would calculate in the following:

1 2 3 -> they add each other from the number beside them
1 + 2 = 3
2 + 3 = 5

from the result (3 and 5), we would need to add it again: 3 + 5 = 8
The triangle would show the final number on top of the pyramid. After much looking into the code, i would realize the dumbest thing i could do is to program

console.log( (result form all array) + \n + (results from second calculated array + \n + (the first original array))

though this would be a problem for bigger original numbers such as 1, 2, until 10 above

JaneFrenceees (0)

@Coder100 though for the final addition it would work, i don't really know how to automatically format the triangle into
[] [] [].... automatically without me doing the barbaric solution i wrote earlier

Coder100 (16958)

done

``````function factorial(num: number[], prev:number = 0): number {
if (num.length == 1) return num + prev
return factorial(num.slice(1), num + num)
}

factorial([1, 2, 3])``````
JaneFrenceees (0)

@Coder100 sorry if i'm asking, but what does the num.slice do? Would be an addition to note for me

Coder100 (16958)

ok, so `.slice` basically take a portion of an `array`
read more here
@JaneFrenceees

JaneFrenceees (0)

@Coder100 ah i see, thank you so much for your assistance!

JaneFrenceees (0)

@Coder100 it gave the final answer. I would say it works well, i just need to see how to parse it into separate lines of the triangle

Coder100 (16958)

Maybe:

``````function factorial(num: number): number {
if (num <= 1) return 1;
return num * factorial(num - 1);
}

factorial(3); // 6``````

And then for your array, it would be really easy with `reduce`:

``````function factorial(num: number[]): number {
return num.reduce((prev: number, curr: number): number => prev * curr, 1)
}``````

# Or do you mean addition?

``````function factorial(num: number): number {
if (num <= 1) return 1;
return num + factorial(num - 1);
}

factorial(3); // 6``````

And,

``````function factorial(num: number[]): number {
return num.reduce((prev: number, curr: number): number => prev + curr, 1)
}``````