| Bytes | Lang | Time | Link |
|---|---|---|---|
| 024 | Tcl | 170505T164911Z | sergiol |
| 025 | Tcl | 250611T154303Z | sergiol |
| 030 | Tcl | 170505T164030Z | sergiol |
| 007 | J | 171012T064836Z | Jonah |
| 068 | Kakoune + bc | 241215T225143Z | JoshM |
| 018 | Raku Perl 6 rakudo | 241212T210106Z | xrs |
| 007 | ARBLE | 241112T212958Z | ATaco |
| 013 | AWK | 241112T210623Z | xrs |
| 032 | sed | 240414T184200Z | guest430 |
| 005 | Uiua 0.11.0 | 240415T034417Z | Tbw |
| 002 | Vyxal | 240415T033216Z | emanresu |
| 017 | Alice | 240414T230958Z | Julian |
| 005 | Thunno 2 | 230609T145024Z | The Thon |
| 010 | ><> Fish | 230602T232911Z | chunes |
| 010 | Braingolf v0.1 | 170504T082932Z | Mayube |
| 004 | Risky | 211009T042246Z | DLosc |
| 007 | TIBasic | 211010T003408Z | Youserna |
| 004 | Vyxal r | 210121T052522Z | lyxal |
| 031 | Python 3 | 210409T194557Z | Symmetr1 |
| 007 | BRASCA | 210129T103331Z | SjoerdPe |
| 015 | Factor | 210129T080657Z | Bubbler |
| 056 | Boolfuck | 210129T051859Z | EasyasPi |
| 051 | brainfuck 8bit | 210120T233450Z | EasyasPi |
| 018 | Python 3 | 210123T155627Z | ToxicCod |
| 014 | Zsh | 210121T095829Z | pxeger |
| 040 | Lua | 210121T041207Z | J. А. de |
| 006 | APL Dyalog Unicode | 201220T111345Z | Kamila S |
| 005 | x8616 machine code | 200813T135655Z | 640KB |
| 012 | Perl 5 | 200813T115641Z | Dom Hast |
| 004 | Japt | 200813T113855Z | Shaggy |
| 007 | Keg | 200813T063802Z | lyxal |
| 018 | MAWP | 200813T062723Z | Razetime |
| 038 | tinylisp | 200813T050956Z | DLosc |
| 008 | Ly | 171012T073740Z | LyricLy |
| 027 | CasioBasic | 171012T061621Z | numberma |
| 024 | Common Lisp | 170717T144805Z | Renzo |
| 021 | Haskell | 170717T081617Z | Sergii M |
| 017 | R | 170713T180344Z | runr |
| 008 | Wise | 170506T144526Z | Wheat Wi |
| 004 | 170713T141914Z | totallyh | |
| 008 | braingasm | 170504T122653Z | daniero |
| 035 | @REXX 35 Bytes | 170517T143841Z | theblitz |
| 213 | Klein | 170516T232739Z | Wheat Wi |
| 061 | Chip | 170510T151855Z | Phlarx |
| 012 | Juby | 170506T201833Z | Cyoce |
| 012 | Ruby | 170506T201308Z | Cyoce |
| 021 | Clojure | 170506T103057Z | NikoNyrh |
| 008 | x86 machine code | 170506T072219Z | user2330 |
| 068 | Python | 170505T183618Z | penalosa |
| 011 | Befunge93 | 170505T173934Z | MercyBea |
| 018 | Befunge 93 | 170504T125758Z | Daniel |
| 006 | Actually | 170505T154627Z | user4594 |
| 010 | Pyth | 170505T111353Z | kalsower |
| 010 | QBIC | 170504T161919Z | steenber |
| 027 | Excel VBA | 170505T072124Z | Stupid_I |
| 009 | x86 Assembly | 170505T055325Z | Cody Gra |
| 004 | Pyth | 170505T060014Z | Esolangi |
| 016 | Python | 170504T085903Z | sagiksp |
| 019 | Mathematica | 170504T083839Z | numberma |
| 010 | dc | 170504T195408Z | Digital |
| 020 | C | 170504T084754Z | feersum |
| 072 | SAS | 170504T181337Z | J_Lard |
| 017 | Groovy | 170504T180955Z | Jimwel A |
| 020 | Python | 170504T133427Z | Wondercr |
| 011 | Excel | 170504T175720Z | pajonk |
| 007 | 05AB1E | 170504T173514Z | sporkl |
| 036 | BrainFlak | 170504T160412Z | Wheat Wi |
| 017 | Fourier | 170504T154033Z | Beta Dec |
| 009 | Cubix | 170504T153136Z | user4854 |
| 015 | AWK | 170504T150907Z | Robert B |
| 011 | Cubix | 170504T143550Z | Luke |
| 006 | Japt | 170504T142749Z | Oliver |
| 029 | Swift | 170504T140339Z | Caleb Kl |
| 011 | C# | 170504T084956Z | Kevin Cr |
| 010 | JavaScript ES6 | 170504T082603Z | Shaggy |
| 006 | CJam | 170504T095327Z | Erik the |
| 004 | 05AB1E | 170504T093445Z | Okx |
| 012 | Javascript | 170504T084030Z | Matthew |
| 018 | Python3 | 170504T083701Z | Yytsi |
| 020 | Batch | 170504T092439Z | Neil |
| 336 | Stack Cats | 170504T090748Z | Martin E |
| 021 | Retina | 170504T091601Z | Neil |
| 010 | Java 8 | 170504T084049Z | Kevin Cr |
| 015 | PHP | 170504T090009Z | user6395 |
| 007 | MATL | 170504T085419Z | Luis Men |
| 020 | Python | 170504T083504Z | numberma |
| 003 | Jelly | 170504T083352Z | Leaky Nu |
| 004 | Jelly | 170504T083022Z | Erik the |
| 029 | C | 170504T083133Z | egonr |
J, 7 bytes
1-@XOR-
This version thanks to south.
J, 9 bytes
(22 b.)&1
22 b. is XOR. Port of Cyoce's ruby answer.
Alternative straightforward answer:
+1:`_1:@.(2&|)
Kakoune + bc, 68 bytes
itry %{exec "/[13579]$<ret>a+1<c-v><esc>"}<ret><esc>hGGypf1t]c02468<esc>f+;r-f<ret>;GGd:<c-r>"<ret>x|bc<ret>
exec is a builtin alias for execute-keys
we search for both even and odd numbers but we use the try %{exec <search and do stuff>} to fail if the search fails and not do any of the other operations.
We append a +1 to odd numbers and a -1 to even numbers.
Then the resulting expression is piped to bc (a basic command line calculator utility)
roughly equivalent to this script
try %{exec "/[13579]$<ret>a+1<esc>"} # search for odd and append +1
try %{exec "/[02468]$<ret>a-1<esc>"} # search for even and append -1
exec "x|bc<ret>" # pipe resulting expression to bc
but to save characters the first line is written, then copied and modified to be the second one and then the final thing is cut and pasted as a command to do the appending
sed, 33 32 bytes
s/^/%/ #insert % at begining
s/../&%/g #put % after char pairs
s/.%.$// #if odd, delete 2 chars
s/%//g #remove the percents
takes input as any unary char other than %.
Alice, 17 bytes
/O\.2%2v
@M/+t* <
/M\.2%2*t+/O@
/M\ # Reads an argument and put it on the slack
.2%2*t+ # Calculates input + (input mod 2) * 2 - 1
/O@ # Prints the top of the stack and exit
Thunno 2, 5 bytes
Ṅ1Æ^Ṅ
Explanation
Ṅ1Æ^Ṅ # Implicit input
Ṅ # -( )
Ṅ # -input
Æ^ # ^
1 # 1
# Implicit output
Braingolf v0.1, 11 10 bytes
.1>2,%?+:-
Try it online! (Second argument is the Braingolf code, third argument is the input)
Saved a byte thanks to Neil
First ever competing braingolf answer :D
Explanation:
. Duplicate the top of the stack
1> Push 1 to the bottom of the stack
2 Push 2 to stack
,% Pop last 2 items, mod them and push result
? If last item > 0
+ Add the 1 to the input
: Else
- Subtract the 1 from the input
No semicolon in code so print last item
Braingolf v0.2, 9 bytes
.2%?1+:1-
Try it online! (Second argument is the Braingolf code, third argument is the input)
See above for explanation. Only difference is in Braingolf v0.2, the default behaviour of diadic operators, and the function of the , modifier, are reversed, meaning the 2 commas in the v0.1 answer are no longer needed.
Risky, 4 bytes
?+0--2?
Explanation
? The input number
+0 plus 0
- minus
- -1
2 to the power of
? the input number
TI-Basic, 7 bytes
Ans-i^(2Ans
Takes input in Ans. Output is stored in Ans and is displayed.
Alternatively, 9 bytes:
Ans-cos(2πfPart(Ans/2
Vyxal r, 4 bytes
‹ue+
Me and the boys porting risky be like
Explained
‹ue+
‹ # input - 1
u # -1
e # ^^ ** ^
+ # ^ + input
Python 3, 36 31 bytes
def f(n):return n+(-1)**(n%2+1)
BRASCA, 7 bytes
ig{1_}n
Explanation
i - Turn ASCII codepoints 48-57 to numbers 0-9
g - Concatenate stack
{ - Decrement
1_ - XOR by 1
} - Increment
n - Output as number
Factor, 15 bytes
[ -1 over ^ - ]
Uses x-(-1)^x method as in many other answers (specifically inspired by the APL one).
In Factor, it is usually better (code-golf-wise) to minimize the number of conditionals, then minimize the number of functions overall (especially when the answer can be found with arithmetic, where all the functions have short names). The top answer beats a different arithmetic answer x+x%2*2-1 (23 bytes)
[ dup 2 mod 2 * + 1 - ]
and a conditional-based answer x+(x.odd()?1:-1) (21 bytes)
[ dup odd? 1 -1 ? + ]
Boolfuck, 91 57 56 bytes
,>,>,>,>,>,>,>+<<<<<<<+[>+]<[<]>+[>]+<[+<]>;>;>;>;>;>;>;
Yes, a real solution using Boolfuck.
Works on 7-bit integers, reads and writes in raw semibytes.
There might still be some optimization room here.
I mostly wanted to avenge my ,+; meme.
,>,>,>,>,>,>, read 7 bits
>+<<<<<<<+[>+]<[<]> decrement
+ xor 1
[>]+<[+<] increment
>;>;>;>;>;>;>; print
brainfuck (8-bit), 51 bytes
,[->>++>+<<<]+++[->>[-<++>]<[->++<]<]>>[>++<[-]]>-.
Requires a fixed 8-bit cell size.
Decided to do something entirely on my own.
Inspired by some meme ARM code I wrote to check if it is a multiple of 4 (screenshot)
Instead of modulo, negate+xor, or binary AND, I shift out all the bits but the lowest to determine if it is even or odd.
// Checks parity by shifting n << 7.
// Requires 8-bit cells
, // [ n 0 0 0]
// copy loop, shifting one once
[->>++>+<<<] // [ 0 0 n<<1 n]
// n <<= 6
+++ // c = 3
[- // loop 3 times, shifting twice
>>[-<++>] // [ c n<<1 0 n]
<[->++<] // [ c 0 n<<1 n]
<] // end loop
// if even:
// tape[2]==0
// else:
// tape[2]==0x80
>>[ // if tape[2] != 0:
>++<[-] // n += 2
]
>- // n -= 1
. // print n
Equivalent C:
uint8_t parity(uint8_t n)
{
uint8_t is_odd = n << 7;
if (is_odd != 0)
n += 2;
return n - 1;
}
The input is a byte from stdin, and the output is a byte printed to stdout. 0-255 only.
The demo uses ASCII arithmetic.
boolfuck (joke), 3 bytes
,+;
For a real Boolfuck solution, see here
Operation works on 1-bit integers from stdin, prints to stdout. Obviously a joke.
Python 3, 18 bytes
lambda n:n+n%2*2-1
Explanation: Take the modulo of "n" and double it
Subtract that off the original "n" and subtract another 1
Basically, the same but easier to understand:
lambda n:n-(1-n%2*2)
Lua (40 bytes)
Using a table in order to avoid math.ceil or math.floor
function m(n)return n+({-1,1})[1+n%2]end
APL (Dyalog Unicode), 6 bytes
-2 thanks to Razetime
⊢-¯1*⊢
Explanation:
⊢-¯1*⊢
¯1*⊢ ⍝ calculate ¯1*⍵ - for even ⍵: 1, for odd ⍵: ¯1.
⊢- ⍝ subtract 1 for even, subtract ¯1 (add 1) for odd.
x86-16 machine code, 5 bytes
Binary:
00000000: 4834 0140 c3 H4.@.
Listing:
48 DEC AX ; decrement input (parity now inverted)
34 01 XOR AL, 1 ; if LSb is 0 (odd input) add 1, otherwise subtract 1
40 INC AX ; increment
C3 RET ; return to caller
Callable function, input/output is AL.
Explanation:
Classic XOR shenanigans to accomplish this equivalent if/else pseudocode:
AL = AL - 1
if ( AL & 1 == 0 ) AL = AL + 1
else AL = AL - 1
AL = AL + 1
Edit:
Well heck:
Silly me for not looking at existing submissions before starting. This approach was suggested by Ilmari Karonen in 2017!
Japt, 4 bytes
aJpU
Try it (includes all test cases)
aJpU :Implicit input of integer U
a :Absolute difference with
J : -1
pU : Raised to the power of U
tinylisp, 38 bytes
(load library
(q((N)((i(odd? N)a s)N 1
Try it online! (Adds 4 bytes to bind the lambda function to a name for ease of testing.)
Ungolfed
(load library)
(lambda (N)
((if (odd? N) add2 sub2) N 1))
Pretty straightforward implementation of the spec: if N is odd, add 1 to N; if not, subtract 1 from N. The main trick is that the if needs only swap out which function we're calling (addition vs. subtraction); the arguments (N and 1) are the same in either case.
Ly, 8 bytes
n:2%2*+,
Explanation:
n:2%2*+,
n # take input
:2% # modulo two
2* # multiply by two
+ # add to input
, # decrement
Casio-Basic, 27 bytes
piecewise(mod(n,2),1,-1)+n
26 bytes for the function, +1 to enter n in the parameters box.
Haskell, 21 bytes
f x|odd x=x+1|0<1=x-1
I have no idea why I'm doing this xD
R, 17 bytes
(n=scan())-(-1)^n
where n=scan() takes the digit value.
Wise, 8 bytes
-::^~-^-
Explanation
If this were the other way around, (decrement if odd, increment if even), it would be quite easy to do this.
We would just flip the last bit.
::^~-^
The fix here is that we flip the last bit while negative. The negative numbers are 1 off from the negation of the numbers ~ so this creates an offset resolving the problem.
So we just take out program and wrap it in -.
-::^~-^-
,,,, 4 bytes
_1^_
Yay.
Explanation
_1^_
input by command-line args
_ negate
1 push 1
^ pop input and 1 and push input ^ 1 (bitwise XOR)
_ negate
implicit output
braingasm, 8 bytes
;o[++]-:
; reads a number, o[++] increments twice if the number is odd, -decrements once, : prints.
edit: changed to p to o to retrofit to a breaking change in the language.
@REXX 35 Bytes
arg a
x=pos(".",a/2)-1
say a+abs(x)/x
Explanation: Explanation: There is no distinction in Rexx between numbers and strings. The action you perform is what defines the type. The "typing" applies just to that action and can change at any time.
So, after dividing the number by 2 we then search for the decimal point. Subtract 1 from its position giving -1 if it was not found and a value in the range 1-n if it was. (Note that 1/2 returns 0.5 and not .5 so pos can never be 1 and therefore x can never be 0).
REXX functions and instructions
Klein, 21 + 3 bytes, (non-competing)
Uses the 000 topology.
:(1-(\))++@
1-+:?\)-(
Explanation
The first bit executed is :(1-(. This puts a copy of the input and a -1 in the scope to be recalled later. This is just required set up for future computation.
The two mirrors \\ then move the ip down a level into the main loop. The main loop, unfolded, is:
)-(1-+:?\
This recalls the first number of the scope and flips its sign then decrements the tos. It will continue to flip the sign back and forth until it reaches zero. This way it will be -1 if our input was even and 1 if it was odd. Once the counter has reached zero ? stops jumping over the mirror and the pointer wraps around to the top. Now the mirror we used earlier deflects the ip to the right causing it to run the code ))++@.
This code recalls the two things from the scope (the copy of the input and the number we have been flipping) with )). And adds the top three items with ++. Since the counter is at zero the result is just the sum of the number we built and the input. Since it can be either -1 or 1 depending on the parity of the input this will flip the sign of the input.
Finally @ ends execution.
Chip, 61 bytes
* *
A~#-#a
B~#~#b
C~#~#c
D~#~#d
E~#~#e
F~#~#f
G~#~#g
H~#~#h
Since Chip natively handles only byte-sized integers, this solution reads in and writes out bytes. The TIO is set up to use the \x00 notation for this.
This Chip solution uses a straightforward approach where the columns are the operations, and the rows are for each bit:
Read in an octet
|Invert all bits
||Increment
|||Invert all bits except the lowest bit
||||Increment
|||||Output the octet
||||||
* *
A~#-#a
B~#~#b
C~#~#c
D~#~#d
E~#~#e
F~#~#f
G~#~#g
H~#~#h
J-uby, 12 bytes
:-@|:^&1|:-@
Explanation
:-@| negate n
:^&1| XOR it with 1
:-@ negate that
With a change I just pushed to GitHub (inspired by this question, but overall useful), it becomes 10 bytes:
:-|:^&1|:-
Ruby, 12 bytes
->n{-(-n^1)}
Clojure, 21 bytes
#(+(if(odd? %)1 -1)%)
It is quite difficult to get creative with this.
x86 machine code, 8 bytes
Load register al with an 8 bit integer
A8 01 (test al, 1; and whatever is in al with one, fast and small method for checking odd/even)
74 04 (jz 8; jump to even code if zf (zero flag, will be set if above instruction returns 0) is set)
04 02 (add al, 2; Two, because the next instruction will subtract one again, as if I incremented and jumped past the dec but shorter and faster)
FE C8 (dec al; Explained above, this is the code that is jumped to if input is even)
If you want, here is some actual assembly in boot-sector format. Just assemble this with nasm filename.asm and run qemu-system-i386 filename to test it. Press a key, and you will see that it will be the next letter if the ascii code was odd, or previous if it was even.
[ORG 0x7C00]
start:
xor ah, ah ;bios keyboard: get character (xoring a register with itself is a fast way to set it to 0 which is what we need)
int 0x16 ; keyboard io bios interrupt
mov ah, 0x0e ;bios graphics: display character (get ready)
test al, 0x01
jz even
add al, 2
even:
dec al
int 0x10 ; we already set al to 0E: display character, which takes a character from al and outputs that.
jmp start ; just go back to the start and get another character
times 510-($-$$) db 0 ; bootsector padding/signature
db 0x55
db 0xAA
Almost forgot, I should probably add the original assembly code that I used to create the bytes above
test al, 0x01
jz even
;odd code
add al, 2
even:
dec al
Python, 68 bytes
lambda x:[m.floor(x-m.cos(m.pi*x)) for m in [__import__('math')]][0]
In the spirit of a unique approach. The following graph shows the function (with purple dots representing the first 10 cases). It should in theory be possible to construct a solution for this question based on most (all?) periodic functions (e.g. sin, tan, sec). In fact, substituting cos for sec in the code as is should work.
Befunge-93, 11 bytes
&:2%2*1-+.@
[Try it online!]
Explanation:
Stack representation: bottom [A, B, C top
&: Pushes 2 copies of the input, N: [N, N
2% Mods the top copy by 2, so it's either 1 or 0: [N, (N % 2)
2* Multiplies that by 2, so that it's either 2 or 0: [N, ((N % 2) * 2)
1- Subtracts 1, so it's either 1 or -1: [N, (((N % 2) * 2) - 1)
+ Adds the 2 together. -1 for evens, and 1 for odds: [(N-1) or [(N+1)
.@ Prints and ends
Befunge-98 Variant, 10 bytes
This program can be trivially modified for Befunge-98 by removing the @, meaning the program will wrap around to the & and end:
&:2%2*1-+.
Actually, 6 bytes
;0Dⁿ@-
Try it online, or run all test cases at once!
Explanation:
;0Dⁿ@-
;0Dⁿ (-1)**n
@- n - (above)
Pyth, 10 bytes
+Q?%Q2 1_1
As simple as using modulo of input with 2 and the ternary operator.
QBIC, 15 10 bytes
:?a-(-1)^a
Saved a lot by using a different calculation.
Explanation:
: Get a number frm the cmd line as var a
? PRINT
a-(-1)^a a decreased by 1 for when even, or -1 (adding one) when odd.
QBasic (and QBIC) need the parenteses around (-1), because code like -1^2 is otherwise seen as negate 1*1 = negate 1 = -1...
Excel VBA 27 bytes
[a2]=iif(n mod 2=0,n-1,n+1)
x86 Assembly, 9 bytes (for competing entry)
Everyone who is attempting this challenge in high-level languages is missing out on the real fun of manipulating raw bits. There are so many subtle variations on ways to do this, it's insane—and a lot of fun to think about. Here are a few solutions that I devised in 32-bit x86 assembly language.
I apologize in advance that this isn't the typical code-golf answer. I'm going to ramble a lot about the thought process of iterative optimization (for size). Hopefully that's interesting and educational to a larger audience, but if you're the TL;DR type, I won't be offended if you skip to the end.
The obvious and efficient solution is to test whether the value is odd or even (which can be done efficiently by looking at the least-significant bit), and then select between n+1 or n−1 accordingly. Assuming that the input is passed as a parameter in the ECX register, and the result is returned in the EAX register, we get the following function:
F6 C1 01 | test cl, 1 ; test last bit to see if odd or even
8D 41 01 | lea eax, DWORD PTR [ecx + 1] ; set EAX to n+1 (without clobbering flags)
8D 49 FF | lea ecx, DWORD PTR [ecx - 1] ; set ECX to n-1 (without clobbering flags)
0F 44 C1 | cmovz eax, ecx ; move in different result if input was even
C3 | ret
(13 bytes)
But for code-golf purposes, those LEA instructions aren't great, since they take 3 bytes to encode. A simple DECrement of ECX would be much shorter (only one byte), but this affects flags, so we have to be a bit clever in how we arrange the code. We can do the decrement first, and the odd/even test second, but then we have to invert the result of the odd/even test.
Also, we can change the conditional-move instruction to a branch, which may make the code run more slowly (depending on how predictable the branch is—if the input alternates inconsistently between odd and even, a branch will be slower; if there's a pattern, it will be faster), which will save us another byte.
In fact, with this revision, the entire operation can be done in-place, using only a single register. This is great if you're inlining this code somewhere (and chances are, you would be, since it's so short).
48 | dec eax ; decrement first
A8 01 | test al, 1 ; test last bit to see if odd or even
75 02 | jnz InputWasEven ; (decrement means test result is inverted)
40 | inc eax ; undo the decrement...
40 | inc eax ; ...and add 1
InputWasEven: ; (two 1-byte INCs are shorter than one 3-byte ADD with 2)
(inlined: 7 bytes; as a function: 10 bytes)
But what if you did want to make it a function? No standard calling convention uses the same register to pass parameters as it does for the return value, so you'd need to add a register-register MOV instruction to the beginning or end of the function. This has virtually no cost in speed, but it does add 2 bytes. (The RET instruction also adds a byte, and there is a some overhead introduced by the need to make and return from a function call, which means this is one example where inlining produces both a speed and size benefit, rather than just being a classic speed-for-space tradeoff.) In all, written as a function, this code bloats to 10 bytes.
What else can we do in 10 bytes? If we care at all about performance (at least, predictable performance), it would be nice to get rid of that branch. Here is a branchless, bit-twiddling solution that is the same size in bytes. The basic premise is simple: we use a bitwise XOR to flip the last bit, converting an odd value into an even one, and vice versa. But there is one niggle—for odd inputs, that gives us n-1, while for even inputs, it gives us n+1— exactly opposite of what we want. So, to fix that, we perform the operation on a negative value, effectively flipping the sign.
8B C1 | mov eax, ecx ; copy parameter (ECX) to return register (EAX)
|
F7 D8 | neg eax ; two's-complement negation
83 F0 01 | xor eax, 1 ; XOR last bit to invert odd/even
F7 D8 | neg eax ; two's-complement negation
|
C3 | ret ; return from function
(inlined: 7 bytes; as a function: 10 bytes)
Pretty slick; it's hard to see how that can be improved upon. One thing catches my eye, though: those two 2-byte NEG instructions. Frankly, two bytes seems like one byte too many to encode a simple negation, but that's the instruction set we have to work with. Are there any workarounds? Sure! If we XOR by -2, we can replace the second NEGation with an INCrement:
8B C1 | mov eax, ecx
|
F7 D8 | neg eax
83 F0 FE | xor eax, -2
40 | inc eax
|
C3 | ret
(inlined: 6 bytes; as a function: 9 bytes)
Another one of the oddities of the x86 instruction set is the multipurpose LEA instruction, which can do a register-register move, a register-register addition, offsetting by a constant, and scaling all in a single instruction!
8B C1 | mov eax, ecx
83 E0 01 | and eax, 1 ; set EAX to 1 if even, or 0 if odd
8D 44 41 FF | lea eax, DWORD PTR [ecx + eax*2 - 1]
C3 | ret
(10 bytes)
The AND instruction is like the TEST instruction we used previously, in that both do a bitwise-AND and set flags accordingly, but AND actually updates the destination operand. The LEA instruction then scales this by 2, adds the original input value, and decrements by 1. If the input value was odd, this subtracts 1 (2×0 − 1 = −1) from it; if the input value was even, this adds 1 (2×1 − 1 = 1) to it.
This is a very fast and efficient way to write the code, since much of the execution can be done in the front-end, but it doesn't buy us much in the way of bytes, since it takes so many to encode a complex LEA instruction. This version also doesn't work as well for inlining purposes, as it requires that the original input value be preserved as an input of the LEA instruction. So with this last optimization attempt, we've actually gone backwards, suggesting it might be time to stop.
Thus, for the final competing entry, we have a 9-byte function that takes the input value in the ECX register (a semi-standard register-based calling convention on 32-bit x86), and returns the result in the EAX register (as with all x86 calling conventions):
SwapParity PROC
8B C1 mov eax, ecx
F7 D8 neg eax
83 F0 FE xor eax, -2
40 inc eax
C3 ret
SwapParity ENDP
Ready to assemble with MASM; call from C as:
extern int __fastcall SwapParity(int value); // MSVC
extern int __attribute__((fastcall)) SwapParity(int value); // GNU
Pyth, 4 bytes
I'm new to Pyth, so please tell me if there are any things I can golf.
_x1_
Explanation:
_ Negate input
x1 Bitwise XOR with 1
_ Negate
Mathematica, 22 19 bytes
Saved 3 bytes thanks to Greg Martin!
#-1[-1][[#~Mod~2]]&
Previous answer, 22 bytes
#+{-1,1}[[#~Mod~2+1]]&
Explanation (for previous answer)
Mathematica has the nice feature that operations such as arithmetic automatically thread over lists.
In this case, we take Mod[#,2] which will return 0 or 1, but we need to add 1 because Mathematica lists are 1-indexed. If it's even, this comes out to 1, so #-1 is returned. If it's odd, this comes out to 2, so #+1 is returned.
SAS, 72 bytes
%macro t(n);%put%eval(&n+%sysfunc(ifn(%sysfunc(mod(&n,2)),1,-1)));%mend;
Groovy, 17 bytes
print x%2?x+1:x-1
Just substitute x for desired number. Try it online here -> https://tio.run/nexus/groovy and copy the code.
Python, 20 bytes
lambda n:n+(n&1)*2-1
Excel, 11 bytes
=A1-(-1)^A1
Assumes input in A1.
05AB1E, 7 bytes
D1(sm-Ä
Explanation:
D1(sm-Ä
Input (implicit). Is 3 for example. Stack: [3]
D Duplicate input. Stack: [3, 3]
1 Push 1. Stack: [3, 3, 1]
( Push opposite of top of stack. Stack: [3, 3, -1]
s Swap the top 2 items on the stack. Stack: [3, -1, 3]
m Push -1**3. Stack: [3, -1]
- Subtract. Stack: [4].
Ä Absolute value. Stack: [4].
Implicit output.
Brain-Flak, 36 bytes
(({})(())){({}[()]<([{}])>)}{}({}{})
I'm personally really happy with this answer because it is a lot shorter than what I would deem a traditional method of solving this problem.
Explanation
The first bit of code
(({})(()))
converts the stack from just n to
n + 1
1
n
Then while the top of the stack is non zero, we decrement it and flip the sign of the number under it
{({}[()]<([{}])>)}
The we remove the zero and add the two remaining numbers
{}({}{})
Fourier, 17 bytes
I~x^ox%2{0}{@xvo}
Explanation:
I~x - Stores input in a variable called x
x^o - Increments x and outputs
x%2{0}{ } - If x mod 2 == 0, do code inside brackets
@ - Clear screen
xvo - Decrements x and outputs
Cubix, 10 9 bytes
cO1)I(//@
Explanation
Net version
c O
1 )
I ( / / @ . . .
. . . . . . . .
. .
. .
The executed characters are
I(1c)O@
I Input
( Decrement
1c XOR with 1
) Increment
O@ Output and exit
AWK, 15 bytes
{$1+=$1%2*2-1}1
I could save 1 byte by using (-1)^$1, but then it would be pretty much the same as everyone else, and this is what I came up with before looking at other answers. :)
Cubix, 11 bytes
u%2!I(/+@O<
Explanation
Net version:
u %
2 !
I ( / + @ O < .
. . . . . . . .
. .
. .
Characters are executed in following order:
I(2%!+O@
I # Take a number as input
( # Decrement it
2% # Take the parity of the decremented number
# (0 if the input is odd, 1 if it's even)
! # If that number is zero:
+ # Add 2
O # Output the number
@ # Terminate the program
JavaScript (ES6), 14 13 12 10 bytes
n=>-(-n^1)
- 1 byte saved thanks to Luke.
- 2 bytes saved by porting feersum's C solution. (If that's frowned upon, please let me know and I'll roll back to my previous solution below)
Try It
f=
n=>-(-n^1)
i.addEventListener("input",_=>o.innerText=f(+i.value))
<input id=i type=number><pre id=o>
Original, 12 bytes
n=>n-1+n%2*2
Javascript, 17 12 bytes
x=>x-(-1)**x
f=x=>x-(-1)**x;
<input id=i oninput=o.innerText=f(this.value) type=number><pre id=o>
Another approach, 10 bytes stolen from the C answer (sssshhh)
x=>-(-x^1)
f=x=>-(-x^1)
<input id=i oninput=o.innerText=f(this.value) type=number><pre id=o>
Python3, 20 18 bytes
lambda n:n-1+n%2*2
Pretty simple. First we calculate n-1 and decide whether to add 2 to it, or not.
If n is even --> n mod 2 will be 0, thus we'll add 2*0 to n-1, resulting in n-1.
If n is odd --> n mod 2 will be 1, thus we'll add 2*1 to n-1, resulting in n+1.
I prefer an explanation that I made with MS paint & a laptop touchpad... 
Batch, 20 bytes
@cmd/cset/a"-(1^-%1)
Independently rediscovered @feersum's algorithm, honest!
Stack Cats, 3 + 3 (-n) = 6 bytes
-*-
Needs the -n flag to work with numeric input and output.
Explanation
Stack Cats is usually far from competitive, because of its limited set of commands (all of which are injections, and most of which are involutions) and because every program needs to have mirror symmetry. However, one of the involutions is to toggle the least-significant bit of a number, and we can offset the value with unary negation which also exists. Luckily, that gives us a symmetric program, so we don't need to worry about anything else:
- Multiply the input by -1.
* Toggle the least significant bit of the value (i.e. take it XOR 1).
- Multiply the result by -1.
Input and output are implicit at the beginning and end of the program, because taking input and producing output is not a reversible operation, so they can't be commands.
Retina, 21 bytes
.+
$*
^11(?=(11)*$)
Try it online! My first Retina answer with two trailing newlines! Explanation: The first two lines convert from decimal to unary. The third and fourth lines subtract two from even numbers. The last line converts back to decimal, but adds one too.
Java 8, 16 10 bytes
n->-(-n^1)
Java 7, 34 28 bytes
int c(int n){return-(-n^1);}
Boring ports of @feersum's amazing C answer.
Try it here.
Old answers:
Java 8, 16 bytes
n->n%2<1?n-1:n+1
Java 7, 34 bytes
int c(int n){return--n%2>0?n:n+2;}
Explanation (of old Java 7 answer):
The answer above is a shorter variant of int c(int n){return n%2<1?n-1:n+1;} by getting rid of the space.
int c(int n){ // Method with integer parameter and integer return-type
return--n%2>0? // If n-1 mod-2 is 1:
n // Return n-1
: // Else:
n+2; // Return n+1
} // End of method
PHP, 15 bytes
<?=-(-$argn^1);
MATL, 7 bytes
Q:HePG)
This avoids any arithmetical operations. Try it online!
Explanation
Consider input 4 as an example.
Q % Implicit input. Add 1
% STACK: 5
: % Range
% STACK: [1 2 3 4 5]
He % Reshape with 2 rows in column-major order. Pads with a zero if needed
% STACK: [1 3 5;
2 4 0]
P % Flip vertically
% STACK: [2 4 0;
1 3 5]
G % Push input again
% STACK: [2 4 0;
1 3 5], 4
) % Index, 1-based, in column major order. Implicitly display
% STACK: 3
Python, 20 bytes
lambda n:n+(n%2or-1)
n%2or-1 will return 1 if it's odd, but if it's even, n%2 is "false" (0), so it instead returns -1. Then we simply add that to n.
Previous solution, 23 bytes
lambda n:[n-1,n+1][n%2]
n%2 calculates the remainder when n is divided by 2. If it's even, this returns 0, and element 0 in this list is n-1. If it's odd, this returns 1, and element 1 in this list is n+1.
C, 29 bytes
a(int b){return b%2?b+1:b-1;}
