36
\$\begingroup\$

Given N, output the Nth term of this infinite sequence:

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

N may be 0-indexed or 1-indexed as you desire.

For example, if 0-indexed then inputs 0, 1, 2, 3, 4 should produce respective outputs -1, 2, -2, 1, -3.

If 1-indexed then inputs 1, 2, 3, 4, 5 should produce respective outputs -1, 2, -2, 1, -3.

To be clear, this sequence is generated by taking the sequence of positive integers repeated twice

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

and rearranging each pair of odd numbers to surround the even numbers just above it

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

and finally negating every other term, starting with the first

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

The shortest code in bytes wins.

\$\endgroup\$
  • \$\begingroup\$ A001057 without the leading zero? \$\endgroup\$ – devRicher Mar 20 '17 at 13:15
  • \$\begingroup\$ @devRicher no, the absolute values there go 1,1,2,2,3,3,4,4,... but here it's 1,2,2,1,3,4,4,3,.... \$\endgroup\$ – Martin Ender Mar 20 '17 at 13:24
  • 6
    \$\begingroup\$ Could you provide a closed form for this sequence or at least something a little more specific than just the first several terms \$\endgroup\$ – 0 ' Mar 20 '17 at 16:48
  • \$\begingroup\$ That equation for the nth term never evaluates to a negative value... something is wrong with it. \$\endgroup\$ – Magic Octopus Urn Mar 20 '17 at 19:49
  • 1
    \$\begingroup\$ @0 ' I've added what I think in an intuitive way of looking at it, though not a closed form. Part of the challenge is figuring out what the pattern is and how to translate it to math and code. \$\endgroup\$ – Calvin's Hobbies Mar 20 '17 at 23:22

26 Answers 26

32
\$\begingroup\$

Python 2, 23 bytes

lambda n:~n/2+n%2*(n|2)

Odd inputs give roughly n/2, even ones roughly -n/2. So, I started with -n/2+n%2*n and tweaked from there.

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Explanation? :) \$\endgroup\$ – MildlyMilquetoast Mar 22 '17 at 4:14
17
\$\begingroup\$

Mathematica, 29 bytes

((#~GCD~4/. 4->-2)+#)/2(-1)^#&

Pure function taking a 1-indexed input. Other than the alternating signs (-1)^#, twice the sequence is close to the input, the differences being 1, 2, 1, -2 cyclically. It's nice that #~GCD~4, the greatest common divisor of the input and 4, is 1, 2, 1, 4 cyclically; so we just manually replace 4->-2 and call it a day. I like this approach because it avoids most of the many-character Mathematica commands.

\$\endgroup\$
9
\$\begingroup\$

Pip, 24 22 bytes

v**a*YaBA2|1+:--a//4*2

Takes input, 1-indexed, as a command-line argument. Try it online or verify 1-20.

Explanation

Observe that the sequence can be obtained by combining three other sequences, one zero-indexed and the others one-indexed:

  • Start with 0 0 0 0 2 2 2 2 4 4 4 4 = a//4*2 (0-indexed);
  • Add 1 2 2 1 1 2 2 1 1 2 2 1 = aBA2|1, where BA is bitwise AND, and | is logical OR (1-indexed);
  • Multiply the sum by -1 1 -1 1 -1 1 -1 1 -1 1 -1 1 = (-1)**a (1-indexed).

If we start with a 1-indexed, we can compute the 1-indexed parts first (reading the expression left to right) and then decrement a for the 0-indexed part. Using the builtin variable v=-1, we get

v**a*((aBA2|1)+--a//4*2)

To shave two more bytes, we have to use some precedence-manipulation tricks. We can eliminate the inner parentheses by replacing + with +: (equivalent to += in a lot of languages). Any compute-and-assign operator is of very low precedence, so aBA2|1+:--a//4*2 is equivalent to (aBA2|1)+:(--a//4*2). Pip will emit a warning about assigning to something that isn't a variable, but only if we have warnings enabled.

The only thing that's lower precedence than : is Y, the yank operator.* It assigns its operand's value to the y variable and passes it through unchanged; so we can eliminate the outer parentheses as well by yanking the value rather than parenthesizing it: YaBA2|1+:--a//4*2.

* Print and Output have the same precedence as Yank, but aren't useful here.

\$\endgroup\$
9
\$\begingroup\$

Jelly, 8 7 bytes

H^Ḃ~N⁸¡

This uses the algorithm from my Python answer, which was improved significantly by @GB.

Try it online!

How it works

H^Ḃ~N⁸¡  Main link. Argument: n

H        Halve; yield n/2. This returns a float, but ^ will cast it to int.
  Ḃ      Bit; yield n%2.
 ^       Apply bitwise XOR to both results.
   ~     Take the bitwise NOT.
    N⁸¡  Negate the result n times.
\$\endgroup\$
  • \$\begingroup\$ I think this is the most standard ASCII characters I've seen in a Jelly submission. I only see two characters that would annoy me (not counting ¡) \$\endgroup\$ – Esolanging Fruit Mar 21 '17 at 2:17
  • \$\begingroup\$ google.com/… \$\endgroup\$ – Dennis Mar 21 '17 at 2:20
9
\$\begingroup\$

Java 8, 19 bytes

n->~(n/2)+n%2*(n|2)

Java 7, 47 37 bytes

int c(int n){return~(n/2)+n%2*(n|2);}

First time Java (8) actually competes and is shorter than some other answers. Still can't beat the actual golfing languages like Jelly and alike, though (duhuh.. what a suprise.. >.> ;P)

0-indexed
Port from @Xnor's Python 2 answer.
-10 bytes thanks to @G.B.

Try it here.

\$\endgroup\$
  • 2
    \$\begingroup\$ You don't need the ternary check if you put (n/2) in parentheses. \$\endgroup\$ – G B Mar 20 '17 at 11:19
  • 1
    \$\begingroup\$ @GB Ah, so that was the issue.. Thanks. I kinda feel stupid now.. >.> \$\endgroup\$ – Kevin Cruijssen Mar 20 '17 at 12:03
  • \$\begingroup\$ Oh, we're allowed just function definitions for java? \$\endgroup\$ – Cruncher Mar 20 '17 at 15:48
  • \$\begingroup\$ @Cruncher Unless the question states otherwise, the default is full program or function. So yes, it is allowed to just post a method in Java, or a lambda in Java 8 (I've added the Java 8 equivalent in my answer above). \$\endgroup\$ – Kevin Cruijssen Mar 20 '17 at 15:56
  • 1
    \$\begingroup\$ @EricDuminil The default is program or function, unless the challenge states otherwise. \$\endgroup\$ – Kevin Cruijssen Mar 22 '17 at 21:59
8
\$\begingroup\$

Jelly, 15 12 11 bytes

Ḷ^1‘ż@N€Fị@

Try it online!

How it works

Ḷ^1‘ż@N€Fị@  Main link. Argument: n

Ḷ            Unlength; yield [0, 1, 2, 3, ..., n-1].
 ^1          Bitwise XOR 1; yield [1, 0, 3, 2, ..., n-1^1].
   ‘         Increment; yield [2, 1, 4, 3, ..., (n-1^1)+1].
      N€     Negate each; yield [-1, -2, -3, -4, ..., -n].
    ż@       Zip with swapped arguments; 
             yield [[-1, 2], [-2, 1], [-3, 4], [-4, 3], ..., [-n, (n-1^1)+1]].
        F    Flatten, yield [-1, 2, -2, 1, -3, 4, -4, 3, ..., -n, (n-1^1)+1].
         ị@  At-index with swapped arguments; select the item at index n.
\$\endgroup\$
  • \$\begingroup\$ I knew there'd be a jelly answer around 10 \$\endgroup\$ – Cruncher Mar 20 '17 at 15:41
  • \$\begingroup\$ There's also a Jelly answer at 7. ;) \$\endgroup\$ – Dennis Mar 20 '17 at 15:44
  • \$\begingroup\$ I saw it right after posting this comment lol. I really need to learn Jelly one of these days... It's funny if you look at the history of questions on this SE. Used to be all GolfScript, then CJam took over, and now it's Jelly. \$\endgroup\$ – Cruncher Mar 20 '17 at 15:47
6
\$\begingroup\$

RProgN 2, 31 25 22 bytes

nx=x2÷1x4%{+$-1x^*}#-?

Explained

nx=                         # Convert the input to a number, set x to it.
   x2÷                      # Floor divide x by 2.
      1                     # Place a 1 on the stack.
       x4%{       }#-?      # If x%4 is 0, subtract 1 from x//2, otherwise...
           +                # Add the 1 and the x together.
            $-1             # Push -1
               x^           # To the power of x.
                 *          # Multiply x//2+1 by -1^x. (Invert if odd, do nothing if even)

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Nice approach! +1 \$\endgroup\$ – R. Kap Mar 21 '17 at 1:13
6
\$\begingroup\$

Ruby, 26 23 18 bytes

->n{~n/2+n%2*n|=2}

0-based

-3 bytes stealing the -1^n idea from Greg Martin, Dennis and maybe somebody else, then -5 bytes stealing the n|2 idea from xnor.

\$\endgroup\$
5
\$\begingroup\$

Stacked, 30 28 bytes

:2%([:2/\4%2=tmo+][1+2/_])\#

Try it online! Returns a function, which as allowed per meta consensus.. Takes input from the top of the stack.

Using the same approach as the RProgN 2 answer.


Alternatively, 46 bytes. Try it online!:

{!()1[::1+,:rev,\srev\,\2+]n*@.n 1-#n 2%tmo*_}

This one generates the range then selects and negates the member as appropriate.

\$\endgroup\$
5
\$\begingroup\$

Python 2,  44  33 27 bytes

lambda n:(-1)**n*~(n/2^n%2)

Thanks to @GB for golfing off 6 bytes!

Try it online!

\$\endgroup\$
4
\$\begingroup\$

05AB1E, 8 bytes

2‰`^±¹F(

Try it online

Explanation

2‰          divmod by 2
  `         flatten list
   ^        XOR
    ±       NOT
     ¹F(    Push 1st argument, loop N times, negate
\$\endgroup\$
  • \$\begingroup\$ Wow, I love it, but ¹F( seems expensive for "if odd, negate". \$\endgroup\$ – Magic Octopus Urn Mar 20 '17 at 16:02
  • \$\begingroup\$ @carusocomputing It does, but that's the shortest I know of. Dennis's similar answer in Jelly also has 3 bytes for that part. It's still shorter than duplicate, push parity, if, negate. \$\endgroup\$ – mbomb007 Mar 20 '17 at 16:37
  • \$\begingroup\$ I tried for 15 minutes to beat it, only thing that came close was another 3 byte solution of to the power of n, to the power of 1/n. \$\endgroup\$ – Magic Octopus Urn Mar 20 '17 at 18:03
4
\$\begingroup\$

Jelly, 9 8 bytes

|2×Ḃ+H~$

Try it online!

-1 thanks to Dennis. Duh float conversions.

Uses @xnor's Python 2 approach.

EDIT: >_>

\$\endgroup\$
3
\$\begingroup\$

CJam, 16 bytes

{_(_1&)^2/)W@#*}

1-based input.

Try it online!

Explanation

Here is a breakdown of the code with the values on the stack for each input from 1 to 4. The first few commands only affect the two least significant bits of n-1 so after 4, this stuff just repeats cyclically, with the results incremented by 2, due to the halving.

Cmd             Stack: [1]       [2]       [3]       [4]
_    Duplicate.        [1 1]     [2 2]     [3 3]     [4 4]
(    Decrement.        [1 0]     [2 1]     [3 2]     [4 3]
_    Duplicate.        [1 0 0]   [2 1 1]   [3 2 2]   [4 3 3]
1&   AND 1.            [1 0 0]   [2 1 1]   [3 2 0]   [4 3 1]
)    Increment.        [1 0 1]   [2 1 2]   [3 2 1]   [4 3 2]
^    XOR.              [1 1]     [2 3]     [3 3]     [4 1]
2/   Halve.            [1 0]     [2 1]     [3 1]     [4 0]
)    Increment.        [1 1]     [2 2]     [3 2]     [4 1]
W    Push -1.          [1 1 -1]  [2 2 -1]  [3 2 -1]  [4 1 -1]
@    Rotate.           [1 -1 1]  [2 -1 2]  [2 -1 3]  [1 -1 4]
#    -1^n.             [1 -1]    [2 1]     [2 -1]    [1 1]
*    Multiply.         [-1]      [2]       [-2]      [1]
\$\endgroup\$
2
\$\begingroup\$

Perl 6,  55 27 24  22 bytes

{(-1,2,-2,1,{|($^a,$^b,$^c,$^d Z+ -2,2,-2,2)}...*)[$_]}

(Inspired by the Haskell zipWith answer)
Try it

{+^($_ div 2)+$_%2*($_+|2)}

(Inspired by several answers)
Try it

{+^($_+>1)+$_%2*($_+|2)}

Try it

{+^$_+>1+$_%2*($_+|2)}

Try it

Expanded:

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

    +^          # numeric binary invert the following
      $_ +> 1   # numeric bit shift right by one
  +
      $_ % 2    # the input modulo 2
    *
      ($_ +| 2) # numeric binary inclusive or 2
}

(All are 0 based)

\$\endgroup\$
  • \$\begingroup\$ Nice submission! \$\endgroup\$ – CraigR8806 Mar 20 '17 at 17:21
2
\$\begingroup\$

Haskell, 37 36 bytes

(([1,3..]>>= \x->[-x,x+1,-x-1,x])!!)

Try it online! This is an anonymous function which takes one number n as argument and returns 0-indexed the nth element of the sequence.

\$\endgroup\$
1
\$\begingroup\$

Haskell, 56 bytes

f n=concat(iterate(zipWith(+)[-2,2,-2,2])[-1,2,-2,1])!!n

0-indexed

\$\endgroup\$
1
\$\begingroup\$

Perl 5 47 + 1 (for flag) = 48 Bytes

print(((sin$_%4>.5)+1+2*int$_/4)*($_%4&1?1:-1))

Old Submission 82 Bytes

@f=(sub{-$_[0]},sub{$_[0]+1},sub{-$_[0]-1},sub{$_[0]});print$f[$_%4](1+2*int$_/4)

Run like so:

perl -n <name of file storing script>  <<<  n
\$\endgroup\$
  • \$\begingroup\$ You can save one byte by using print +(( and removing the final ). And two more by using say and -E. And also one more by doing ($_%4&1||-1) instead of the ternary. \$\endgroup\$ – simbabque Mar 22 '17 at 16:24
1
\$\begingroup\$

JavaScript (ES7), 28 bytes

n=>(n+2>>2)*2*(-1)**n-!(n&2)

1-indexed. I haven't looked at any other answers yet so I don't know if this is the best algorithm, but I suspect not.

\$\endgroup\$
1
\$\begingroup\$

JavaScript, 28 22 bytes

Thanks @ETHproductions for golfing off 6 bytes

x=>x%2?~x>>1:x%4+x/2-1

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Hmm... would f=x=>x%2?~x>>1:x/2+x%4-1 work? \$\endgroup\$ – ETHproductions Mar 20 '17 at 20:46
  • \$\begingroup\$ For some reason I had left the f= in front of the anonymous function :P \$\endgroup\$ – fəˈnɛtɪk Mar 20 '17 at 20:51
1
\$\begingroup\$

dc, 98 bytes

?sa0sb1sq[lq1+dsqla!<i3Q]sf[lb1-lfx]su[lblfx]sx[lb1+dsblfx]sj[lqdd4%d0=u1=j2%1=xljxlfx]dsix_1la^*p

Gosh, this is the longest answer here, mainly because I went the path of generating the absolute value of each element of the sequence one by one based on the following recursive formula:

enter image description here

then outputting (-1)^n * a_n, rather than directly computing the n'th element. Anyways, this is 1-indexed.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

R, 38 bytes

function(n)floor(n/2+1-2*!n%%4)*(-1)^n

Explanation

floor(n/2+1)                ->  1 2  2 3  3 4  4 5...
floor(n/2+1-2*!n%%4)        ->  1 2  2 1  3 4  4 3... (subtract 2 where n%%4 == 0)
floor(n/2+1-2*!n%%4)*(-1)^n -> -1 2 -2 1 -3 4 -4 3... (multiply odd n by -1)
\$\endgroup\$
1
\$\begingroup\$

TI-Basic (TI-84 Plus CE), 31 bytes

.5(Ans+1+remainder(Ans+1,2)-4not(remainder(Ans,4)))i^(2Ans

TI-Basic is a tokenized language and each token used here is one byte, except remainder(, which is two.

This uses the 1-indexed version.

Explanation:

There is a pattern that repeats every four numbers. In the 1-indexed version, it is: -(x+1)/2, (x+1)/2, -(x+1)/2, (x-1)/2 for the input value x. This can be represented as a piecewise-defined function.

f(x) = -(x+1)/2 if x ≡ 1 mod 4; (x+1)/2 if x ≡ 2 mod 4; -(x+1)/2 if x ≡ 3 mod 4; (x-1)/2 if x ≡ 0 mod 4

Because the "x ≡ 1 mod 4" and "x ≡ 3 mod 4" parts are the same, we can combine them into "x ≡ 1 mod 2".

Now are piecewise function is:

f(x) = -(x+1)/2 if x ≡ 1 mod 2; (x+2)/2 if x ≡ 2 mod 4; (x-2)/2 if x ≡ 0 mod 4

This is where I start breaking it into actual commands. Since the value is positive for even indexes and negative for odd ones, we can use (-1)^x. However, in TI-Basic i^(2X (5 bytes) is shorter than (-1)^Ans (6 bytes). Note that parentheses are required due to order of operations.

Now that we have the way to negate the odd inputs out of the way, we move on to the mods (adding the negating back on later). I made the case of an odd input the default, so we start with .5(Ans+1).

To fix the case of even input, just add one to the number in the parentheses, but only when x ≡ 0 mod 2. This could be represented as .5(Ans+1+remainder(Ans+1,2)) or .5(Ans+1+not(remainder(Ans,2))), but they have the same byte count, so it doesn't matter which.

To fix the case of multiple-of-4 input, we need to subtract 3 from the number in the parentheses, but also another 1 because all multiples of 4 are even, which would add one from our previous step, so we now have .5(Ans+1+remainder(Ans+1,2)-4not(remainder(Ans,4))).

Now, just tack on the sign-determining part to the end to get the full program.

\$\endgroup\$
0
\$\begingroup\$

Befunge 93, 25 bytes

Zero-indexed

&4/2*1+&4%3%!!+&2%2*1-*.@

Try it Online!

The number is given by ((2(n / 4) + 1) + !!((n % 4) % 3)) * (2(n % 2) - 1)

\$\endgroup\$
0
\$\begingroup\$

QBIC, 53 bytes

b=1:{[b,b+3|~b=a|_x(-(b%2)*2+1)*(q+(b%4>1)*-1)]]q=q+2

Explanation:

b=1     Set b to a starting value of 1
        QBIC would usually use the pre-initialised variable q, but that is already in use
:       Get an input number from the cmd-line, our term to find
{       Start an infinite loop
[b,b+3| FOR-loop: this runs in groups of 4, incrementing its own bounds between runs
~b=a|   If we've reached the term requested
_x      QUIT the program and print:

(-(b%2)*2+1)   The b%2 gives a 1 or a 0, times 2 (2,0), negged (-2,0) and plus one (-1,1)
*              That gives us the sign of our term. Now the value:
(q+(b%4>1)*-1) This is q + 1 if the inner loop counter MOD 4 (1,2,3,0...) is 2 or 3.
]       Close the IF that checks the term
]       Close the FOR-loop
q=q+2   And raise q by 2 for the next iteration of the DO-loop.
\$\endgroup\$
0
\$\begingroup\$

Wise, 19 bytes

::>!:><^^~![!-!-~]|

Try it Online!

This is just a port of @Dennis' Jelly answer to Wise.

\$\endgroup\$
0
\$\begingroup\$

Q, 52 bytes

{(1 rotate(,/){x,(-)x}each 1_((_)x%4)+til 3)x mod 4}

0 indexed solution.

  1. Gets the block number ie. which [-x x+1 -(x+1) x] block within the sequence contains the index.
  2. Gets the index of the value within the block based on the index of the value within the whole sequence.
  3. Creates the block.
  4. Indexes into it via index derived in step 2.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.