19
\$\begingroup\$

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

68 Answers 68

26
\$\begingroup\$

05AB1E, 1 byte

Code:

_

Explanation:

_     # Logical not

Try it online!

\$\endgroup\$
  • 5
    \$\begingroup\$ I love the explanation \$\endgroup\$ – Stephan Bijzitter Sep 17 '16 at 12:06
14
\$\begingroup\$

Jelly, 1 byte

¬

Try it online!

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

\$\endgroup\$
  • 12
    \$\begingroup\$ I think @Dennis is going to have a hard time outgolfing you. \$\endgroup\$ – flawr Sep 15 '16 at 11:51
  • 15
    \$\begingroup\$ @flawr It's just a matter of time before Dennis does it in 0 bytes or less. \$\endgroup\$ – Erik the Outgolfer Sep 15 '16 at 14:02
  • 2
    \$\begingroup\$ @EriktheGolfer "0 bytes or less" hmm \$\endgroup\$ – zdimension Sep 17 '16 at 14:38
  • 1
    \$\begingroup\$ @zdimension It's Dennis, he can do it shorter than you think (read the memes). \$\endgroup\$ – Erik the Outgolfer Sep 17 '16 at 14:40
13
\$\begingroup\$

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>

\$\endgroup\$
12
\$\begingroup\$

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.

\$\endgroup\$
  • 22
    \$\begingroup\$ get @rgument, negate, output, terminate, right? \$\endgroup\$ – Martin Ender Sep 15 '16 at 11:45
  • 2
    \$\begingroup\$ Haha, right, I'm surprised you're so fluent in Matlab! \$\endgroup\$ – flawr Sep 15 '16 at 11:46
  • \$\begingroup\$ lol, this sounds like Borat "This should be self explanatory .... NOT" \$\endgroup\$ – user2023861 Sep 15 '16 at 12:57
  • \$\begingroup\$ surely ~ is an appropriate answer since it's an operator that receives an argument. I think ~[1,0,0,1,0] is entirely appropriate. \$\endgroup\$ – Tasos Papastylianou Sep 16 '16 at 1:29
  • 1
    \$\begingroup\$ @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. ;) \$\endgroup\$ – Martin Ender Sep 16 '16 at 8:30
10
\$\begingroup\$

Haskell, 7 bytes

map not

Example:

Prelude> (map not) [False, True, True]
[True,False,False]
\$\endgroup\$
  • \$\begingroup\$ You don't need the parenthesis in the example, right? \$\endgroup\$ – flawr Sep 15 '16 at 12:02
  • 9
    \$\begingroup\$ I don’t, but I wanted to demonstrate in the example how my answer is a valid expression and not a snippet. \$\endgroup\$ – Lynn Sep 15 '16 at 12:07
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ – Lynn Sep 15 '16 at 15:25
  • 2
    \$\begingroup\$ and also you're not supposed to suggest code via edits anyway \$\endgroup\$ – undergroundmonorail Sep 15 '16 at 18:18
10
\$\begingroup\$

MATL, 1 byte

~

Try it online!

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

\$\endgroup\$
  • 2
    \$\begingroup\$ Works in APL too. \$\endgroup\$ – Adám Sep 15 '16 at 12:47
10
\$\begingroup\$

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]
\$\endgroup\$
  • \$\begingroup\$ Shorter than I expected to see for C! \$\endgroup\$ – Chris Jefferson Sep 17 '16 at 17:28
10
\$\begingroup\$

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.
\$\endgroup\$
  • 1
    \$\begingroup\$ To save on submitting identical answers, this also works in Julia (except it doesn't work on numeric input there) \$\endgroup\$ – Sp3000 Sep 15 '16 at 12:15
8
\$\begingroup\$

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)
\$\endgroup\$
  • \$\begingroup\$ I was just trying to puzzle out the same thing. I only got as far as {!«@_} :) \$\endgroup\$ – hobbs Sep 15 '16 at 18:39
7
\$\begingroup\$

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:

,:):/$.:,
,::)/)$.,
,:):%)$.,
\$\endgroup\$
  • 2
    \$\begingroup\$ This forwards-backwards effect is really cool. \$\endgroup\$ – DLosc Sep 15 '16 at 18:58
  • \$\begingroup\$ I like this answer. It's happy. :) \$\endgroup\$ – Nic Hartley Sep 18 '16 at 0:16
6
\$\begingroup\$

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, #]&.

\$\endgroup\$
  • 11
    \$\begingroup\$ How the !#&/@#& am I supposed to read that? :) \$\endgroup\$ – Lynn Sep 15 '16 at 11:32
  • 1
    \$\begingroup\$ @Lynn Does that help? :) \$\endgroup\$ – Martin Ender Sep 15 '16 at 11:44
  • 4
    \$\begingroup\$ I'm surprised that Not isn't listable \$\endgroup\$ – A Simmons Sep 15 '16 at 15:35
  • \$\begingroup\$ @ASimmons Yeah so was I. \$\endgroup\$ – Martin Ender Sep 15 '16 at 15:45
6
\$\begingroup\$

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]
\$\endgroup\$
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – Lynn Sep 15 '16 at 11:52
  • 2
    \$\begingroup\$ b^1 also works. \$\endgroup\$ – xnor Sep 15 '16 at 14:39
  • \$\begingroup\$ @xnor And that would actually be better, because then the space before the for could be dropped. \$\endgroup\$ – Mego Sep 16 '16 at 5:14
  • \$\begingroup\$ I didn't realize that 1for would be parsed as two separate tokens. Huh, TIL. \$\endgroup\$ – Steven H. Sep 16 '16 at 5:20
6
\$\begingroup\$

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);
\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ Oh my god... My company just switched away from lotus notes; I had hoped to never see it again. +1 for that throwback. \$\endgroup\$ – Magic Octopus Urn Sep 15 '16 at 17:46
  • \$\begingroup\$ 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 :-) \$\endgroup\$ – ElPedro Sep 15 '16 at 18:18
5
\$\begingroup\$

J, 2 bytes

-.

This is the negation verb.

Test case

   -. 0 1 0 0 1
1 0 1 1 0
\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ An impressively short answer for a language that is terrible for golfing in. :) \$\endgroup\$ – DJMcMayhem Sep 16 '16 at 18:24
  • \$\begingroup\$ I feel like I broke a rule or something. I'm not sure how these are judged. :D \$\endgroup\$ – mklbtz Sep 16 '16 at 18:25
  • \$\begingroup\$ This is awesome. \$\endgroup\$ – JAL Oct 11 '16 at 16:03
5
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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: {}
\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

Brachylog, 7 bytes

:{-$_}a

Try it online!

Explanation

:{   }a   Apply this predicate to each element of the Input
  -         Decrement
   $_       Negate
\$\endgroup\$
3
\$\begingroup\$

Cheddar, 10 bytes

@.map((!))

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

\$\endgroup\$
  • 1
    \$\begingroup\$ I think, equivalently, fn.vec((!)), if that was ever released :P \$\endgroup\$ – Conor O'Brien Sep 15 '16 at 21:00
3
\$\begingroup\$

Java, 58 bytes

void f(boolean[]a){for(boolean i:a)System.out.print(!i);}
\$\endgroup\$
  • \$\begingroup\$ Ways to golf: change arr to a (saves 4 bytes), write int[]a instead of int a[] (saves 1 byte), \$\endgroup\$ – Olivier Grégoire Sep 15 '16 at 14:02
  • \$\begingroup\$ oops! how do i forget it?how insane i am. and thanks @OlivierGrégoire \$\endgroup\$ – Numberknot Sep 15 '16 at 14:06
3
\$\begingroup\$

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

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

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

\$\endgroup\$
  • \$\begingroup\$ I think you can remove the space between out and !binp. \$\endgroup\$ – acrolith Sep 22 '16 at 23:32
  • \$\begingroup\$ @daHugLenny Huh, I was not aware you could do that. Thanks! \$\endgroup\$ – Qwerp-Derp Sep 23 '16 at 6:59
2
\$\begingroup\$

CJam, 4 bytes

{:!}

Input is a list of 0s and 1s.

Try it online!

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

Retina, 3 bytes

%`0

Try it online!

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

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Ruby, 14 bytes

Anonymous function:

->a{a.map &:!}

Test it:

->a{a.map &:!}.call([true, true, false, true, false, true, true])
# => [false, false, true, false, true, false, false]
\$\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.