Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

A nice simple one

Input

Given a boolean array (Or an acceptable alternative), you can assume the array will never be more than 32 elements long.

[false, false, true, false, false]

Output

Invert every element of the array and output it.

[true, true, false, true, true]

Rules

  • You can write a full program or just a function
  • Standard loopholes apply
  • Shortest code in bytes, per language, wins!

Test cases

Input:
[true, false]
Output:
[false, true]

Input: //Example of acceptable alternative
[0,1,1]
Output:
[1,0,0]
share|improve this question
    
How about arrays of 0 (false, all 0 bits) and -1 (true, all 1 bits)? – Lynn yesterday
5  
    
Related. (Given the simplicity of the core task, I'd say the differences in format are significant enough that these aren't duplicates.) – Martin Ender yesterday
1  
More than code golf this looks to me like: what is the not operator in your favourite language? Additional points if it works on lists. – licorna yesterday

51 Answers 51

05AB1E, 1 byte

Code:

_

Explanation:

_     # Logical not

Try it online!

share|improve this answer

Jelly, 1 byte

¬

Try it online!

¬ is logical NOT (1 if false-y, else 0). C (“complement”, 1−z) also works.

share|improve this answer
11  
I think @Dennis is going to have a hard time outgolfing you. – flawr yesterday
12  
@flawr It's just a matter of time before Dennis does it in 0 bytes or less. – Erik the Golfer yesterday

Haskell, 7 bytes

map not

Example:

Prelude> (map not) [False, True, True]
[True,False,False]
share|improve this answer
    
You don't need the parenthesis in the example, right? – flawr yesterday
8  
I don’t, but I wanted to demonstrate in the example how my answer is a valid expression and not a snippet. – Lynn yesterday
2  
There was a suggested edit just now to make the code not<$>, but that’s not a valid expression; you can’t write f = not<$> and then f [False, True, True]; operator slices need parentheses around them, which would contribute towards the byte count. – Lynn yesterday
1  
and also you're not supposed to suggest code via edits anyway – undergroundmonorail yesterday

Matlab, 4 1 bytes

This should be self explanatory.

~

Matlab has the one-byte negation operator ~, if you want a function you can use @not.

share|improve this answer
18  
get @rgument, negate, output, terminate, right? – Martin Ender yesterday
1  
Haha, right, I'm surprised you're so fluent in Matlab! – flawr yesterday
    
lol, this sounds like Borat "This should be self explanatory .... NOT" – user2023861 yesterday
    
surely ~ is an appropriate answer since it's an operator that receives an argument. I think ~[1,0,0,1,0] is entirely appropriate. – Tasos Papastylianou yesterday
1  
@TasosPapastylianou Operator submissions are definitely valid (in some languages like Julia and Mathematica it's even common practice to define your own operators because that's shorter than defining your own function), but I'm sure flawr just doesn't want to invalidate my comment. ;) – Martin Ender 17 hours ago

Javascript ES6, 15 bytes

a=>a.map(b=>!b)

Not much explanation needed I guess

f=
a=>a.map(b=>!b)

a.innerHTML = `[true, false, 1, 0] => ${ f([true, false, 1, 0]) }`
<pre id=a>

share|improve this answer

MATL, 1 byte

~

Try it online!

~ is the logical not and as many functions, it can also be applied to arrays/matrices.

share|improve this answer
1  
Works in APL too. – Adám yesterday

R, 1 byte

!

Example:

> !c(TRUE, FALSE)
[1] FALSE  TRUE

It also works with numerical input:

> !c(1, 0)
[1] FALSE  TRUE

We're not restricted to one-dimensional arrays, either. Let's make a matrix, and randomly populate it with 0s and 1s:

> mat = matrix(rbinom(16, 1, .5), ncol=4)
> mat
     [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    1    1    0    1
[3,]    0    1    0    0
[4,]    0    1    1    0

We can invert this just as easily:

> !mat
      [,1]  [,2]  [,3]  [,4]
[1,]  TRUE FALSE FALSE FALSE
[2,]  TRUE FALSE  TRUE  TRUE
[3,]  TRUE  TRUE  TRUE  TRUE
[4,] FALSE FALSE FALSE  TRUE

We can continue to do this for arbitrary numbers of dimensions. Here's an example on a four-dimensional array:

> bigarray = array(rbinom(32, 1, 0.5), dim=c(2,2,2,2))
> bigarray
, , 1, 1

     [,1] [,2]
[1,]    0    0
[2,]    0    0

, , 2, 1

     [,1] [,2]
[1,]    1    0
[2,]    0    0

, , 1, 2

     [,1] [,2]
[1,]    0    1
[2,]    0    1

, , 2, 2

     [,1] [,2]
[1,]    1    0
[2,]    1    1

> !bigarray
, , 1, 1

     [,1] [,2]
[1,] TRUE TRUE
[2,] TRUE TRUE

, , 2, 1

      [,1] [,2]
[1,] FALSE TRUE
[2,]  TRUE TRUE

, , 1, 2

     [,1]  [,2]
[1,] TRUE FALSE
[2,] TRUE FALSE

, , 2, 2

      [,1]  [,2]
[1,] FALSE  TRUE
[2,] FALSE FALSE

Doesn't work for characters, I'm afraid.

> !"Hello world"
Error in !"Hello world" : Invalid argument type.
share|improve this answer
1  
To save on submitting identical answers, this also works in Julia (except it doesn't work on numeric input there) – Sp3000 yesterday

C, 47 Bytes

f(char*s){for(;*s;putchar(*s&72?*s:*s^1),s++);}

Run using this main function

main(c,v)char**v;
{
    f(v[1]);
}

and input like this

a.exe [1,0,1,1,0]
[0,1,0,0,1]
share|improve this answer

Labyrinth, 9 bytes

,$:)%#$.,

Try it online! Assumes newline-separated input with a trailing newline. Thanks to @MartinEnder for help with golfing.

This program's a bit weird for a Labyrinth program - it doesn't make use of the 2D nature of the language, and it actually bounces back and forth. On the first forward trip, we have:

[Moving rightward]
,            Read char c of input
 $           XOR c with implicit 0 at bottom of stack
  :)%        Calculate c % (c+1), erroring out if c == -1 from EOF, otherwise returns c
     #$      XOR with (length of stack == 1)
       .     Output (c^1) as char
        ,    Read newline

[Moving leftward]
       .     Output newline
      $      XOR two implicit 0s, stack [0]
    %#       Mod with (length of stack == 1), giving stack [0]
 $:)         Increment, duplicate then XOR, stack still [0]
,            Read char c of input

The next occurence of $ then XORs the existing 0 on the stack with c, as opposed to an implicit 0 at the bottom of the stack like in the first run. Both situations leave the stack as [c], and the program repeats thereafter.

Alternative 9-bytes:

,:):/$.:,
,::)/)$.,
,:):%)$.,
share|improve this answer
1  
This forwards-backwards effect is really cool. – DLosc yesterday

J, 2 bytes

-.

This is the negation verb.

Test case

   -. 0 1 0 0 1
1 0 1 1 0
share|improve this answer

Python, 27 25 24 bytes

Thanks to Lynn for golfing off two bytes, and xnor and Mego for golfing off another.

lambda a:[b^1for b in a]
share|improve this answer
1  
Arrays of 0/1 are allowed, and 1-b is shorter than not b. I asked the OP if arrays of 0/-1 are allowed, in which case ~b is even shorter. – Lynn yesterday
2  
b^1 also works. – xnor yesterday
    
@xnor And that would actually be better, because then the space before the for could be dropped. – Mego 20 hours ago
    
I didn't realize that 1for would be parsed as two separate tokens. Huh, TIL. – Steven H. 20 hours ago

Mathematica, 7 bytes

Not/@#&

or without letters:

!#&/@#&

As for the syntactic sugar: & marks the right end of an unnamed function and has very low precedence. # refers to the first argument of the nearest and enclosing &. ! is the operator for Not. So !#& is just an unnamed function that negates its argument, in other words its identical to the built-in Not. /@ is the operator for Map. So the code would also be equivalent to the somewhat more readable Map[Not, #]&.

share|improve this answer
9  
How the !#&/@#& am I supposed to read that? :) – Lynn yesterday
1  
@Lynn Does that help? :) – Martin Ender yesterday
2  
I'm surprised that Not isn't listable – A Simmons yesterday
    
@ASimmons Yeah so was I. – Martin Ender yesterday

JAISBaL, 1 byte

!

Like all the other 1-byte answers, this is the negation operator, which can operate over an array if needed. This leaves the output on the stack, which is printed at the end of the program.

For two bytes, the array can be explicitly printed:

Input is in JAISBaL's incredibly odd array format (which I did invent, but I don't like it...).

Test Cases (Output from the Java interpreter, 3.0.5):

Enter a value > [true][false]


--------------------
Stack: [[false, true]]
Locals: {}
----------------------------------------
Enter a value > [false][false][true][false][false]


--------------------
Stack: [[true, true, false, true, true]]
Locals: {}
share|improve this answer

IBM/Lotus Notes Formula, 2 bytes

!a

Usage:

Create a Notes form with two fields named a and b.

a (input) = editable, number, multi-value, comma separated

b (output) = computed, number, multi-value, comma separated

Paste the above formula into b and give a a default value of 0.

Create a new document with the form, enter a binary list in a and press F9 to update the output.

Examples:

enter image description here

enter image description here

enter image description here

Works because given a list as input, Notes formula will apply whatever specified action to every element in the list.

share|improve this answer
1  
Oh my god... My company just switched away from lotus notes; I had hoped to never see it again. +1 for that throwback. – carusocomputing yesterday
    
I think many companies are @carusocomputing and probably rightly so. I've been working with it on and off for over 20 years and it still amazes me what formula language can do with list iterations sometimes. It's fun to open up designer occasionally and see how much I can still remember :-) – ElPedro yesterday

Perl, 7 bytes

Includes +2 for -lp

Give each boolean value as 0 or 1 on its own line

invert.pl
1
1
0
^D

invert.pl:

#!/us/bin/perl -lp
$_^=1
share|improve this answer

Cheddar, 10 bytes

@.map((!))

I hope I counted right as I'm writing from phone

share|improve this answer
    
I think, equivalently, fn.vec((!)), if that was ever released :P – Conor O'Brien yesterday

Java, 58 bytes

void f(boolean[]a){for(boolean i:a)System.out.print(!i);}
share|improve this answer
    
Ways to golf: change arr to a (saves 4 bytes), write int[]a instead of int a[] (saves 1 byte), – Olivier Grégoire yesterday
    
oops! how do i forget it?how insane i am. and thanks @OlivierGrégoire – numberknot yesterday

brainfuck (58 Bytes)

-[>+<-----]>--->,[<[->->+<<]>[--<]>[>]<[-<+<+>>]<+.[-]<>,]

Try it here

Ungolfed

-[>+<-----]>---     Number 48 (stands for 0)
>,                  Read in first point
[               
    <[->->+<<]      Subtract 1 from 48 flag, subtract 1 from read data, add 1 for new flag
    >           
    [--<]           If sitting on 1 (true) subtract 2 and move left)
        >[>]<       Move to 48 flag
        [-<+<+>>]   Add 48 to data point
        <+.[-]<     Add 1 move print, zero cell, move to new 48 cell
        >,          Read in next point
]                   Loop if input remaining

Takes an input of undivided 1s or 0s (11001).

share|improve this answer

Perl 6, 4 bytes

"French"/Unicode version:

!«*

"Texas"/ASCII version:

!<<*

Input is a single value which can be treated as a list.

This is a a Whatever lambda (*) with the logical not prefix operator (!) combined using prefix hyper operator («).

Effectively this is the same as:

-> $_ { $_.values.hyper.map: &prefix:<!> }
# ( currently the Rakudo implementation doesn't actually do the 「.hyper」 call,
#   but prefix 「«」 is specifically designated for doing things in parallel )

Usage:

# pretend it's a method
say (True,False,True,True).&( !«* );
# (False True False False)

say ( !«* )( (False,False,True,False,False) );
# (True True False True True)


# give it a lexical name
my &list-invert = !«*;

#              v¯¯ a space is necessary here
say list-invert (True,False);
# (False True)

say (False,True).&list-invert;
# (True False)
share|improve this answer
    
I was just trying to puzzle out the same thing. I only got as far as {!«@_} :) – hobbs yesterday

C#, 19 bytes

as an annonymous function, takes a bool[] and returns an IEnumerable

b=>b.Select(x=>!x);

or in 36 bytes with

dynamic f(bool[]b)=>b.Select(x=>!x);
share|improve this answer

CJam, 4 bytes

{:!}

Input is a list of 0s and 1s.

Try it online!

share|improve this answer

Brachylog, 7 bytes

:{-$_}a

Try it online!

Explanation

:{   }a   Apply this predicate to each element of the Input
  -         Decrement
   $_       Negate
share|improve this answer

PowerShell, 15 bytes

$args[0]|%{!$_}

I think this may even work in v1, hence I left the version number off the title. Loops through the input $args and negates each item in turn. That resulting array is left on the pipeline.

The neat thing, however, is because PowerShell is so loose on its casting requirements, you can do a completely mixed input and get an appropriate Boolean output. For example, here are the literal Boolean values $false/$true, the numbers 0 1 and 123456789 as integers, an empty string, a non-empty string, an empty array, and a non-empty array --

PS C:\Tools\Scripts\golfing> .\invert-a-boolean-array.ps1 @($false,$true,0,1,123456789,'','foo',@(),@(1,1))
True
False
True
False
False
True
False
True
False
share|improve this answer

Japt, 3 bytes

¡!X

Japt doesn't have boolean input, so input is an array of 0s and 1s. Test it online!

How it works

¡    // Map each item X in the input to
 !X  //  the boolean NOT of X.
     // Implicit output
share|improve this answer

Retina, 3 bytes

%`0

Try it online!

For each line (%), count the number of 0s.

share|improve this answer

Python 2, 24 bytes (non-competing)

lambda a:[i-1for i in a]

Logic is similar to Steven's, but I tried to use this comment's idea, but different, because it still takes 0/1 arrays, not 0/-1. There is no byte shaving for using 0/-1, so let's be sane. Note that this is non-competing, until Steven or Lynn allows me to use the idea. If so, I might remove the non-competing mark. Note that this code cannot be shamelessly stolen, it's still here. Only Steven can use it for his answer.

share|improve this answer

Perl 6, 9 bytes

*.map: !*

Usage:

say (*.map: !*)((0, 1, 1)) # (True False False)
share|improve this answer

Logicode, 10 bytes

out !input

Simple, really.

Takes input as a binary string, as Logicode doesn't have support for lists (so [true, false] would be 10).

The out outputs the line's result.

The ! command calculates the NOT of every bit in the string, so something like !111 would be 000.

The input is input.

share|improve this answer

Clojure, 12 bytes

#(map not %) 

Basically the same as the Haskell answer. Unfortunately, Clojure doesn't have implicit partial application; thus the function macro.

share|improve this answer

Swift 3 (7 bytes)

.map(!)

e.g.

[true, false].map(!)

Explanation

Seems pretty obvious. Calls map on the array [true, false]. The one "gotcha" is that, in Swift, operators are just functions and can be passed around as arguments. This means map(!) is passing the "not" function ! into map.

share|improve this answer
    
An impressively short answer for a language that is terrible for golfing in. :) – DJMcMayhem 7 hours ago
    
I feel like I broke a rule or something. I'm not sure how these are judged. :D – mklbtz 7 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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