Oddly Even, Positively Negative

36

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.

Calvin's Hobbies

Posted 2017-03-20T02:51:48.227

Reputation: 84 000

A001057 without the leading zero? – devRicher – 2017-03-20T13:15:46.650

@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,.... – Martin Ender – 2017-03-20T13:24:20.417

6Could you provide a closed form for this sequence or at least something a little more specific than just the first several terms – 0 ' – 2017-03-20T16:48:55.313

That equation for the nth term never evaluates to a negative value... something is wrong with it. – Magic Octopus Urn – 2017-03-20T19:49:57.773

1@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. – Calvin's Hobbies – 2017-03-20T23:22:50.930

@devRicher A121496 looks to be correct for the absolute values.

– Bob – 2017-03-21T04:34:50.647

Answers

32

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!

xnor

Posted 2017-03-20T02:51:48.227

Reputation: 115 687

1Explanation? :) – MildlyMilquetoast – 2017-03-22T04:14:42.323

17

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.

Greg Martin

Posted 2017-03-20T02:51:48.227

Reputation: 13 940

9

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.

DLosc

Posted 2017-03-20T02:51:48.227

Reputation: 21 213

9

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.

Kevin Cruijssen

Posted 2017-03-20T02:51:48.227

Reputation: 67 575

2You don't need the ternary check if you put (n/2) in parentheses. – G B – 2017-03-20T11:19:06.503

1@GB Ah, so that was the issue.. Thanks. I kinda feel stupid now.. >.> – Kevin Cruijssen – 2017-03-20T12:03:54.987

Oh, we're allowed just function definitions for java? – Cruncher – 2017-03-20T15:48:57.967

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

– Kevin Cruijssen – 2017-03-20T15:56:01.217

The types for the lambda do need to be declared: https://codegolf.meta.stackexchange.com/questions/11223/untyped-functions-in-static-langauges

– Nathan Merrill – 2017-03-21T15:40:27.597

Nice. But don't golf submissions should be stand-alone programs? As in, save it as .java and compile? – Eric Duminil – 2017-03-22T21:46:37.343

1

@EricDuminil The default is program or function, unless the challenge states otherwise.

– Kevin Cruijssen – 2017-03-22T21:59:33.797

@KevinCruijssen Thanks! – Eric Duminil – 2017-03-22T22:02:05.720

9

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.

Dennis

Posted 2017-03-20T02:51:48.227

Reputation: 196 637

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 ¡) – Esolanging Fruit – 2017-03-21T02:17:54.563

8

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.

Dennis

Posted 2017-03-20T02:51:48.227

Reputation: 196 637

I knew there'd be a jelly answer around 10 – Cruncher – 2017-03-20T15:41:30.383

There's also a Jelly answer at 7. ;) – Dennis – 2017-03-20T15:44:21.503

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. – Cruncher – 2017-03-20T15:47:01.473

6

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!

ATaco

Posted 2017-03-20T02:51:48.227

Reputation: 7 898

Nice approach! +1 – R. Kap – 2017-03-21T01:13:49.773

6

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.

G B

Posted 2017-03-20T02:51:48.227

Reputation: 11 099

5

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.

Conor O'Brien

Posted 2017-03-20T02:51:48.227

Reputation: 36 228

5

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!

Dennis

Posted 2017-03-20T02:51:48.227

Reputation: 196 637

4

Jelly, 9 8 bytes

|2×Ḃ+H~$

Try it online!

-1 thanks to Dennis. Duh float conversions.

Uses @xnor's Python 2 approach.

EDIT: >_>

Erik the Outgolfer

Posted 2017-03-20T02:51:48.227

Reputation: 38 134

3Just when you think you're winning, Dennis will come along and beat you. – HyperNeutrino – 2017-03-20T16:02:11.820

|2×Ḃ+H~$ saves a byte. https://tio.run/nexus/jelly#AR0A4v//fDLDl@G4gitIfiT/MjThuLbCtcW8w4figqxH/w – Dennis – 2017-03-20T16:03:01.207

@Dennis I thought that would spit an error. – Erik the Outgolfer – 2017-03-20T16:50:00.203

4

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

mbomb007

Posted 2017-03-20T02:51:48.227

Reputation: 21 944

Wow, I love it, but ¹F( seems expensive for "if odd, negate". – Magic Octopus Urn – 2017-03-20T16:02:34.197

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

– mbomb007 – 2017-03-20T16:37:58.650

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. – Magic Octopus Urn – 2017-03-20T18:03:31.763

3

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]

Martin Ender

Posted 2017-03-20T02:51:48.227

Reputation: 184 808

2

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)

Brad Gilbert b2gills

Posted 2017-03-20T02:51:48.227

Reputation: 12 713

Nice submission! – CraigR8806 – 2017-03-20T17:21:09.553

2

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.

Laikoni

Posted 2017-03-20T02:51:48.227

Reputation: 23 676

1

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

CraigR8806

Posted 2017-03-20T02:51:48.227

Reputation: 480

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. – simbabque – 2017-03-22T16:24:30.237

1

Haskell, 56 bytes

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

0-indexed

Blex

Posted 2017-03-20T02:51:48.227

Reputation: 289

1

JavaScript, 28 22 bytes

Thanks @ETHproductions for golfing off 6 bytes

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

Try it online!

fəˈnɛtɪk

Posted 2017-03-20T02:51:48.227

Reputation: 4 166

Hmm... would f=x=>x%2?~x>>1:x/2+x%4-1 work? – ETHproductions – 2017-03-20T20:46:05.690

For some reason I had left the f= in front of the anonymous function :P – fəˈnɛtɪk – 2017-03-20T20:51:59.363

1

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.

ETHproductions

Posted 2017-03-20T02:51:48.227

Reputation: 47 880

1

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!

R. Kap

Posted 2017-03-20T02:51:48.227

Reputation: 4 730

1

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)

user2390246

Posted 2017-03-20T02:51:48.227

Reputation: 1 391

1

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.

pizzapants184

Posted 2017-03-20T02:51:48.227

Reputation: 3 174

0

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)

MildlyMilquetoast

Posted 2017-03-20T02:51:48.227

Reputation: 2 907

0

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.

steenbergh

Posted 2017-03-20T02:51:48.227

Reputation: 7 772

0

Wise, 19 bytes

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

Try it Online!

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

MildlyMilquetoast

Posted 2017-03-20T02:51:48.227

Reputation: 2 907

0

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.

Daniel Plainview

Posted 2017-03-20T02:51:48.227

Reputation: 21