倒挂金字塔加法是一个过程,把一个数字的列表,并连续地加在一起,直到你达到一个数字。
当给定数字2, 1, 1时,将发生以下过程:
2 1 1
3 2
5这以数字5结尾。
考虑到向上向上的金字塔(上升)的右侧,编写一个程序或函数来返回原始列表。
新的额外挑战:尝试在小于O(n^2)的范围内完成此任务。
f([5, 2, 1]) => [2, 1, 1]
f([84,42,21,10,2]) => [4,7,3,8,2]注:倒向金字塔将永远不会是空的,将永远由正整数组成。
发布于 2019-04-30 14:48:14
发布于 2019-04-30 13:50:43
Ans→L₁:dim(L₁→dim(L₂:While 1-Ans:L₁(Ans→L₂(Ans:-ΔList(L₁→L₁:dim(Ans:End:L₁(Ans→L₂(Ans:L₂输入是Ans中三角形右侧的列表,正如挑战中所描述的那样。
输出是所述三角形的顶部行。
{5,2,1
{5 2 1}
prgmCDGF19
{2 1 1}
{84,42,21,10,2
{84 42 21 10 2}
prgmCDGF19
{4 7 3 8 2}解释:
该解决方案滥用了这样一个事实,即以三角形的右侧为起始点形成的三角形最终是每个元素中的变化。
换句话说,
2 1 1
3 2
5变成:
5 2 1
3 1
2因此,生成的列表是这个新三角形的右侧,可以通过将最后一个元素设置为其父列表长度的索引来形成该三角形。
Ans→L₁ ;store the input list in L₁
dim(L₁→dim(L₂ ;set the length of L₂ to the length of L₁
While 1-Ans ;while the L₁'s length is not 1
L₁(Ans→L₂(Ans ;set the last element of L₁ to the corresponding index in L₂
-ΔList(L₁→L₁ ;get the change in each element, then negate
; (elements are in descending order so the change in each
; element will be negative)
; and store the resulting list in L₁
dim(Ans ;leave the length of L₁ in "Ans"
End
L₁(Ans→L₂(Ans ;set the element again
; (needed for final step)
L₂ ;leave L₂ in "Ans"
;implicit print of "Ans"注: TI-BASIC是一种标记化语言.字符计数不等于字节计数。
https://codegolf.stackexchange.com/questions/184951
复制相似问题