# Alternating Sign Sequence

### Introduction

The sign of a number is either a +, or a - for every non-zero integer. Zero itself is signless (+0 is the same as -0). In the following sequence, we are going to alternate between the positive sign, the zero and the negative sign. The sequence starts with 1, so we write 1 with a positive sign, with zero (this one is weird, but we just multiply the number by 0) and the negative sign:

1, 0, -1


The next number is 2, and we do the same thing again:

2, 0, -2


The sequence eventually is:

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
...


Given a non-negative integer n, output the nth term of the above sequence. You can choose if you use the zero-indexed or one-indexed version.

### Test cases:

Zero-indexed:

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


Or if you prefer one-indexed:

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


This is , so the submission with the smallest number of bytes wins!

• Is it Ok if you start with [0, 0, 0, -1, 0, 1...
– Blue
May 28 '16 at 16:54
• @muddyfish no sorry, it has to start with 1. May 28 '16 at 16:59

# JavaScript ES6, 18 bytes

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


Turned out very similar to @LeakyNun's answer but I didn't see his until after I posted mine.

## Explanation and Ungolfed

-~ is shorthand for Math.ceil, or rounding up:

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, ...


function f(n){n=i.value;o.value=-~(n/3)*(1-n%3);}
Input: <input id=i oninput="f()"/><br /><br />
Output: <input id=o readable/>

• (I hereby attest that he did not see my solution before he posted his solution) May 28 '16 at 16:53
• Math.ceil and -~ are different; Math.ceil(1) == 1 whereas -~1 == 2 May 30 '16 at 23:26
• 1 byte shorter: n=>~(n/3)*~-(n%3) May 30 '16 at 23:31

# Jelly, 7 bytes

+6d3’PN


Zero-indexed. Test cases here.

Explanation:

+6      Add 6:     x+6
d3      Divmod:    [(x+6)/3, (x+6)%3]
’       Decrement: [(x+6)/3-1, (x+6)%3-1]
P       Product    ((x+6)/3-1) * ((x+6)%3-1)


# MarioLANG, 93 81 bytes

one-indexed

Try It Online

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


Explanation :

we begin by taking the imput

;


wich give us

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


we then decrement the left byte and increment the right byte with

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


we end up with

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


we then set up the loop

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


the loop will go until the memory look like

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


we then only need to output the result

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

• Nice! You seem to like MarioLang. May 29 '16 at 3:41
• @EasterlyIrk The feeling doesn't seem mutual from MarioLang to EtherFrog, though: ;( and >:(. Although, two times [<: could be considered slightly happy. ;P Aug 31 '16 at 14:34

# Python 2, 24 bytes

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


## Full program:

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


# MATL, 15 12 bytes

3/XkG3X\2-*_


This uses one based indexing.

Explanation:

    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

• To take care of most of the issues something like Q3/Xk-1:1G_)* may work better. It can probably be modified ever further for 1-based indexing instead. May 28 '16 at 17:55

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


Slightly more interesting 28 byte solution:

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


(Both are 0-indexed)

# MATL, 8 bytes

:t~y_vG)


The result is 1-based.

Try it online!

### Explanation

This builds the 2D array

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


and then uses linear indexing to extract the desired term. Linear indexing means index down, then across (so in the above array the first entries in linear order are 1, 0, -1, 2, 0, ...)

:     % 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


# Perl 5, 22 bytes

21 plus one for -p:

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


Uses 1-based indexing.

Explanation:

-p sets the variable $_ equal to the input. The code then sets it equal to the $_%3th element, divided by 3, of the 0-based list (-$_,$_+2) (where % is modulo). Note that if $_%3 is two, then there is no such element, and the subsequent division by 3 numifies the undefined to 0. -p then prints $_.

echo $[(1+$1/3)*(1-$1%3)]  • @DigitalTrauma, tkx, didn't know this... May 30 '16 at 18:38 # Perl 6, 26 23 bytes {({|(++$,0,--$)}...*)[$_]}
{($_ div 3+1)*(1-$_%3)}

( The shorter one was translated from other answers )

## Explanation (of the first one):

{ # 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)
}


### Test:

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

# store it lexically
' : / 3 $~ { 3 ' . % ( / ' * ! . . . . . . . . . . . .  Try it online! My first foray into Hexagony, so I'm certain I've not done this anywhere near as efficiently as it could be done... Calculates -(n%3 - 1) on one memory edge, n/3 + 1 on an adjacent one, then multiplies them together. • Wow, very interesting to see this! :) Jun 2 '16 at 20:17 # R, 28 bytes -((n=scan())%%3-1)*(n%/%3+1)  Looks like this is a variation of most of the answers here. Zero based.  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  The nice thing about it is that it handles multiple inputs > -((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 >  Originally I wanted to do the following, but couldn't trim off the extra bytes. rbind(I<-1:(n=scan()),0,-I)[n]  Uses rbind to add 0's and negatives to a range of 1 to n then return the n'th term (one based). # 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  # Batch (Windows), 86 bytes ## 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%  This program is run as Alternate.bat n where n is the number you wish to call the function on. ## APL, 12 chars -×/1-0 3⊤6+⎕  0 3⊤ is APL's divmod 3. # Java 7, 3837 36 bytes My first golf, be gentle int a(int i){return(1+i/3)*(1-i%3);}  Try it here! (test cases included) Edit: I miscounted, and also golfed off one more character by replacing (-i%3+1) with (1-i%3). • Hello, and welcome to PPCG! You can remove the space after return, and use a Java 8 lambda. Jun 23 '16 at 17:43 • I should specify that this was Java 7. I'll remove that space, though. Thanks! Jun 23 '16 at 17:47 # Retina, 45 bytes .+ 11$&$* (111)+(1)*$#2$#1 Td+0-^. ^0.+ 0  Try it online! Test suite. Takes input/output in base-ten. 1-indexed. ### Unary input, base-ten output, 1-indexed: 40 bytes $
11
(111)+(1)*
$#2$#1
Td+0-^.
^0.+
0


Try it online!

Test suite.

# MATLAB / Octave, 27 bytes

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


This creates an anonymous function that can be called using ans(n). This solution uses 1-based indexing.

All test cases

# Mathematica 26 bytes

With 4 bytes saved thanks to Martin Ender.

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


Uses the same approach as Suever.

# Octave, 23 bytes

With no mod cons...

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


Uses 1-based indexing magic.

Explanation

Creates an anonymous function that will:

(-[-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


After the multiplication step we'll have a 3xn matrix like so (for 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


Making n columns is overkill, but it's a convenient number that is guaranteed to be large enough. Linear indexing counts down each column from left to right, so the element at linear index 4 would be 2.

All test cases on ideone.

# dc, 10

?2+3~1r-*p


Uses 1-based indexing.

?              # Push input to stack
3~          # divmod by 3
1r-       # subtract remainder from 1
*      # multiply by quotient
p     # print