제로섬 카운팅


25

n ≥ 1 이 주어지면 솔루션 수를 ± 1 ± 2 ± 3 ± ... ± n = 0으로 되 돌리는 프로그램 또는 함수를 작성하십시오 .

n = 6의 경우 해가 없으므로 답은 0입니다. n = 4의 경우 해가 두 개이므로 답은 2입니다 (두 해는 1-2-3 + 4 = -1 + 2 + 3-4입니다). = 0).

OEIS 시퀀스 A063865 입니다. 입력 / 출력 예제는 다음과 같습니다.

n       a(n)
1       0
2       0
3       2
4       2
5       0
6       0
7       8
8       14
9       0
10      0
11      70
12      124
13      0
14      0
15      722
16      1314

바이트 단위의 최단 코드가 이깁니다.



1
@ManishKundu 흠, 나에게 가능한 속임수 대상처럼 보입니다. 끝에 "길이"를 붙이거나 "합계로 필터"대신 "sum each then count"를 수행하여 이에 대한 답을 얻으십시오. .
Outgolfer Erik

2
@EriktheOutgolfer 나는 그 도전을 알지 못했지만 이것에 대한 대답은 실질적으로 다를 수 있습니다. 예를 들어 내 것을보십시오.
orlp

2
@ManishKundu 방금이 도전이 어떻게 다른지 설명했습니다.
orlp

2
네, 봤어요 불행히도 자신의 질문 을 실수 로 망치는 것은 아니지만 동의하지 않는 투표를하도록 강요해서는 안됩니다.
Dennis

답변:






5

C (gcc), 45 62 52 50 바이트

f(n,r){n=n?f(n-1,r+n)+f(n-1,r-n):!r;}F(n){f(n,0);}

Kevin Cruijssen 항의 Java 8 답변 .

여기에서 온라인으로 사용해보십시오 .

주석에서 제안 된 개선 사항으로 인해 코드는 clang으로 컴파일 할 때 작동하지 않는 지점까지 정의되지 않은 동작을 생성합니다.

3 바이트 골프를위한 etene 에게 감사 합니다. 10 바이트 더 골프를 해준 Kevin Cruijssen 에게 감사 합니다. 2 바이트 더 골프 해 준 Christoph 에게 감사드립니다 .

언 골프 버전 :

f(n, r) { // recursive function - return type and parameter type are omitted, they default to int
    n = // instead of returning, we set n - dirty trick
        n ? // if n is not 0, recurse
        f(n-1,r+n) // +n
       +f(n-1,r-n) // -n
        !r; // else if r != 0 return 0 else return 1
}
F(n) { // function to start the recursion; again implicitly int(int)
    n = f(n, 0); // call the recursive function; this time we simply don't return
}

1
로 교체 r?0:1하여 3 바이트를 줄일 수 !r있습니다. 42 바이트
etene

2
초기 값을 설정하기 위해 추가 입력을받는 것 같습니다 r. 허용되지 않습니다.
Shaggy

1
@etene 잘 발견, 감사합니다!
OOBalance

2
@KevinCruijssen 더 나은 아직 두 번째 n=는 필요하지 않습니다 : f(n,r){n=n?f(n-1,r+n)+f(n-1,r-n):!r;}F(n){f(n,0);}.
Christoph

2
@OOBalance 트릭은 2의 보수 입니다. 이 의미 -x = ~x+1하기 때문에 ~x = -x-1.
Christoph

5

05AB1E , 9 8 바이트

바이트를 저장해 준 Emigna 에게 감사합니다 !

암호:

LæO·sLO¢

05AB1E 인코딩을 사용합니다 . 온라인으로 사용해보십시오!

설명

L           # Create the list [1, 2, .., input]
 æ          # Compute the powerset of this list
  O         # Sum each list
   ·        # Double each element
    sLO     # Compute the sum of [1, 2, .., input]
       ¢    # Count the number of occurrences

4

MATL , 14 13 바이트

[la]Z^G:!Y*~s

1 바이트를 절약 한 @Giuseppe 에게 감사드립니다 !

온라인으로 사용해보십시오! 또는 모든 테스트 사례를 확인하십시오 .

설명

고려 n = 3예를 들어. 스택이 거꾸로 표시됩니다. 즉, 최신이 아래에 나타납니다.

[la]   % Push array [1 -1]
       % STACK: [1 -1]
Z^     % Cartesian power with inplicit input n
       % STACK: [ 1  1  1
                  1  1 -1
                  1 -1  1
                  1 -1 -1
                 -1  1  1
                 -1  1 -1
                 -1 -1  1
                 -1 -1 -1]
G:     % Push n, range: gives [1 2 ... n]
       % STACK: [ 1  1  1
                  1  1 -1
                  1 -1  1
                  1 -1 -1
                 -1  1  1
                 -1  1 -1
                 -1 -1  1
                 -1 -1 -1],
                 [1  2  3]
!      % Transpose
       % STACK: [ 1  1  1
                  1  1 -1
                  1 -1  1
                  1 -1 -1
                 -1  1  1
                 -1  1 -1
                 -1 -1  1
                 -1 -1 -1],
                 [1
                  2
                  3]
Y*     % Matrix multiplication
       % STACK: [6
                 0
                 2
                -4
                 4
                -2
                 0
                -6]
~      % Logical negation
       % STACK: [0
                 1
                 0
                 0
                 0
                 0
                 1
                 0]
s      % Sum of vector. Implicit display
       % STACK: 2

4

젤리 , 8 바이트

ŒPS€ċÆṁ$

온라인으로 사용해보십시오!

작동 원리

ŒPS€ċÆṁ$  Main link. Argument: n

ŒP        Take the powerset of [1, ..., n].
  S€      Take the sum of each subset.
       $  Combine the two links to the left into a monadic chain.
     Æṁ       Compute the median of the sums, i.e, (1 + ... + n)/2.
    ċ         Count the occurrences of the median.

3

파이썬 2, 74 바이트

def f(n):l=k=1;exec"l+=l<<n*k;k+=1;"*n;return(l>>n*n*-~n/4)%2**n*(~-n%4>1)

더 재미있는 제출, ​​직접 생성 함수 계산.


3

옥타브 (통신 패키지 포함), 39 바이트

@(n)sum((2*de2bi(0:2^n-1)-1)*(1:n)'==0)

온라인으로 사용해보십시오!

설명:

0 ... n ^ 2-1 의 범위를 취하여 이진수로 변환하십시오. 이것은 01 의 모든 조합을 가진 행렬을 제공합니다 . 곱해 2 및 빼기 1 의 모든 조합 매트릭스 얻을 -1+1을 .

± 1 ± 2 ... ± n 의 모든 조합을 얻으려면 1 ... n 범위의 내적을 구하십시오 . 0이 몇 개인 지 세십시오.

기본적으로 같은 바이트 수 :

@(n)nnz(~((2*de2bi(0:2^n-1)-1)*(1:n)'))


3

파이썬 2와 3, 50 바이트

대부분의 답변과 같은 재귀 접근법 :

f=lambda n,r=0:f(n-1,r+n)+f(n-1,r-n)if n else r==0

온라인으로 사용해보십시오

이중 재귀 호출에 너무 많은 바이트가 필요합니다.이를 단순화하는 방법이있을 것입니다.


3

자바 8, 72 71 70 바이트

n->f(0,n)int f(int r,int n){return n>0?f(r+n,--n)+f(r+~n,n):r==0?1:0;}

@Arnauld 의 JavaScript (ES6) 답변 포트 . @ OlivierGrégoire
덕분에 -2 바이트 .

온라인으로 사용해보십시오.

설명:

n->                 // Method with integer parameter and integer return-type
  f(0,n)            //  Call the recursive method with 0 and this parameter

int f(int r,int n){ // Recursive method with integer as both two parameters and return-type
  return n>0?       //  If `n` is not 0 yet:
    f(r+n,--n)      //   Recursive call with `r+n` (and `n` lowered by 1 first with `--n`)
    +f(r+~n,n)      //   + Recursive call with `r-n` (and `n` also lowered by 1)
   :r==0?           //  Else-if `r` is 0
     1              //   Return 1
    :               //  Else:
     0;}            //   Return 0



3

Brachylog , 12 바이트

⟦₁{{ṅ|}ᵐ+0}ᶜ

온라인으로 사용해보십시오!

설명

⟦₁               The range [1, …, Input]
  {       }ᶜ     Count the number of times the following predicate succeeds on that range:
   {  }ᵐ           Map for each element of the range:
    ṅ                Negate
     |               Or do nothing
        +0         The sum of the elements after the map is 0








1

Pyth, 14 13 바이트

lf!s.nT*F_BRS

여기 사용해보십시오

설명

lf!s.nT*F_BRS
            SQ  Take the list [1, ..., <implicit input>].
         _BR    Get the pairs [[1, -1], [2, -2], ...].
       *F       Take the Cartesian product.
 f!s.nT         Find the ones where the flattened sum is 0.
l               Take the length.


1

Stax , 9 바이트

è%é┐╬@₧╠¬

실행 및 디버깅

젤리에 의해 지금까지 가장 짧은 답변 중 하나입니다 .

명시 적으로 어떤 부호의 합계가 0인지를 확인하는 것은 그리 골치 아픈 것이 아니라고 생각합니다. 대신 파워 세트를 가져 와서 파워 세트의 몇 세트가 n 번째 삼각 수의 절반의 합계인지 확인합니다. 이 방법은 놀랍게도 어떤 부호가 0인지 확인하는 것과 같은 시간 복잡성입니다.

ASCII 상응 :

RS{|+Hmx|+#


0

J , 28 바이트

(*>:){1j3#1+//.@(*/)/@,.=@i.

OEIS의 다른 정의를 사용합니다 a(n) = coefficient of x^(n(n+1)/4) in Product_{k=1..n} (1+x^k) if n = 0 or 3 mod 4 else a(n) = 0.

온라인으로 사용해보십시오!

설명

(*>:){1j3#1+//.@(*/)/@,.=@i.  Input: n
                          i.  Range [0, n)
                        =     Self-Classify. Forms an identity matrix of order n
          1           ,.      Stitch. Prepend 1 to each row
                    /         Reduce using
                                Convolution
                 */               Product table
           +//.                   Sum along anti-diagonals
      1j3#                    Copy each once, padding with 3 zeroes after
     {                        Index at n*(n+1)
  >:                            Increment n
 *                              Times n


0

Gol> <> , 26 바이트

:IFPlMF2K+}:@-}||0lMF$z+|h

온라인으로 사용해보십시오! 또는 1에서 16까지 테스트 사례를 실행하십시오!

작동 원리

:IFPlMF2K+}:@-}||0lMF$z+|h

Main outer loop
:IFPlMF ...... ||
:        Duplicate top; effectively generate two explicit zeroes
         Top is the loop counter `i`;
         the rest is the generated 2**i sums
 I       Take input as number
  F ........... |  Pop n and loop n times
   P     i++
    lM   Push stack length - 1, which is 2**(i-1)
      F ...... |   Loop 2**(i-1) times

Main inner loop: generate +i and -i from 2**(i-1) previous sums
2K+}:@-}
          Stack: [... x i]
2K        [... x i x i]    Copy top two
  +}      [x+i ... x i]    Add top two and move to the bottom
    :@    [x+i ... i i x]  Duplicate top and rotate top 3
      -}  [i-x x+i ... i]  Subtract and move to the bottom

Counting zeroes
0lMF$z+|h
0lM        Push zero (zero count) and 2**n (loop count)
   F...|   Loop 2**n times
    $z+    Swap top two; Take logical not; add to the count
        h  Print top as number and halt
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.