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, ...
Or a more readable form:
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
...
The Task
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 code-golf, so the submission with the smallest number of bytes wins!
54 Answers 54
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)
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/>
-
2\$\begingroup\$ (I hereby attest that he did not see my solution before he posted his solution) \$\endgroup\$Leaky Nun– Leaky Nun2016年05月28日 16:53:41 +00:00Commented May 28, 2016 at 16:53
-
\$\begingroup\$
Math.ceiland-~are different;Math.ceil(1) == 1whereas-~1 == 2\$\endgroup\$Cyoce– Cyoce2016年05月30日 23:26:26 +00:00Commented May 30, 2016 at 23:26 -
1\$\begingroup\$ 1 byte shorter:
n=>~(n/3)*~-(n%3)\$\endgroup\$Cyoce– Cyoce2016年05月30日 23:31:05 +00:00Commented May 30, 2016 at 23:31
MarioLANG, (削除) 93 (削除ここまで) 81 bytes
one-indexed
;(-))+(-
"============<
>:(![<:![<:)![
!=#="!#="!=#=
! < !-< !- <
#==" #=" #=="
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
;(-))+(-
"============<
>:(![<:![<:)![
!=#="!#="!=#=
! < !-< !- <
#==" #=" #=="
-
2\$\begingroup\$ Nice! You seem to like MarioLang. \$\endgroup\$Riker– Riker2016年05月29日 03:41:02 +00:00Commented May 29, 2016 at 3:41
-
\$\begingroup\$ @EasterlyIrk The feeling doesn't seem mutual from MarioLang to EtherFrog, though:
;(and>:(. Although, two times[<:could be considered slightly happy. ;P \$\endgroup\$Kevin Cruijssen– Kevin Cruijssen2016年08月31日 14:34:40 +00:00Commented Aug 31, 2016 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/XkG3X2円-*_
This uses one based indexing.
Try it online! or verify test cases
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
-
\$\begingroup\$ 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. \$\endgroup\$Suever– Suever2016年05月28日 17:55:51 +00:00Commented May 28, 2016 at 17:55
Haskell, 27 bytes
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.
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 $_.
05AB1E, 7 bytes
Code:
(3‰`<*(
Explained:
( # 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
Bash, (削除) 28 (削除ここまで) 25 Bytes
echo $[(1+1ドル/3)*(1-1ドル%3)]
-
\$\begingroup\$ @DigitalTrauma, tkx, didn't know this... \$\endgroup\$rexkogitans– rexkogitans2016年05月30日 18:38:37 +00:00Commented May 30, 2016 at 18:38
Hexagony, 25 bytes
?'+}@/)${':/3$~{3'.%(/'*!
Or, in non-minified format:
? ' + }
@ / ) $ {
' : / 3 $ ~
{ 3 ' . % ( /
' * ! . . .
. . . . .
. . . .
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.
-
\$\begingroup\$ Wow, very interesting to see this! :) \$\endgroup\$Adnan– Adnan2016年06月02日 20:17:26 +00:00Commented Jun 2, 2016 at 20:17
APL, 12 chars
×ばつ/1-0 3⊤6+⎕
0 3⊤ is APL's divmod 3.
Retina, 45 bytes
.+
11$&$*
(111)+(1)*
$#2$#1
T`d`+0-`^.
^0.+
0
Takes input/output in base-ten. 1-indexed.
Unary input, base-ten output, 1-indexed: 40 bytes
$
11
(111)+(1)*
$#2$#1
T`d`+0-`^.
^0.+
0
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
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)
J, (削除) 19 (削除ここまで) 15 bytes
>.@(%&3)*1-3|<:
Probably need to golf this further...
1-indexed.
Ungolfed:
>> 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 >> means input (STDIN) and << means output (STDOUT).
Pyke, (削除) 8 (削除ここまで) 7 bytes (old version)
3.DeRt*
Try it here! - Note that link probably won't last for long
3.D - a,b = divmod(input, 3)
e - a = ~a -(a+1)
t - b -= 1
* - a = a*b
- implicit output a
Newest version
3.DhRt*_
3.D - a,b = divmod(input, 3)
h - a+=1
t - b-=1
* - a = a*b
_ - a = -a
- implicit output a
-
\$\begingroup\$ Can you provide a link to the (old version) \$\endgroup\$Downgoat– Downgoat2016年05月28日 17:09:40 +00:00Commented May 28, 2016 at 17:09
-
J, 27 bytes
Whilst not the golfiest, I like it better, as it uses an agenda.
>.@(>:%3:)*1:`0:`_1:@.(3|])
Here is the tree decomposition of it:
┌─ >.
┌─ @ ──┤ ┌─ >:
│ └────┼─ %
│ └─ 3:
├─ *
──┤ ┌─ 1:
│ ┌────┼─ 0:
│ │ └─ _1:
└─ @. ─┤
│ ┌─ 3
└────┼─ |
└─ ]
This is very similar to Kenny's J answer, in that it chooses the magnitude and sign, but it's different in that I use an agenda to choose the sign.
MATL, 8 bytes
_3&\wq*_
This solution uses 1-based indexing into the sequence.
Modified version showing all test cases
Explanation
% 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
Pyth, 10 bytes
*h/Q3-1%Q3
Explanation:
* : Multiply following two arguments
h/Q3 : 1 + Input/3
-1%Q3 : 1 - Input%3
Note: I've assumed the zero-indexed sequence.
-
1\$\begingroup\$ You would probably like to include this link. Also, welcome to PPCG! \$\endgroup\$Leaky Nun– Leaky Nun2016年05月29日 02:46:09 +00:00Commented May 29, 2016 at 2:46
-
\$\begingroup\$ I got quite close to your solution...
*@(1ZtZ)%Q3h/Q3\$\endgroup\$THC– THC2016年05月30日 19:52:30 +00:00Commented May 30, 2016 at 19:52 -
\$\begingroup\$ @FliiFe
(1ZtZ)=-L1 2\$\endgroup\$Leaky Nun– Leaky Nun2016年05月30日 23:34:35 +00:00Commented May 30, 2016 at 23:34
Actually, 10 bytes
3@│\u)%1-*
Explanation:
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)])
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.
GeoGebra, 44 bytes
Element[Flatten[Sequence[{t,0,-t},t,1,n]],n]
where n is one-indexed.
Explanation:
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} |
It is not necessary to generate all triplets through {n, 0, -n}, but it's shorter than writing ceil(n/3) or something to that effect.
Note that n must be defined to create this object (if it isn't defined at the time this is run, GeoGebra will prompt you to create a slider for n).
-
\$\begingroup\$ Hi and welcome to PPCG! Do you have a link I can test this (preferably online)? \$\endgroup\$Riker– Riker2016年06月02日 02:54:09 +00:00Commented Jun 2, 2016 at 2:54
-
-
\$\begingroup\$ Oh cool. But how where do I put in the formula? >_> I tried pasting it into the blank, and it prompted to create a slider, but nothing else happened. \$\endgroup\$Riker– Riker2016年06月02日 22:37:26 +00:00Commented Jun 2, 2016 at 22:37
-
\$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ: Over on the left-hand side, where it says "Input..." First, to initialise
n, enter something liken=297(this will give you a slider that's configured nicely). Then paste the formula into the Input box, which should now be below then. (Make sure to hit return ;) The formula should evaluate to thenth term of the sequence, and it should change when you move the slider. \$\endgroup\$juh– juh2016年06月02日 22:50:55 +00:00Commented Jun 2, 2016 at 22:50
Labyrinth, (削除) 17 (削除ここまで) (削除) 15 (削除ここまで) 14 bytes
Saved 3 bytes using Sok's idea of using 1-(n%3) instead of ~(n%3-2).
1?:#/)}_3%-{*!
The program terminates with an error (division by zero), but the error message goes to STDERR.
Explanation
The program is completely linear, although some code is executed in reverse at the end.
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.
The instruction pointer now hits a dead end and turns around, so it starts to execute the code from the end:
* 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.
Erlang, 40 bytes
F=fun(N)->trunc((N/3+1)*(1-N rem 3))end.
Sadly Erlang has no '%' modulo operator and 'rem' requires the spaces, even before the 3.
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.
Java 7, (削除) 38 (削除ここまで) (削除) 37 (削除ここまで) 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).
-
1\$\begingroup\$ Hello, and welcome to PPCG! You can remove the space after
return, and use a Java 8 lambda. \$\endgroup\$NoOneIsHere– NoOneIsHere2016年06月23日 17:43:20 +00:00Commented Jun 23, 2016 at 17:43 -
\$\begingroup\$ I should specify that this was Java 7. I'll remove that space, though. Thanks! \$\endgroup\$Steven H.– Steven H.2016年06月23日 17:47:33 +00:00Commented Jun 23, 2016 at 17:47
-
\$\begingroup\$ 18 bytes \$\endgroup\$ceilingcat– ceilingcat2019年08月12日 21:12:10 +00:00Commented Aug 12, 2019 at 21:12
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.
Mathematica 26 bytes
With 4 bytes saved thanks to Martin Ender.
⎡#/3⎤(-#~Mod~3-1)&
Uses the same approach as Suever.
[0, 0, 0, -1, 0, 1...\$\endgroup\$1. \$\endgroup\$