# Invert a boolean array

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]

• How about arrays of 0 (false, all 0 bits) and -1 (true, all 1 bits)?
– Lynn
Sep 15 '16 at 11:52
• @Lynn While it's the OPs decision, I'd say it should be up to whether your language considers though truthy/falsy. Sep 15 '16 at 11:53
• Related. (Given the simplicity of the core task, I'd say the differences in format are significant enough that these aren't duplicates.) Sep 15 '16 at 12:28
• 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. Sep 15 '16 at 23:32

# 05AB1E, 1 byte

Code:

_


Explanation:

_     # Logical not


Try it online!

• I love the explanation Sep 17 '16 at 12:06

# 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> • Probably can't get shorter than that... – user100690 Mar 15 at 12:05 • Would simply map(b=>!b) count? May 7 at 2:45 • @MatthewJensen no because map is a method and not a regular function – user100690 May 7 at 8:01 # Jelly, 1 byte ¬  Try it online! ¬ is logical NOT (1 if false-y, else 0). C (“complement”, 1−z) also works. • I think @Dennis is going to have a hard time outgolfing you. Sep 15 '16 at 11:51 • @flawr It's just a matter of time before Dennis does it in 0 bytes or less. Sep 15 '16 at 14:02 • @EriktheGolfer "0 bytes or less" hmm Sep 17 '16 at 14:38 • @zdimension It's Dennis, he can do it shorter than you think (read the memes). Sep 17 '16 at 14:40 # Matlab, 4 1 byte This should be self explanatory. ~  Matlab has the one-byte negation operator ~, if you want a function you can use @not. • get @rgument, negate, output, terminate, right? Sep 15 '16 at 11:45 • Haha, right, I'm surprised you're so fluent in Matlab! Sep 15 '16 at 11:46 • lol, this sounds like Borat "This should be self explanatory .... NOT" Sep 15 '16 at 12:57 • surely ~ is an appropriate answer since it's an operator that receives an argument. I think ~[1,0,0,1,0] is entirely appropriate. Sep 16 '16 at 1:29 • @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. ;) Sep 16 '16 at 8:30 # Haskell, 7 bytes map not  Example: Prelude> (map not) [False, True, True] [True,False,False]  • You don't need the parenthesis in the example, right? Sep 15 '16 at 12:02 • I don’t, but I wanted to demonstrate in the example how my answer is a valid expression and not a snippet. – Lynn Sep 15 '16 at 12:07 • 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 Sep 15 '16 at 15:25 • and also you're not supposed to suggest code via edits anyway Sep 15 '16 at 18:18 • Can you do map(1-) and use [0,1,1] instead of [False, True, True]? May 7 at 2:55 # MATL, 1 byte ~  Try it online! ~ is the logical not and as many functions, it can also be applied to arrays/matrices. • Works in APL too. – Adám Sep 15 '16 at 12:47 # C, 46 Bytes recursive version f(char*s){*s?putchar(*s&72?*s:*s^1),f(++s):0;}  # C, 47 Bytes iterative version 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]  • Shorter than I expected to see for C! Sep 17 '16 at 17:28 # 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,] 0 1 1 1 [2,] 0 1 0 0 [3,] 0 0 0 0 [4,] 1 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.  • To save on submitting identical answers, this also works in Julia (except it doesn't work on numeric input there) Sep 15 '16 at 12:15 # 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)  • I was just trying to puzzle out the same thing. I only got as far as {!«@_} :) Sep 15 '16 at 18:39 • !** should work too – Jo King Nov 21 '19 at 5:57 # 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:

,:):/$.:, ,::)/)$.,
,:):%)$.,  • This forwards-backwards effect is really cool. Sep 15 '16 at 18:58 • I like this answer. It's happy. :) – Nic Sep 18 '16 at 0:16 ## 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, #]&. • How the !#&/@#& am I supposed to read that? :) – Lynn Sep 15 '16 at 11:32 • @Lynn Does that help? :) Sep 15 '16 at 11:44 • I'm surprised that Not isn't listable Sep 15 '16 at 15:35 • @ASimmons Yeah so was I. Sep 15 '16 at 15:45 # Python, 2725 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]  • 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 Sep 15 '16 at 11:52 • b^1 also works. – xnor Sep 15 '16 at 14:39 • @xnor And that would actually be better, because then the space before the for could be dropped. – user45941 Sep 16 '16 at 5:14 • I didn't realize that 1for would be parsed as two separate tokens. Huh, TIL. Sep 16 '16 at 5:20 # 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);  # 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. • An impressively short answer for a language that is terrible for golfing in. :) Sep 16 '16 at 18:24 • I feel like I broke a rule or something. I'm not sure how these are judged. :D Sep 16 '16 at 18:25 • This is awesome. – JAL Oct 11 '16 at 16:03 # 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: Works because given a list as input, Notes formula will apply whatever specified action to every element in the list. • Oh my god... My company just switched away from lotus notes; I had hoped to never see it again. +1 for that throwback. Sep 15 '16 at 17:46 • 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 :-) Sep 15 '16 at 18:18 # J, 2 bytes -.  This is the negation verb. ## Test case  -. 0 1 0 0 1 1 0 1 1 0  # Shakespeare Programming Language, 240 bytes . Ajax,. Puck,. Act I:. Scene I:. [Enter Ajax and Puck] Puck: Open your mind.Is hog as big as you?If so, let us return to scene II.You be sum of difference of zero and you and cat.Open thy heart!Let us return to scene I. Scene II:. [Exeunt]  Takes input as a string of \0 and \1 control characters. Outputs as a string of 0 or 1. If the input must be the same as the output, replace Open thy heart with Speak thy mind for no change in bytecount. If \0 and \1 can't be used, do the above, but also replace Open your mind with Listen to thy heart for a 5-byte penalty. Ungolfed: The Invertion of Veronan Arrays. Romeo, who stores the element. Juliet, who lectures him. Act I: In which an array is inverted. Scene I: A silent entrance. [Enter Romeo and Juliet] Scene II: In which Juliet pours out her heart to Romeo. Juliet: Open your mind. Is nothing better than thee? If so, let us proceed to scene III. Thou art as good as the sum of the difference between nothing and thee and my cat. Open your heart! Let us return to scene II. Scene III: Finale. [Exeunt]  This roughly translates to the following C pseudocode: int romeo; Scene1: romeo = getchar(); if (0 > romeo) goto Scene2; romeo = 0 - romeo + 1; printf("%d", romeo); goto Scene1; Scene2:;  I'm using this interpreter. Sample run: $ python splc.py invert.spl > invert.c
$gcc invert.c -o invert.exe$ echo -ne "\x00\x01\x00" | ./invert
101


# 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: {}


## 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  # 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


# Brachylog, 7 bytes

:{-$_}a  Try it online! ### Explanation :{ }a Apply this predicate to each element of the Input - Decrement$_       Negate


# Cheddar, 10 bytes

@.map((!))


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

• I think, equivalently, fn.vec((!)), if that was ever released :P Sep 15 '16 at 21:00

# Java, 58 bytes

void f(boolean[]a){for(boolean i:a)System.out.print(!i);}

• Ways to golf: change arr to a (saves 4 bytes), write int[]a instead of int a[] (saves 1 byte), Sep 15 '16 at 14:02
• oops! how do i forget it?how insane i am. and thanks @OlivierGrégoire Sep 15 '16 at 14:06

# brainfuck (58 Bytes)

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


Try it here

Ungolfed

-[>+<-----]>---     Number 48 (stands for 0)
[
<[->->+<<]      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
]                   Loop if input remaining


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

# Java, 15 bytes

s->s.map(b->!b)


Note: s is a java.util.stream.Stream<Boolean> and the import is not necessary, proof below.

## Testing and ungolfed

LookMaNoImports.java

class LookMaNoImports {
static Main.F f = s -> // transform a Stream<Boolean>
s.map(               // by applying its map method
b ->               // which in turns transforms a boolean
!b               // by applying its negation.
);
}


Main.java

    import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {

interface F {
Stream<Boolean> f(Stream<Boolean> s);
}

public static void main(String[] args) {
F f=LookMaNoImports.f;

test(f, new Boolean[]{true}, new Boolean[]{false});
test(f, new Boolean[]{false}, new Boolean[]{true});
test(f, new Boolean[]{true, false}, new Boolean[]{false, true});
test(f, new Boolean[]{true, true}, new Boolean[]{false, false});
}

static void test(F f, Boolean[] param, Boolean[] expected) {
List<Boolean> result = f.f(Arrays.stream(param)).collect(Collectors.toList());
if (result.equals(Arrays.asList(expected))) {
System.out.printf("%s: OK%n", Arrays.toString(param));
} else {
System.out.printf("%s: NOT OK, expected %s%n", Arrays.toString(param), Arrays.toString(expected));
}
}
}


# Logicode, 9 8 bytes

out!binp


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 binp is binary input.

1 byte saved thanks to @daHugLenny

• I think you can remove the space between out and !binp. Sep 22 '16 at 23:32
• @daHugLenny Huh, I was not aware you could do that. Thanks! Sep 23 '16 at 6:59

# Binary Lambda Calculus, 64 bits = 8 bytes

0001011000000000010111001011111000001000001100101111011010000010


Try it online!

Note: This is a function and its list format is slightly different from the list format used by default in BLC’s I/O, so the TIO link doesn’t really do anything.

## Explanation

My function takes a list of Church booleans as input. The list encoding that it uses is the one where a list is encoded as its right fold function. i.e. The encoding of list is foldr list (in pseudo-Haskell). An example of this kind of list is \c n. c (T (c F n)), where T and F are the Church booleans for true and false, respectively. This example represents the list [true, false].

Here is the lambda calculus (pseudo-?)code that I used to get my BLC code:

\l. l (\a b. \c n. c (a (\x y. y) (\x y. x)) (b c n)) (\c n. n)


(\ is abstraction, \a b. ... means \a. \b. ..., abstraction extends as far as it can, and application is left-associative.)

I then represented it using De Bruijin indices:

\1 (\\\\2 (4 (\\1) (\\2)) (321)) (\\1)


Note that 321 means ((3)2)1, not literally a De Bruijin index using the number 321.

Then I used @ to represent application (i.e. @mn means m(n)).

\@@1\\\\@@2@@4\\1\\2@@321\\1


(Note that I transcribed this “by hand,” so if my answer doesn’t work, then it’s probably a problem with this.)

I then used this to get the BLC code. (See here for information about how the encoding works and more information about BLC.)

## The actual explanation is here

So I’m going to explain using a condensed version of the lambda calculus notation.

Note that my vocabulary, specifically “the accumulator’ and “the new element”, is probably wrong. I’m basically trying to paint the image of a for loop initializing the “accumulator” at a value and changing it each time it passes through a “new element” of the list.

\l.l(\abcn.c(a(\xy.y)(\xy.x))(bcn))(\cn.n)

\l.l(                             )(     )  Right fold of l.
\cn.n   Start the accumulator as the empty list.
\a                                     a is the new element.
b                                    b is the accumulator.
cn.c(                               Prepend...
a(\xy.y)(\xy.x)                  the logical negation of a
)(bcn)            to the accumulator.


(This is a high-level overview and it’s probably possible to explain some of these concepts a better way.)

# CJam, 4 bytes

{:!}


Input is a list of 0s and 1s.

Try it online!

# 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


# Retina, 3 bytes

%0


Try it online!

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