문제

목록 목록을 생성하십시오 (또는 인쇄, 나는 신경 쓰지 않습니다) 파스칼의 삼각형 최소한의 코드 라인이있는 크기 N!

여기에 내 시도가 있습니다 (118 자 파이썬 2.6 사용 트릭):

c,z,k=locals,[0],'_[1]'
p=lambda n:[len(c()[k])and map(sum,zip(z+c()[k][-1],c()[k][-1]+z))or[1]for _ in range(n)]

설명:

  • 목록 이해력의 첫 번째 요소 (길이가 0 일 때)는 다음과 같습니다. [1]
  • 다음 요소는 다음과 같은 방법으로 얻습니다.
  • 이전 목록을 가져 와서 두 개의 목록을 작성하십시오. 하나는 처음에 0으로 패딩하고 다른 하나는 끝에 있습니다.
    • 예를 들어 두 번째 단계를 위해 우리는 가져갑니다 [1] 그리고 만듭니다 [0,1] 그리고 [1,0]
  • 두 개의 새로운 목록 요소를 요소별로 합산하십시오
    • 예를 들어 새 목록을 만듭니다 [(0,1),(1,0)] 그리고 합계로지도.
  • N 시간을 반복하면 그게 전부입니다.

사용법 (실제로 코드 골프 XD에서 인쇄, 실제로 인쇄) : :

result = p(10)
lines = [" ".join(map(str, x)) for x in result]
for i in lines:
    print i.center(max(map(len, lines)))

산출:

             1             
            1 1            
           1 2 1           
          1 3 3 1          
         1 4 6 4 1         
       1 5 10 10 5 1       
      1 6 15 20 15 6 1     
    1 7 21 35 35 21 7 1    
   1 8 28 56 70 56 28 8 1  
1 9 36 84 126 126 84 36 9 1
도움이 되었습니까?

해결책

제이, APL 가족의 다른 언어, 9 자 :

p=:!/~@i.

이것은 J의 내장 "조합"동사를 사용합니다.

산출:

   p 10
1 1 1 1 1  1  1  1  1   1
0 1 2 3 4  5  6  7  8   9
0 0 1 3 6 10 15 21 28  36
0 0 0 1 4 10 20 35 56  84
0 0 0 0 1  5 15 35 70 126
0 0 0 0 0  1  6 21 56 126
0 0 0 0 0  0  1  7 28  84
0 0 0 0 0  0  0  1  8  36
0 0 0 0 0  0  0  0  1   9
0 0 0 0 0  0  0  0  0   1

다른 팁

케이 (위키 백과), 15 자 :

p:{x{+':x,0}\1}

예제 출력 :

  p 10
(1
 1 1
 1 2 1
 1 3 3 1
 1 4 6 4 1
 1 5 10 10 5 1
 1 6 15 20 15 6 1
 1 7 21 35 35 21 7 1
 1 8 28 56 70 56 28 8 1
 1 9 36 84 126 126 84 36 9 1
 1 10 45 120 210 252 210 120 45 10 1)

또한 쉽게 설명됩니다.

p:{x {+':x,0} \ 1}
   ^ ^------^ ^ ^
   A    B     C D
  • p 암시 적 매개 변수를 취하는 함수입니다 x.

  • p 전개 (c) 익명 기능 (b) x 시간 (a)에서 시작합니다 1 (디).

  • 익명 함수는 단순히 목록을 가져옵니다 x, 추가 0 추가하여 결과를 반환합니다 (+) 각 인접한 쌍 (':)의 값 : 예를 들어, 시작 (1 2 1), 그것은 생산할 것입니다 (1 2 1 0), 쌍을 추가하십시오 (1 1+2 2+1 1+0), 기부 (1 3 3 1).


업데이트: K4에 적응하여 또 다른 두 캐릭터를 깎습니다. 참고로 원래 K3 버전은 다음과 같습니다.

p:{x{+':0,x,0}\1}

Haskell, 58 자 :

r 0=[1]
r(n+1)=zipWith(+)(0:r n)$r n++[0]
p n=map r[0..n]

산출:

*Main> p 5
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10,10,5,1]]

더 읽기 쉬운 :

-- # row 0 is just [1]
row 0     = [1]
-- # row (n+1) is calculated from the previous row
row (n+1) = zipWith (+) ([0] ++ row n) (row n ++ [0])
-- # use that for a list of the first n+1 rows
pascal n  = map row [0..n]

C에서 69C :

f(int*t){int*l=t+*t,*p=t,r=*t,j=0;for(*t=1;l<t+r*r;j=*p++)*l++=j+*p;}

그렇게 사용하십시오.

int main()
{
#define N 10
    int i, j;
    int t[N*N] = {N};

    f(t);

    for (i = 0; i < N; i++)
    {
        for (j = 0; j <= i; j++)
            printf("%d ", t[i*N + j]);
        putchar('\n');
    }
    return 0;
}

에프#: 81 숯

let f=bigint.Factorial
let p x=[for n in 0I..x->[for k in 0I..n->f n/f k/f(n-k)]]

설명 : 나는 Haskell과 K 프로그래머만큼 영리하기에는 너무 게으르기 때문에 간단한 경로를 가져갔습니다. Pascal의 삼각형의 각 요소는 Row N과 Col K를 사용하여 고유하게 식별 할 수 있습니다. 각 요소의 값은 다음과 같습니다. n!/(k! (n-k)!.

파이썬 : 75 자

def G(n):R=[[1]];exec"R+=[map(sum,zip(R[-1]+[0],[0]+R[-1]))];"*~-n;return R

짧은 프롤로그 버전 (164 대신 112) :

n([X],[X]).
n([H,I|T],[A|B]):-n([I|T],B),A is H+I.
p(0,[[1]]):-!.
p(N,[R,S|T]):-O is N-1,p(O,[S|T]),n([0|S],R).

또 다른 찌르기 (파이썬) :

def pascals_triangle(n):
    x=[[1]]
    for i in range(n-1):
        x.append(list(map(sum,zip([0]+x[-1],x[-1]+[0]))))
    return x

Haskell, 164c 형식 :

i l=zipWith(+)(0:l)$l++[0]
fp=map (concatMap$(' ':).show)f$iterate i[1]
c n l=if(length l<n)then c n$' ':l++" "else l
cl l=map(c(length$last l))l
pt n=cl$take n fp

서식없이 52c :

i l=zipWith(+)(0:l)$l++[0]
pt n=take n$iterate i[1]

더 읽기 쉬운 형태 :

iterateStep row = zipWith (+) (0:row) (row++[0])
pascalsTriangle n = take n $ iterate iterateStep [1]

-- For the formatted version, we reduce the number of rows at the final step:
formatRow r = concatMap (\l -> ' ':(show l)) r
formattedLines = map formatRow $ iterate iterateStep [1]
centerTo width line =
    if length line < width
        then centerTo width (" " ++ line ++ " ")
        else line
centerLines lines = map (centerTo (length $ last lines)) lines
pascalsTriangle n = centerLines $ take n formattedLines

및 Perl, 111C, 중심 없음 :

$n=<>;$p=' 1 ';for(1..$n){print"$p\n";$x=" ";while($p=~s/^(?= ?\d)(\d* ?)(\d* ?)/$2/){$x.=($1+$2)." ";}$p=$x;}

체계 - 100 자의 압축 버전

(define(P h)(define(l i r)(if(> i h)'()(cons r(l(1+ i)(map +(cons 0 r)(append r '(0))))))(l 1 '(1)))

이것은 더 읽기 쉬운 형태 (269 자)입니다.

(define (pascal height)
  (define (next-row row)
    (map +
         (cons 0 row)
         (append row '(0))))

  (define (iter i row)
    (if (> i height)
        '()
        (cons row
              (iter (1+ i)
                    (next-row row)))))

  (iter 1 '(1)))

VBA/VB6 (392 chars w/ smatting)

Public Function PascalsTriangle(ByVal pRows As Integer)

Dim iRow As Integer
Dim iCol As Integer
Dim lValue As Long
Dim sLine As String

  For iRow = 1 To pRows
    sLine = ""
    For iCol = 1 To iRow
      If iCol = 1 Then
        lValue = 1
      Else
        lValue = lValue * (iRow - iCol + 1) / (iCol - 1)
      End If
      sLine = sLine & " " & lValue
    Next
    Debug.Print sLine
  Next

End Function

PHP 100 자

$v[]=1;while($a<34){echo join(" ",$v)."\n";$a++;for($k=0;$k<=$a;$k++)$t[$k]=$v[$k-1]+$v[$k];$v=$t;}

루비, 83C :

def p(n);n>0?(m=p(n-1);k=m.last;m+[([0]+k).zip(k+[0]).map{|x|x[0]+x[1]}]):[[1]];end

테스트:

irb(main):001:0> def p(n);n>0?(m=p(n-1);k=m.last;m+[([0]+k).zip(k+[0]).map{|x|x[0]+x[1]}]):[[1]];end
=> nil
irb(main):002:0> p(5)
=> [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]]
irb(main):003:0> 

또 다른 파이썬 솔루션, 내장 기능의 이름이 짧은 경우 훨씬 짧을 수 있습니다 ... 106 캐릭터.

from itertools import*
r=range
p=lambda n:[[len(list(combinations(r(i),j)))for j in r(i+1)]for i in r(n)]

또 다른 시도 프롤로그 (나는 XD를 연습하고 있습니다) 너무 짧지 않습니다.

s([],[],[]).
s([H|T],[J|U],[K|V]):-s(T,U,V),K is H+J.
l([1],0).
l(P,N):-M is N-1,l(A,M),append(A,[0],B),s(B,[0|A],P).
p([],-1).
p([H|T],N):-M is N-1,l(H,N),p(T,M).

설명:

  • s = 합계는 요소 별 요소를 나열합니다
  • l = 삼각형의 n 번째 줄
  • p = 크기 n의 전체 삼각형 n

VBA, 122 숯 :

Sub p(n)
For r = 1 To n
l = "1"
v = 1
For c = 1 To r - 1
v = v / c * (r - c)
l = l & " " & v
Next
Debug.Print l
Next
End Sub

몇 년 전에이 C ++ 버전을 썼습니다.

#include <iostream>
int main(int,char**a){for(int b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0;b<atoi(a[1]);(d|f|h)>1?e*=d>1?--d:1,g*=f>1?--f:1,i*=h>1?--h:1:((std::cout<<(i*g?e/(i*g):1)<<" "?d=b+=c++==b?c=0,std::cout<<std::endl?1:0:0,h=d-(f=c):0),e=d,g=f,i=h));}

다음은 a를 반환하는 스칼라 함수입니다 List[List[Int]]. 예쁜 인쇄 나 아무것도 없습니다. 제안 된 개선이 있습니까? (비효율적이라는 것을 알고 있지만 지금은 주요 도전이 아닙니다.). 145 C.

def p(n: Int)={def h(n:Int):List[Int]=n match{case 1=>1::Nil;case _=>(0::h(n-1) zipAll(h(n-1),0,0)).map{n=>n._1+n._2}};(1 to n).toList.map(h(_))}

또는 아마도 :

def pascal(n: Int) = {
  def helper(n: Int): List[Int] = n match {
    case 1 => 1 :: List()
    case _ => (0 :: helper(n-1) zipAll (helper(n-1),0,0)).map{ n => n._1 + n._2 }
  }
  (1 to n).toList.map(helper(_))
}

(저는 스칼라 멍청이이므로 나에게 친절 해주세요 : D)

Perl 버전 (139 chars w/o shebang)

@p = (1,1);
while ($#p < 20) {
    @q =();
    $z = 0;
    push @p, 0;
    foreach (@p) {
        push @q, $_+$z;
        $z = $_
    }
    @p = @q;
    print "@p\n";
}

출력은 1 2 1부터 시작합니다

PHP, 115 숯

$t[][]=1;
for($i=1;$i<$n;++$i){
$t[$i][0]=1;
for($j=1;$j<$i;++$j)$t[$i][$j]=$t[$i-1][$j-1]+$t[$i-1][$j];
$t[$i][$i]=1;}

Print_r ()가 출력 배열을 올바른 순서로 표시하는지 여부를 신경 쓰지 않으면 113 숯으로 면도 할 수 있습니다.

$t[][]=1;
for($i=1;$i<$n;++$i){
$t[$i][0]=$t[$i][$i]=1;
for($j=1;$j<$i;++$j)$t[$i][$j]=$t[$i-1][$j-1]+$t[$i-1][$j];}

Perl, 63 자 :

for(0..9){push@z,1;say"@z";@z=(1,map{$z[$_-1]+$z[$_]}(1..$#z))}

C ++에서의 나의 시도 (378c). 나머지 게시물만큼 좋은 곳은 아닙니다.

int* pt(int n)
{
  int s=n*(n+1)/2;
  int* t=new int[s];

  for(int i=0;i<n;++i)
    for(int j=0;j<=i;++j)
      t[i*n+j] = (!j || j==i) ? 1 : t[(i-1)*n+(j-1)] + t[(i-1)*n+j];
  return t;
}

int main()
{
  int n,*t;
  std::cin>>n;
  t=pt(n);

  for(int i=0;i<n;++i)
  {
    for(int j=0;j<=i;j++)
      std::cout<<t[i*n+j]<<' ';
    std::cout<<"\n";
  }
}

오래된 스레드이지만 오늘 다른 포럼에서 도전에 응답하여 이것을 썼습니다.

def pascals_triangle(n):
    x=[[1]]
    for i in range(n-1):
        x.append([sum(i) for i in zip([0]+x[-1],x[-1]+[0])])
    return x

for x in pascals_triangle(5):
    print('{0:^16}'.format(x))

      [1]       
     [1, 1]     
   [1, 2, 1]    
  [1, 3, 3, 1]  
[1, 4, 6, 4, 1]
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top