帕斯卡的交替三角形


21

Pascal的三角形是通过以1连续的加法开始并使其各行形成而生成的。相反,在这里,我们将通过交替的乘法和加法来形成一个三角形。

我们开始行1只是一个孤独的1。之后,对奇数行进行加法,对偶数行(1索引)进行乘法。在执行加法步骤时,假定三角形外部的空间用0s 填充。当执行乘法步骤时,假定外部被1s 填充。

这是向下到7行的完整三角形。左侧的*+显示了执行该步骤以生成该行的步骤。

1                1
2 *            1   1
3 +          1   2   1
4 *        1   2   2   1
5 +      1   3   4   3   1
6 *    1   3  12  12   3   1
7 +  1   4  15  24  15   4   1

挑战

给定输入n,输出n该三角形的第th行。

规则

  • 您可以选择使用0-index,但是请注意加法和乘法行必须翻转,以便如上所述生成完全相同的三角形。如果您选择这样做,请在提交的内容中注明。
  • 可以假定输入和输出适合您语言的本机整数类型。
  • 输入和输出可以任何方便的格式给出。
  • 完整的程序或功能都是可以接受的。如果是函数,则可以返回输出而不是打印输出。
  • 如果可能,请提供一个在线测试环境的链接,以便其他人可以尝试您的代码!
  • 禁止出现标准漏洞
  • 这是因此所有常用的高尔夫规则都适用,并且最短的代码(以字节为单位)获胜。

例子

从多个示例中显示两个可能的输出示例:一个列表或一个用空格分隔的字符串。

4
[1, 2, 2, 1]

8
"1 4 60 360 360 60 4 1"

2
@totallyhuman不,唯一要输出的应该是第nth行。
AdmBorkBork

Answers:


16

帕斯卡249个 247 233字节

好吧,这是帕斯卡的交替三角形。

@ Mr.Xcoder节省了1个字节

function f(n,k:integer):integer;begin if((k<1)or(k>n)or(n=1))then f:=n mod 2 else if n mod 2=0then f:=f(n-1,k-1)*f(n-1,k)else f:=f(n-1,k-1)+f(n-1,k)end;
procedure g(n:integer);var k:integer;begin for k:=1to n do write(f(n,k),' ')end;

在线尝试!



7

Python 2中97个 93 86 81 78字节

-4个字节感谢Rod。-10个字节,要感谢Halvard Hummel。

f=lambda n:n and[[i+j,i*j][n%2]for i,j in zip([n%2]+f(n-1),f(n-1)+[n%2])]or[1]

0索引。

在线尝试!


1
干得好,我的方法(更长)。虽然我还没有时间去打高尔夫球。
Xcoder先生17年

1
我猜map([int.__add__ ,int.__mul__][i%2],[i%2]+a,a+[i%2])应该可以(未经测试)
Rod


1
不,这是递归的。您必须包括名称。
Xcoder先生17年


5

果冻17 12字节

µ×+LḂ$?Ḋ1;µ¡

这是一个完整的程序(或niladic链接),它从STDIN接收输入。

在线尝试!

怎么运行的

µ×+LḂ$?Ḋ1;µ¡  Main link. No arguments. Implicit argument: 0

          µ¡  Start a monadic chain and apply the ntimes quick to the previous one.
              This reads an integer n from STDIN and executes the previous chain n
              times, with initial argument 0, returning the last result.
µ             Start a monadic chain. Argument: A (array or 0)
       Ḋ          Dequeue; yield A without its first element.
   LḂ$?           If the length of A is odd:
 ×                    Multiply A and dequeued A.
                  Else:
  +                   Add A and dequeued A.
        1;        Prepend a 1 to the result.


3

贾姆,25个字节

{1a\{2%!_2$+\{.*}{.+}?}/}

0索引。

在线尝试!

说明

这是一个匿名块,它从堆栈中获取数字并将结果保留在堆栈中。

1a                        Push [1].
  \                       Bring the number to the top.
   {                 }/   For reach number 0 .. arg-1, do:
    2%!                    Push 0 if even, 1 if odd.
       _                   Copy that.
        2$+                Copy the list so far and prepend the 0 or 1 to it.
           \               Bring the 0 or 1 back to the top.
            {.*}{.+}?      If 1, element-wise multiplication. If 0, element-wise addition.

等待2%!是否应将偶数按1,奇数按0,否?
硕果累累'18

3

Mathematica,92个字节

(s={i=1};While[i<#,s=Flatten@{1,{Tr/@#,Times@@@#}[[i~Mod~2+1]]&@Partition[s,2,1],1};i++];s)&

在线尝试!(为了进行数学运算,将“ Tr”替换为“ Total”)


3

Haskell76 72字节

0索引解决方案:

(p!!)
p=[1]:[zipWith o(e:l)l++[1]|(l,(o,e))<-zip p$cycle[((*),1),((+),0)]]

在线尝试!

说明

p 递归定义交替三角形,它的基本情况/第一个元素是 [1]

p=[1]:[                                                            ]

然后,使用上一行(l)构建三角形。要知道该怎么做,我们需要跟踪正确的运算符(o)和相应的中性元素(e):

                           |(l,(o,e))<-zip p$cycle[((*),1),((+),0)]

从这一行开始,通过复制该行来生成新行,对于一个副本,我们在中性元素之前添加,用操作符将其压缩并附加一个1:

       zipWith o(e:l)l++[1]

3

R108 98字节

-10字节,方法是将实际的乘号替换为加号。请原谅我。

f=function(n){if(n<3)return(rep(1,n))else{v=f(n-1)};if(n%%2)`*`=`+`;return(c(1,v[3:n-2]*v[-1],1))}

在线尝试!

我对通用方法非常满意(我第一次给基元起别名),但是我敢肯定还需要打高尔夫球,尤其是当n <3导致很多样板的情况下处理笨拙时。


85个字节。我真的很喜欢您的解决方案`*`=`+`!相当聪明。我其余的改进只是标准的高尔夫技术,我很乐意根据您的要求进行解释:)
朱塞佩(Giuseppe)

80字节。我从您关于处理案件的笔记n<3
朱塞佩(Giuseppe)

2

外壳17 16字节

!G₅;1¢e*+
:1Sż⁰t

在线尝试!

1索引解决方案。

说明

第一行是main函数,它在第二行中调用helper函数。通常使用来调用helper函数,但是在这种情况下,我使用的是溢出标签壳的功能:如果你指的是线ň与程序M <N行,你行ň模m与修正功能的M / N应用于它。第二个修饰符函数是flip,因此我用于翻转辅助函数的参数而没有任何额外的字节开销。

这是助手功能。

:1Sż⁰t  Takes a function f and a list x.
   ż    Zip preserving elements of longer list
    ⁰   using function f
  S  t  x and its tail,
:1      then prepend 1.

这是主要功能。

!G₅;1¢e*+  Takes a number n.
      e*+  2-element list of the functions * and +
     ¢     repeated infinitely.
 G         Left scan this list
  ₅        using the flipped helper function
   ;1      with initial value [1].
!          Get n'th element.

2

C#(.NET Core)143 134 128字节

-4字节归Phaeze赞
--5字节归Zac Faragher赞--6
字节归Kevin Kevin Cruijssen赞

n=>{int[]b={1},c;for(int i=0,j;++i<n;b=c)for(c=new int[i+1],c[0]=c[i]=1,j=0;++j<i;)c[j]=i%2<1?b[j-1]+b[j]:b[j-1]*b[j];return b;}

在线尝试!

说明:

n =>
{
    int[] b = { 1 }, c;               // Create first layer
    for(int i = 0, j; ++i < n; b = c) // Iterate for every layer, replace last layer with a new one
        for(c = new int[i+1],         // Create new layer
            c[0] = c[i] = 1,          // First and last elements are always 1
            j = 0;
            ++j < i; )                // Replace every element (besides 1st and last)...
                c[j] = i % 2 == 0 ?
                    b[j - 1] + b[j] : // ... with addition...
                    b[j - 1] * b[j];  // ... or multiplication of two from previous layers
    return b;                         // Return latest layer
};

您应该能够将b数组初始化更改为var b=new[]{1};,编译器将为您确定数组类型。
JustinM-恢复莫妮卡

1
构造第一层的另一种方式是int[]b={1};- 11个字节对20原样或16如在@Phaeze的建议
扎克法拉格

1
@ZacFaragher和Phaeze谢谢!
GrzegorzPuławski17年

1
我知道已经有一段时间了,但是您可以再打6个字节:n=>{int[]b={1},c;for(int i=0,j;++i<n;b=c)for(c=new int[i+1],c[0]=c[i]=1,j=0;++j<i;)c[j]=i%2<1?b[j-1]+b[j]:b[j-1]*b[j];return b;}。我c像这样结合在一起int[]b={1},c;; 缩短i%2==0i%2<1; 并通过将所有内容放入其中来删除循环的括号。
凯文·克鲁伊森

大!感谢@KevinCruijssen
GrzegorzPuławski18年


1

腐霉菌,22个字节

@FryAmTheEggman节省了很多字节!最初的解决方案如下。

u++1@,+VGtG*VGtGlG1Q[1

完整测试套件(0索引)。

Pyth40 38 36 35字节

这感觉waaaaaaaay的时间过长。欢迎提出建议。

K]1VStQ=K++]1m@,sd*hded%N2C,KtK]1;K

测试套件在线试用!


使用reduce似乎要短得多。我也不认为这是最佳选择,我认为sub 20是否可管理?
FryAmTheEggman

@FryAmTheEggman查看我的修订历史。我说过我正在尝试找到一个与reduce相对的解决方法u(但无法弄清楚)。谢谢!
Xcoder先生17年

如果Pyth内置了一个预先添加...
Xcoder先生


1

Perl 5,111 + 2(-na)= 113字节

sub t{($r,$c)=@_;!--$r||!$c||$c>=$r?1:eval"t($r,$c)".($r%2?"*":"+")."t($r,$c-1)"}say map{t($F[0],$_).$"}0..$_-1

在线尝试!


1

Mathematica,70个字节

Fold[#2@@@Partition[#,2,1,{-1,1},{}]&,{1},PadRight[{},#,{1##&,Plus}]]&

Wolfram沙箱上尝试一下!不幸的是,它在数学中不起作用。它是0索引的。

说明:Partition[#,2,1,{-1,1},{}]获取一个列表并返回所有两个元素的子列表,再加上开始和结束的1个元素的列表-例如,{1,2,3,4}变为{{1}, {1,2}, {2,3}, {3,4}, {4}}PadRight[{},#,{1##&,Plus}]组成1##&(有效Times)和的交替列表Plus,其长度为输入数字。然后Fold,将Pluses和Timeses 重复应用分区函数,以创建三角形的行。




0

TI-Basic(TI-84 Plus CE),100字节

Prompt X
{1→M
For(A,2,X
LM→L
A→dim(M
For(B,2,A–1
If A/2=int(A/2
Then
LL(B–1)LL(B→LM(B
Else
LL(B–1)+LL(B→LM(B
End
End
1→LM(dim(LM
End
LM

1索引,提示用户输入并打印包含以下内容的列表: n Pascal交替三角形第th行的。

在循环时:L M是当前行,并且 L L是上一行。

TI-Basic是 标记化语言。此处使用的所有令牌均为一字节令牌。

我认为我可以通过从头开始修改M来进一步打高尔夫球。

说明:

Prompt X            # 3 bytes; get user input, store in X
{1→M                # 5 bytes, store the first row into LM
For(A,2,X           # 7 bytes, Loop X-1 times, with A as the counter, starting at 2
LM→L                # 5 bytes, copy list M into list L
A→dim(M             # 5 bytes, extend M by one
For(B,2,A–1         # 9 bytes, for each index B that isn't the first or last...
If A/2=int(A/2      # 10 bytes,    if A is even...
Then                # 2 bytes,     then...
LL(B–1)LL(B→LM(B     # 17 bytes,        the Bth item in this row is the Bth times the (B-1)th of the previous row
Else                # 2 bytes,     else...
LL(B–1)+LL(B→LM(B    # 18 bytes,        the Bth item in this row is the Bth plus the (B-1)th of the previous row
End                 # 2 bytes,     endif
End                 # 2 bytes,  endfor
1→LM(dim(LM         # 9 bytes, the last item is always 1
End                 # 2 bytes, endfor
LM                  # 2 bytes, Implicitly print the final row


0

JavaScript(ES6),71 69 66字节

f=n=>n?(p=f(n-1),[...p.map((v,i)=>i--?n%2?v*p[i]:v+p[i]:1),1]):[1]

在线尝试!

0索引。
-3字节 @Arnauld

f=n=>n?(p=f(n-1),[...p.map((v,i)=>i--?n%2?v*p[i]:v+p[i]:1),1]):[1]

for (var i = 0; i < 10; ++i) {
  console.log(JSON.stringify(f(i)));
}


1
使用三进制应节省3个字节:i--?n%2?v*p[i]:v+p[i]
Arnauld
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.