交互サインシーケンス


16

前書き

数値の符号は、a +、または-ゼロ以外のすべての整数に対してaです。ゼロ自体は無意味です(+0と同じです-0)。次のシーケンスでは、正符号ゼロ負符号を交互に使用します。シーケンスはで始まる1ため1、正の符号、ゼロ(これは奇妙ですが、数字に0を掛けるだけ)と負の符号で記述します。

1, 0, -1

次の番号は2で、同じことを繰り返します。

2, 0, -2

最終的なシーケンスは次のとおりです。

1, 0, -1, 2, 0, -2, 3, 0, -3, 4, 0, -4, 5, 0, -5, 6, 0, -6, 7, 0, -7, ...

または、より読みやすい形式:

a(0) = 1
a(1) = 0
a(2) = -1
a(3) = 2
a(4) = 0
a(5) = -2
a(6) = 3
a(7) = 0
a(8) = -3
a(9) = 4
...

タスク

負でない整数nが与えられた場合、上記のシーケンスのn 番目の項を出力します。あなたが使用している場合は、選択することができ、ゼロインデックスまたは1-インデックス付きのバージョンを。

テストケース:

ゼロインデックス:

a(0) = 1
a(11) = -4
a(76) = 0
a(134) = -45
a(296) = -99

または、インデックスが1つだけの場合:

a(1) = 1
a(12) = -4
a(77) = 0
a(135) = -45
a(297) = -99

これはであるため、バイト数が最小の提出が勝ちです!


あなたが始まるならそれは大丈夫ですか[0, 0, 0, -1, 0, 1...
ブルー

@muddyfish申し訳ありませんが、で始まる必要があり1ます。
アドナン

回答:



6

JavaScript ES6、18バイト

n=>-~(n/3)*(1-n%3)

@LeakyNunの答えと非常によく似ていましたが、私が私の投稿をするまでは彼に会いませんでした。

説明と未ゴルフ

-~は短縮形Math.ceil、または切り上げです:

n =>               // input in var `n`
    Math.ceil(n/3) // Get every 3rd number 1,1,1,2,2,2, etc.
    *
    (1-n%3)        // 1, 0, -1, 1, 0, -1, ...


1
(IここATTEST彼は彼のソリューションを投稿する前に、彼は私の解決策を見ていないこと)
漏れ修道女

Math.ceil-~は異なります。Math.ceil(1) == 1一方-~1 == 2
16年

1
1バイト短縮:n=>~(n/3)*~-(n%3)
16年

6

MarioLANG、93 81バイト

ワンインデックス

オンラインで試す

;(-))+(-
"============<
>:(![<:![<:)![
 !=#="!#="!=#=
!  < !-< !- <
#==" #=" #=="

説明 :

入力をとることから始めます

;

私たちにくれ

          v
... 0 0 input 0 0 ...

次に、左バイトをデクリメントし、右バイトをインクリメントします

;(-))+(
=======

で終わる

           v
... 0 -1 input +1 0 ...

次に、ループを設定します

;(-))+(-
"============<
>  ![< ![<  ![
   #=" #="  #=
!  < !-< !- <
#==" #=" #=="

メモリが次のようになるまでループが続きます

         v 
... 0 -X 0 +X 0 ...

次に、結果を出力するだけです

;(-))+(-
"============<
>:(![<:![<:)![
 !=#="!#="!=#=
!  < !-< !- <
#==" #=" #=="

2
いいね!MarioLangが好きなようです。
Rɪᴋᴇʀ

@EasterlyIrk感がけれども、MarioLangからEtherFrogに相互いないようです:;(>:(。とはいえ、2回[<:は少し幸せだと考えられます。; P
ケビンクルーイッセン

4

Python 2、24バイト

lambda n:(n/3+1)*(1-n%3)

完全なプログラム:

a=lambda n:(n/3+1)*(1-n%3)

print(a(0))   #   1
print(a(11))  #  -4
print(a(76))  #   0
print(a(134)) # -45
print(a(296)) # -99

4

MATL、15 12バイト

3/XkG3X\2-*_

これは、1ベースのインデックスを使用します。

オンラインでお試しください!またはテストケースを検証する

説明:

    G          #Input
     3X\       #Modulus, except multiples of 3 give 3 instead of 0
        2-     #Subtract 2, giving -1, 0 or 1
3/Xk           #Ceiling of input divided by 3.
          *    #Multiply 
           _   #Negate

ほとんどの問題を処理するには、次のようなものQ3/Xk-1:1G_)*が適しています。代わりに、1ベースのインデックス作成用にさらに変更することができます。
-Suever

4

Haskell、27バイト

f x=div(x+3)3*(1-mod(x+3)3)

少し興味深い28バイトのソリューション:

(((\i->[i,0,-i])=<<[1..])!!)

(両方とも0-indexed)


3

MATL、8バイト

:t~y_vG)

結果は1ベースです。

オンラインでお試しください!

説明

これにより、2D配列が構築されます

 1  2  3  4  5 ...
 0  0  0  0  0 ...
-1 -2 -3 -4 -5 ...

次に、線形インデックスを使用して目的の用語を抽出します。線形インデックス手段インデックスダウン、次に両端の(SO上記アレイ内の線形順序で最初のエントリです10-120、...)

:     % Vector [1 2 ... N], where N is implicit input
t~    % Duplicate and logical negate: vector of zeros
y_    % Duplicate array below the top and negate: vector [-1 -2 ... -N]
v     % Concatenate all stack contents vertically
G)    % Index with input. Implicit display

3

Perl 5、22バイト

21プラスワンのために-p

$_=(-$_,$_+2)[$_%3]/3

1ベースのインデックスを使用します。

説明:

-p$_入力に等しい変数を設定します。次に、コード$_%3は、0から始まるリストの3番目の要素で割った値に等しくなるように設定します(-$_,$_+2)%モジュロ)。if $_%3が2の場合、そのような要素は存在せず、後続の3での除算により、未定義が0に-pなります$_



2

Perl 6の 26の  23バイト

{({|(++$,0,--$)}...*)[$_]}
{($_ div 3+1)*(1-$_%3)}

(短い方は他の回答から翻訳されました)

説明(最初のもの):

{ # bare block with implicit parameter 「$_」
  (

    # start of sequence generator

    { # bare block
      |(  # slip ( so that it flattens into the outer sequence )
        ++$, # incrementing anon state var =>  1, 2, 3, 4, 5, 6
        0,   # 0                           =>  0, 0, 0, 0, 0, 0
        --$  # decrementing anon state var => -1,-2,-3,-4,-5,-6
      )
    }
    ...  # repeat
    *    # indefinitely

    # end of sequence generator

  )[ $_ ] # get the nth one (zero based)
}

テスト:

#! /usr/bin/env perl6
use v6.c;
use Test;

# store it lexically
my &alt-seq-sign = {({|(++$,0,--$)}...*)[$_]}
my &short-one = {($_ div 3+1)*(1-$_%3)}

my @tests = (
    0 =>   1,
   11 =>  -4,
   76 =>   0,
  134 => -45,
  296 => -99,
  15..^30  => (6,0,-6,7,0,-7,8,0,-8,9,0,-9,10,0,-10)
);

plan @tests * 2 - 1;

for @tests {
  is alt-seq-sign( .key ), .value, 'alt-seq-sign  ' ~ .gist;

  next if .key ~~ Range; # doesn't support Range as an input
  is short-one(    .key ), .value, 'short-one     ' ~ .gist;
}
1..11
ok 1 - alt-seq-sign  0 => 1
ok 2 - short-one     0 => 1
ok 3 - alt-seq-sign  11 => -4
ok 4 - short-one     11 => -4
ok 5 - alt-seq-sign  76 => 0
ok 6 - short-one     76 => 0
ok 7 - alt-seq-sign  134 => -45
ok 8 - short-one     134 => -45
ok 9 - alt-seq-sign  296 => -99
ok 10 - short-one     296 => -99
ok 11 - alt-seq-sign  15..^30 => (6 0 -6 7 0 -7 8 0 -8 9 0 -9 10 0 -10)

2

J、19 15バイト

>.@(%&3)*1-3|<:

おそらくこれをさらにゴルフする必要があります...

1インデックス付き。

ゴルフをしていない:

>> choose_sign      =: 1-3|<:      NB. 1-((n-1)%3)
>> choose_magnitude =: >.@(%&3)    NB. ceil(n/3)
>> f                =: choose_sign * choose_magnitude
>> f 1 12 77
<< 1 _4 0

Where >>は入力(STDIN)を<<意味し、output(STDOUT)を意味します。


2

Pyke、8 7バイト(旧バージョン)

3.DeRt*

ここで試してみてください! -リンクはおそらく長続きしないことに注意してください

3.D      - a,b = divmod(input, 3)
   e     - a = ~a -(a+1)
     t   - b -= 1
      *  - a = a*b
         - implicit output a

最新バージョン

3.DhRt*_

ここで試してみてください!

3.D      - a,b = divmod(input, 3)
   h     - a+=1
     t   - b-=1
      *  - a = a*b
       _ - a = -a
         - implicit output a

(旧バージョン)へのリンクを提供できますか?
Downgoat

古いコードがここで機能する最新のコミット(これは今日より早い)
ブルー

2

J、27バイト

ゴルファーではありませんが、アジェンダを使用しているので、私はそれがより好きです。

>.@(>:%3:)*1:`0:`_1:@.(3|])

以下にツリーの分解を示します。

         ┌─ >.      
  ┌─ @ ──┤    ┌─ >: 
  │      └────┼─ %  
  │           └─ 3: 
  ├─ *              
──┤           ┌─ 1: 
  │      ┌────┼─ 0: 
  │      │    └─ _1:
  └─ @. ─┤          
         │    ┌─ 3  
         └────┼─ |  
              └─ ]  

これは、大きさと記号を選択するという点でケニーのJの答えに非常に似ていますが、記号を選択するために議題を使用するという点で異なります。


2

MATL、8バイト

_3&\wq*_

このソリューションでは、シーケンスに1ベースのインデックスを使用します。

オンラインで試す

すべてのテストケースを示す修正版

説明

        % Implicitly grab the input
_       % Negate the input
3&\     % Compute the modulus with 3. The second output is floor(N/3). Because we negated
        % the input, this is the equivalent of ceil(input/3)
w       % Flip the order of the outputs
q       % Subtract 1 from the result of mod to turn [0 1 2] into [-1 0 1]
*       % Take the product with ceil(input/3)
_       % Negate the result so that the sequence goes [N 0 -N] instead of [-N 0 N]
        % Implicitly display the result

2

Pyth、10バイト

*h/Q3-1%Q3

オンラインでお試しください!

説明:

*     : Multiply following two arguments
h/Q3  : 1 + Input/3
-1%Q3 : 1 - Input%3

注:インデックスがゼロのシーケンスを想定しています。



あなたのソリューションにかなり近づきました*@(1ZtZ)%Q3h/Q3
...-FliiFe

@FliiFe (1ZtZ)=-L1 2
リーキー修道女

2

実際には、10バイト

3@│\u)%1-*

オンラインでお試しください!

説明:

3@│\u)%1-*
3@│         push 3, swap, duplicate entire stack ([n 3 n 3])
   \u)      floor division, increment, move to bottom ([n 3 n//3+1])
      %1-   mod, subtract from 1 ([1-n%3 n//3+1])
         *  multiply ([(1-n%3)*(n//3+1)])

2

05AB1E、7バイト

コード:

(3‰`<*(

説明:

(           # negate input: 12 -> -12
 3‰         # divmod by 3: [-4, 0]
   `        # flatten array: 0, -4
    <       # decrease the mod-result by 1: -1, -4
     *      # multiply: 4
      (     # negate -4

2

GeoGebra、44バイト

Element[Flatten[Sequence[{t,0,-t},t,1,n]],n]

どこn一つは、インデックスが作成されます。

説明:

Element[                      , n] # Return the nth element of the list                  .
 Flatten[                    ]     # Strip all the unnecessary braces from the list     /|\
  Sequence[{t,0,-t}, t, 1, n]      # Generate a list of lists of the form {t, 0, -t}     |
                             # This list will start with {1,0,-1} and end with {n,0,-n}  |

を介してすべてのトリプレットを生成する必要はありません{n, 0, -n}が、書き込みceil(n/3)またはその効果をもたらすものよりも短いです。nこのオブジェクトを作成するために定義する必要があることに注意してください(これが実行時に定義されていない場合、GeoGebraはのスライダーを作成するように求めますn)。


こんにちは、PPCGへようこそ!これをテストできるリンクがありますか(できればオンライン)。
Rɪᴋᴇʀ

@EᴀsᴛᴇʀʟʏIʀᴋ、ありがとう!オンラインアプレットの事へのリンクは次のとおりです。ページはしばらくの間空白に見えましたが、その後表示されました。
ジョー

かっこいい、イケてる。しかし、どのように式に入れますか?> _>空白に貼り付けようとしましたが、スライダーを作成するように促されましたが、他には何も起こりませんでした。
Rɪᴋᴇʀ

@EᴀsᴛᴇʀʟʏIʀᴋ:左側の「入力...」と書かれた部分に、最初に、初期化するためにn、次のように入力しますn=297(これにより、適切に構成されたスライダーが表示されます)。次に、入力ボックスに数式を貼り付けます。入力ボックスはの下にあるはずnです。(必ずreturnをn押してください。)数式はシーケンスのth項まで評価され、スライダーを動かすと変化するはずです。
ジョー

2

ラビリンス17 15 14バイト

1-(n%3)代わりに使用するSokのアイデアを使用して3バイトを保存しました~(n%3-2)

1?:#/)}_3%-{*!

プログラムはエラー(ゼロ除算)で終了しますが、エラーメッセージはSTDERRに送られます。

オンラインでお試しください!

説明

プログラムは完全に線形ですが、一部のコードは最後に逆に実行されます。

1     Turn top of stack into 1.
?:    Read input as integer and duplicate.
#     Push stack depth (3).
/)    Divide and increment.
}     Move over to auxiliary stack.
_3%   Take other copy modulo 3.
-     Subtract from 1. This turns 0, 1, 2 into 1, 0, -1, respectively.
{*    Move other value back onto main stack and multiply.
!     Output as integer.

命令ポインタは行き止まりにぶつかり、向きを変えるので、最後からコードの実行を開始します。

*     Multiply two (implicit) zeros.
{     Pull an (implicit) zero from the auxiliary to the main stack.
-     Subtract two (implicit) zeros from one another.
      Note that these were all effectively no-ops due to the stacks which are
      implicitly filled with zeros.
%     Attempt modulo, which terminates the program due to a division-by-zero error.

2

アーラン、40バイト

F=fun(N)->trunc((N/3+1)*(1-N rem 3))end.

悲しいことに、Erlangには「%」モジュロ演算子がなく、「rem」には3の前でもスペースが必要です。


2

六角形、25バイト

?'+}@/)${':/3$~{3'.%(/'*!

または、縮小されていない形式の場合:

    ? ' + }
   @ / ) $ {
  ' : / 3 $ ~
 { 3 ' . % ( /
  ' * ! . . .
   . . . . .
    . . . .

オンラインでお試しください!

初めて六角形に進出したので、できる限り効率的にこれをやったことがないと確信しています...

-(n%3 - 1)1つのメモリエッジとn/3 + 1隣接するメモリエッジで計算し、それらを乗算します。


うわー、これを見て非常に興味深い!:)
アドナン

2

R、28バイト

-((n=scan())%%3-1)*(n%/%3+1)

これは、ほとんどの回答のバリエーションであるようです。ゼロベース。

   n=scan()                  # get input from STDIN
  (        )%%3-1            # mod by 3 and shift down (0,1,2) -> (-1,0,1)
-(               )           # negate result (1,0,-1), this handles the alternating signs
                  *(n%/%3+1) # integer division of n by 3, add 1, multiply by previous

それの良いところは、複数の入力を処理することです

> -((n=scan())%%3-1)*(n%/%3+1)
1: 0 3 6 9 1 4 7 10 2 5 8 11
13: 
Read 12 items
 [1]  1  2  3  4  0  0  0  0 -1 -2 -3 -4
> 

もともと私は次のことをしたかったのですが、余分なバイトを削除できませんでした。

rbind(I<-1:(n=scan()),0,-I)[n]

を使用rbindして0の値と負の値を1の範囲に追加しnn「th」項(1ベース)を返します。

# for n = 5
rbind(                    )    # bind rows 
            n=scan()           # get input from STDIN and assign to n
      I<-1:(        )          # build range 1 to n and assign to I
                     ,0        # add a row of zeros (expanded automatically)
                       ,-I     # add a row of negatives
                           [n] # return the n'th term

2

バッチ(Windows)、86バイト

Alternate.bat

SET /A r=%1%%3
SET /A d=(%1-r)/3+1
IF %r%==0 ECHO %d%
IF %r%==1 ECHO 0
IF %r%==2 ECHO -%d%

このプログラムは次のように実行されます Alternate.bat nn、関数を呼び出す番号がどこにあるかとしてれます。



2

Java 7、38 37 36バイト

私の最初のゴルフ、穏やかに

int a(int i){return(1+i/3)*(1-i%3);}

ここで試してみてください!(テストケースが含まれています)

編集:私は誤って数え、またに置き換え(-i%3+1)てもう1人のキャラクターをゴルフにかけ(1-i%3)


1
こんにちは、PPCGへようこそ!後returnにスペースを削除し、Java 8ラムダを使用できます。
-NoOneIsHere

これはJava 7であることを指定する必要がありますが、そのスペースは削除します。ありがとう!
スティーブンH.


1

MATLAB /オクターブ、27バイト

@(n)ceil(n/3)*(mod(-n,3)-1)

これにより、を使用して呼び出すことができる匿名関数が作成されans(n)ます。このソリューションは、1ベースのインデックスを使用します。

すべてのテストケース


1

Mathematica 26バイト

Martin Enderのおかげで4バイトが節約されました。

⎡#/3⎤(-#~Mod~3-1)&

Sueverと同じアプローチを使用します。


1

オクターブ、23バイト

mod consなしで...

@(n)(-[-1:1]'*[1:n])(n)

1ベースのインデックスマジックを使用します。


説明

以下を行う匿名関数を作成します。

(-[-1:1]'*[1:n])(n)
  [-1:1]              % make a row vector [-1 0 1]
 -      '             % negate and take its transpose making a column vector
          [1:n]       % make a row vector [1..n], where n is the input
         *            % multiply with singleton expansion
               (n)    % use linear indexing to get the nth value

乗算ステップの後、次のような3xn行列ができます(n = 12の場合):

 1    2    3    4    5    6    7    8    9   10   11   12
 0    0    0    0    0    0    0    0    0    0    0    0
-1   -2   -3   -4   -5   -6   -7   -8   -9  -10  -11  -12

n列の作成はやり過ぎですが、十分な大きさであることが保証されている便利な数です。線形インデックスは各列を左から右にカウントダウンするため、線形インデックスの要素は次の4ようになります。2

イデオンのすべてのテストケース。


1

DC、10

?2+3~1r-*p

1ベースのインデックスを使用します。

?              # Push input to stack
 2+            # Add 2
   3~          # divmod by 3
     1r-       # subtract remainder from 1
        *      # multiply by quotient
         p     # print
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.