Invert a boolean array

19

3

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]

Shaun Wild

Posted 2016-09-15T10:50:45.677

Reputation: 2 329

How about arrays of 0 (false, all 0 bits) and -1 (true, all 1 bits)? – Lynn – 2016-09-15T11:52:03.913

5

@Lynn While it's the OPs decision, I'd say it should be up to whether your language considers though truthy/falsy.

– Martin Ender – 2016-09-15T11:53:15.473

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 – 2016-09-15T12:28:05.810

6More 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 – 2016-09-15T23:32:25.110

Answers

27

05AB1E, 1 byte

Code:

_

Explanation:

_     # Logical not

Try it online!

Adnan

Posted 2016-09-15T10:50:45.677

Reputation: 41 965

5I love the explanation – Stephan Bijzitter – 2016-09-17T12:06:16.320

14

Jelly, 1 byte

¬

Try it online!

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

Lynn

Posted 2016-09-15T10:50:45.677

Reputation: 55 648

12I think @Dennis is going to have a hard time outgolfing you. – flawr – 2016-09-15T11:51:16.617

15@flawr It's just a matter of time before Dennis does it in 0 bytes or less. – Erik the Outgolfer – 2016-09-15T14:02:28.620

2@EriktheGolfer "0 bytes or less" hmm – zdimension – 2016-09-17T14:38:50.967

1@zdimension It's Dennis, he can do it shorter than you think (read the memes). – Erik the Outgolfer – 2016-09-17T14:40:28.833

13

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>

Bassdrop Cumberwubwubwub

Posted 2016-09-15T10:50:45.677

Reputation: 5 707

12

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.

flawr

Posted 2016-09-15T10:50:45.677

Reputation: 40 560

22get @rgument, negate, output, terminate, right? – Martin Ender – 2016-09-15T11:45:51.963

2Haha, right, I'm surprised you're so fluent in Matlab! – flawr – 2016-09-15T11:46:51.130

lol, this sounds like Borat "This should be self explanatory .... NOT" – user2023861 – 2016-09-15T12:57:58.690

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 – 2016-09-16T01:29:22.113

besides, by that logic, you should be doing f=@not anyway. – Tasos Papastylianou – 2016-09-16T01:34:53.433

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 – 2016-09-16T08:30:36.493

10

Haskell, 7 bytes

map not

Example:

Prelude> (map not) [False, True, True]
[True,False,False]

Lynn

Posted 2016-09-15T10:50:45.677

Reputation: 55 648

You don't need the parenthesis in the example, right? – flawr – 2016-09-15T12:02:04.030

9I don’t, but I wanted to demonstrate in the example how my answer is a valid expression and not a snippet. – Lynn – 2016-09-15T12:07:48.020

3There 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 – 2016-09-15T15:25:12.407

2and also you're not supposed to suggest code via edits anyway – undergroundmonorail – 2016-09-15T18:18:27.657

10

MATL, 1 byte

~

Try it online!

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

flawr

Posted 2016-09-15T10:50:45.677

Reputation: 40 560

2Works in APL too. – Adám – 2016-09-15T12:47:33.407

10

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.

rturnbull

Posted 2016-09-15T10:50:45.677

Reputation: 3 689

1To save on submitting identical answers, this also works in Julia (except it doesn't work on numeric input there) – Sp3000 – 2016-09-15T12:15:29.803

10

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]

cleblanc

Posted 2016-09-15T10:50:45.677

Reputation: 3 360

Shorter than I expected to see for C! – Chris Jefferson – 2016-09-17T17:28:05.877

8

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)

Brad Gilbert b2gills

Posted 2016-09-15T10:50:45.677

Reputation: 12 713

I was just trying to puzzle out the same thing. I only got as far as {!«@_} :) – hobbs – 2016-09-15T18:39:12.590

!** should work too – Jo King – 2019-11-21T05:57:10.960

7

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:

,:):/$.:,
,::)/)$.,
,:):%)$.,

Sp3000

Posted 2016-09-15T10:50:45.677

Reputation: 58 729

2This forwards-backwards effect is really cool. – DLosc – 2016-09-15T18:58:57.557

I like this answer. It's happy. :) – Fund Monica's Lawsuit – 2016-09-18T00:16:57.313

6

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

Martin Ender

Posted 2016-09-15T10:50:45.677

Reputation: 184 808

11How the !#&/@#& am I supposed to read that? :) – Lynn – 2016-09-15T11:32:11.200

1@Lynn Does that help? :) – Martin Ender – 2016-09-15T11:44:45.977

4I'm surprised that Not isn't listable – A Simmons – 2016-09-15T15:35:15.563

@ASimmons Yeah so was I. – Martin Ender – 2016-09-15T15:45:07.220

6

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]

Steven H.

Posted 2016-09-15T10:50:45.677

Reputation: 2 841

1Arrays 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 – 2016-09-15T11:52:41.203

2b^1 also works. – xnor – 2016-09-15T14:39:07.293

@xnor And that would actually be better, because then the space before the for could be dropped. – Mego – 2016-09-16T05:14:14.510

I didn't realize that 1for would be parsed as two separate tokens. Huh, TIL. – Steven H. – 2016-09-16T05:20:21.087

6

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

hstde

Posted 2016-09-15T10:50:45.677

Reputation: 159

5

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.

ElPedro

Posted 2016-09-15T10:50:45.677

Reputation: 5 301

2Oh my god... My company just switched away from lotus notes; I had hoped to never see it again. +1 for that throwback. – Magic Octopus Urn – 2016-09-15T17:46:45.347

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 – 2016-09-15T18:18:35.337

5

J, 2 bytes

-.

This is the negation verb.

Test case

   -. 0 1 0 0 1
1 0 1 1 0

Conor O'Brien

Posted 2016-09-15T10:50:45.677

Reputation: 36 228

5

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.

mklbtz

Posted 2016-09-15T10:50:45.677

Reputation: 151

An impressively short answer for a language that is terrible for golfing in. :) – James – 2016-09-16T18:24:43.867

I feel like I broke a rule or something. I'm not sure how these are judged. :D – mklbtz – 2016-09-16T18:25:40.990

This is awesome. – JAL – 2016-10-11T16:03:20.453

5

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

Copper

Posted 2016-09-15T10:50:45.677

Reputation: 3 684

4

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

Socratic Phoenix

Posted 2016-09-15T10:50:45.677

Reputation: 1 629

4

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

AdmBorkBork

Posted 2016-09-15T10:50:45.677

Reputation: 41 581

4

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

Ton Hospel

Posted 2016-09-15T10:50:45.677

Reputation: 14 114

3

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

clismique

Posted 2016-09-15T10:50:45.677

Reputation: 6 600

I think you can remove the space between out and !binp. – acrolith – 2016-09-22T23:32:24.640

@daHugLenny Huh, I was not aware you could do that. Thanks! – clismique – 2016-09-23T06:59:39.273

3

Brachylog, 7 bytes

:{-$_}a

Try it online!

Explanation

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

Fatalize

Posted 2016-09-15T10:50:45.677

Reputation: 32 976

3

Java, 58 bytes

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

Numberknot

Posted 2016-09-15T10:50:45.677

Reputation: 885

Ways to golf: change arr to a (saves 4 bytes), write int[]a instead of int a[] (saves 1 byte), – Olivier Grégoire – 2016-09-15T14:02:44.590

oops! how do i forget it?how insane i am. and thanks @OlivierGrégoire – Numberknot – 2016-09-15T14:06:23.613

3

Cheddar, 10 bytes

@.map((!))

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

Downgoat

Posted 2016-09-15T10:50:45.677

Reputation: 27 116

1I think, equivalently, fn.vec((!)), if that was ever released :P – Conor O'Brien – 2016-09-15T21:00:43.083

3

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

gtwebb

Posted 2016-09-15T10:50:45.677

Reputation: 191

2

CJam, 4 bytes

{:!}

Input is a list of 0s and 1s.

Try it online!

Martin Ender

Posted 2016-09-15T10:50:45.677

Reputation: 184 808

2

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

ETHproductions

Posted 2016-09-15T10:50:45.677

Reputation: 47 880

2

Retina, 3 bytes

%`0

Try it online!

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

Martin Ender

Posted 2016-09-15T10:50:45.677

Reputation: 184 808

2

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.

Erik the Outgolfer

Posted 2016-09-15T10:50:45.677

Reputation: 38 134

2

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]

daniero

Posted 2016-09-15T10:50:45.677

Reputation: 17 193

2

Julia (1 Byte - Thanks to Dennis [See Comments])

!

Map the logical not to all elements of collection y, works due to automatic vectorization (as Dennis explained). My previous answer was basically using `f(n)=map(!,n)' to map the logical not, but Julia does this on it's own. Jeez, what a cool language. Second time using it, still trying to learn here!

Try it here

Magic Octopus Urn

Posted 2016-09-15T10:50:45.677

Reputation: 19 422

2! (1 byte) is enough. ! vectorizes automatically. – Dennis – 2016-09-15T21:36:18.150

In the console I had it didnt let me do that :(, plus thats a snippet, is it not? – Magic Octopus Urn – 2016-09-16T02:03:09.447

1

I've tested it with version 0.4; it's possible that it doesn't work in older versions of Julia. ! by itself evaluates to a function, which can be saved in a variable (just like a lambda), and is therefore considered a valid function submission. For.example, you can use it like f=!;print(f([true,false])).

– Dennis – 2016-09-16T02:24:43.237

That's neat, technically 3 bytes for f=! though, unless just saying "!" is its own function works. – Magic Octopus Urn – 2016-09-19T15:09:58.787

By community consensus, ! is a valid answer on ois own.

– Dennis – 2016-09-19T15:22:08.703

2

Perl 6, 9 bytes

*.map: !*

Usage:

say (*.map: !*)((0, 1, 1)) # (True False False)

bb94

Posted 2016-09-15T10:50:45.677

Reputation: 1 831

2

Actually, 2 bytes

♂Y

Try it online!

Map () Boolean negate (Y)

Mego

Posted 2016-09-15T10:50:45.677

Reputation: 32 998

2

Clojure, 12 bytes

#(map not %) 

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

Carcigenicate

Posted 2016-09-15T10:50:45.677

Reputation: 3 295

2

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));
            }
        }
    }

Olivier Grégoire

Posted 2016-09-15T10:50:45.677

Reputation: 10 647

1

Pyth, 2 bytes

!M

Explanation: (M)ap boolean not (!) over input.

Try it online!

Steven H.

Posted 2016-09-15T10:50:45.677

Reputation: 2 841

m! works aswell and makes more sense to me since you map the not over the input array. – KarlKastor – 2016-09-15T12:25:25.090

1@KarlKastor They compile down to the same thing, assign("Q", eval_input()); imp_print(Pmap(lambda d: Pnot(d), Q)) – Steven H. – 2016-09-15T12:38:42.750

1

Hoon, 24 bytes

|*
*
(turn +< |=(? !+<))

Creates a generic gate, map over the contents of the list, negate all loobeans in it.

This uses the normal Hoon tricks, namely using a generic ("wet"/|*) gate to avoid having to specify the sample type, along with having unnamed samples (* or ?) and using tree navigation syntax (+<) to fetch them.

> a 
~[%.y %.n %.n %.y %.n %.y] 
> =f |* 
  * 
  (turn +< |=(? !+<)) 
> (f a) 
~[%.n %.y %.y %.n %.y %.n] 

RenderSettings

Posted 2016-09-15T10:50:45.677

Reputation: 620

1

braingasm, 9 bytes

,[48-z:,]

Assumes that input from stdin is a string of only "0"s and "1"s, i.e. bytes containing the value 48 or 49. Prints the negated values to stdout.

How it works: Read one byte from stdin (,), and loop ([]) until the end of the input. For each byte, subtract 48 (48-) and print 1 if the result is 0 and vice versa (z is the zero-flag, : prints the given integer value), then get another byte from stdin (,)

Run it like e.g. $ echo -n 001011 | braingasm invert.bg and get 110100

daniero

Posted 2016-09-15T10:50:45.677

Reputation: 17 193

1

Groovy (19 Bytes)

{x->x.collect{!it}}

Simple mapping function in a closure.

Magic Octopus Urn

Posted 2016-09-15T10:50:45.677

Reputation: 19 422

1

Clojure, 12 bytes

(map not x)

as in:

(map not [true false true])

=> (false true false)

Updating due to the objection that this is not a function or program:

#(map not %)

Returns a function that nots anything passed to it.

user3810626

Posted 2016-09-15T10:50:45.677

Reputation: 111

This isn't a function or program, and preassumes x exists. – Carcigenicate – 2016-09-16T13:16:06.460

How is that different from the other examples? – user3810626 – 2016-09-16T23:08:20.740

Because the other answers are (mostly) all functions, and don't assume the existence of a variable for their code to work. Your second example is fine though. – Carcigenicate – 2016-09-16T23:16:41.177

1

Stata, 20 bytes

recode x (0=1) (1=0)

x is the input, and the rest is self-explanatory

f1rstguess

Posted 2016-09-15T10:50:45.677

Reputation: 181

1

Scala, 27 bytes

def f(a:Boolean*)=a map(!_)

Takes a bool array as varargs and maps each element to its inverse.

corvus_192

Posted 2016-09-15T10:50:45.677

Reputation: 1 889

The type annotation isn't required is it? Shouldn't it be able to infer the type from !? – Carcigenicate – 2016-09-16T13:22:48.843

@Carcigenicate Sadly, Scala can't infer the types of method arguments. – corvus_192 – 2016-09-16T22:14:34.110

Damn. Forgot about that. That's 9 bytes right there! – Carcigenicate – 2016-09-16T22:15:18.960

@Carcigenicate I can't use Int*, because that's neither truthy nor falsey. – corvus_192 – 2016-09-16T22:20:57.897

1

Kotlin, 13 bytes

{it.map{!it}}

This is a lambda of (List<Boolean>)->List<Boolean> type (or (BooleanArray)->List<Boolean>, as map function on arrays returns lists instead of arrays).

{it.map{!it}.toBooleanArray()} would return the result as an actual array.

JustACluelessNewbie

Posted 2016-09-15T10:50:45.677

Reputation: 161

1

sed 8

y,01,10,

Takes input as 1s and 0s.

Riley

Posted 2016-09-15T10:50:45.677

Reputation: 11 345

1

Scala, 36 35 34 bytes

def f(a:Array[Boolean])=a.map(!_)

Discovered I could remove the second space. Discovered I could remove brackets.

Himself12794

Posted 2016-09-15T10:50:45.677

Reputation: 61

1

Gogh, 4 bytes

{!}m

Usage:

$ ./gogh -noa '{!}m' "1 0 1 0 0 0 1"
[0 1 0 1 1 1 0]

Zach Gates

Posted 2016-09-15T10:50:45.677

Reputation: 6 152

1

Racket, 15 bytes

(curry map not)

Basically the Haskell answer.

Winny

Posted 2016-09-15T10:50:45.677

Reputation: 1 120

Making this a lambda might make this more succinct, no? I was going to partially apply for my answer (partial map not, Clojure), but a function macro ended up being smaller. Idk what Rackets anonymous functions look like though honestly. – Carcigenicate – 2016-09-22T22:12:26.570

Unfortunately Racket's shortest anonymous function uses the form of (λ (arguments) function-body), so it would be (λ(l)(map not l)) which is 18 bytes (the lambda symbol is two bytes). Interestingly, (map not(read)) is also 15 bytes. – Winny – 2016-09-24T20:18:31.403

It actually uses a lambda symbol? Damn. That seems needlessly complicated :/ – Carcigenicate – 2016-09-24T21:09:11.803

(There is also lambda, but that's not applicable to code golfing at all.) – Winny – 2016-09-25T09:48:46.437

1

Pyke, 2 bytes

m!

Try it here!

map(not, input)

Blue

Posted 2016-09-15T10:50:45.677

Reputation: 26 661

1

Golang, 40 bytes

func(a[]bool){for i,b:=range a{a[i]=!b}}

usage

package main
import "fmt"
func main() {
    a:=[]bool{true, true, false}
    func(a []bool){for i,b:=range a{a[i]=!b}}(a)
    fmt.Print(a) // => [false false true]
}

cia_rana

Posted 2016-09-15T10:50:45.677

Reputation: 441

1

PHP, 30 bytes

foreach($argv[1] as$i)echo!$i;

Testing code:

$argv[1] = [true,true,false,true,false,false,true,false];
foreach($argv[1] as$i)echo!$i;

Test online

Mario

Posted 2016-09-15T10:50:45.677

Reputation: 3 043

1

C++11, 30 bytes

As unnamed lambda:

[](auto&v){for(auto&x:v)x=!x;}

Accepts any standard container like vector<int> (but not vector<bool>) or int[] or bool[].

Karl Napf

Posted 2016-09-15T10:50:45.677

Reputation: 4 131

For the suggested edit: making this a function would require a return type – Karl Napf – 2016-11-15T00:22:58.123

0

SmileBASIC, 25 bytes

DEF l l
ARYOP 1,l,1,l
END

Explanation:

DEF 'create a function
    l 'named "L"
      l 'with 0 outputs and 1 input named "L"
ARYOP 'array operation
      1 'mode 1 (subtract)
       ,l 'set each element in L to...
         ,1 '1 minus...
           ,l 'the corresponding element in L
END 'end function definition

12Me21

Posted 2016-09-15T10:50:45.677

Reputation: 6 110

0

FALSE, 13 bytes

[49^$0>][-.]#

Input is a list of 0 and 1 characters.

12Me21

Posted 2016-09-15T10:50:45.677

Reputation: 6 110

0

Tcl, 31 bytes

proc N L {lmap b $L {expr !$b}}

Try it online!

sergiol

Posted 2016-09-15T10:50:45.677

Reputation: 3 055

It renders more bytes as a command line argument: https://tio.run/##K0nO@f@/oLSkWCE6JzexQCFJoVqrViWxKL1MoTq1oqBIQVElqTb2////BgoGCoZAbAAA

– sergiol – 2018-04-03T10:47:43.857

0

PHP , 45 Bytes

<?foreach($_GET[a]as$v)$a[]=1-$v;print_r($a);

Jörg Hülsermann

Posted 2016-09-15T10:50:45.677

Reputation: 13 026

As the question states 'Invert every element of the array and output it.' and people aren't usually too picky on output format, save 6 bytes by doing print_r($a); at the end – gabe3886 – 2016-09-15T16:13:40.260

Okay I'll try it – Jörg Hülsermann – 2016-09-15T16:22:07.920

1You don't need the spaces there. Your whole code can be written as <?foreach($_GET[a]as$v)$a[]=1-$v;print_r($a);. This saves 2 bytes and works. – Ismael Miguel – 2016-09-15T20:43:42.933

0

Java, 51 bytes

l.stream().map(b->!b).collect(Collectors.toList());

l = a Collection of Booleans I feel like this could be shorter, then again golfing in java ^^

dwana

Posted 2016-09-15T10:50:45.677

Reputation: 531

6

Unless the challenge says otherwise, all submissions need to be full programs or callable functions, as opposed to snippets which expect the input to be stored in a hardcoded variable. The shortest fix would probably be to wrap what you've got in a simple function body (or lambda, depending on Java version).

– Martin Ender – 2016-09-15T12:48:52.100

1

As alternative, you can use streams directly: s->s.map(b->!b). I'm currently asking on meta if this is acceptable or not.

– Olivier Grégoire – 2016-09-15T13:58:03.750

2Hmmm... Also, you don't reference the packages, either in import or full text. – Olivier Grégoire – 2016-09-15T14:29:54.533

If s->s.map(b->!b) that @OlivierGrégoire already posted wasn't allowed, you could still golf it by returning an Object-array l->l.stream().map(b->!b).toArray() instead (also, as stated by others, your current solution isn't valid. It should have a leading l->; Collectors should be java.util.stream.Collectors; and you can drop the trailing ;). – Kevin Cruijssen – 2018-01-24T15:24:35.870

0

 Common Lisp, 7

bit-not

Negate bits on a bit array.

Example

(bit-not #*00101010010100101001010010101)
=> #*11010101101011010110101101010

coredump

Posted 2016-09-15T10:50:45.677

Reputation: 6 292

0

Ruby, 30 bytes

gets.split(?,).map{|e|!eval e}

"true,false" outputs false,true.

Jatin Dhankhar

Posted 2016-09-15T10:50:45.677

Reputation: 141

@EasterlyIrk Sorry didn't know about that. Newbie here – Jatin Dhankhar – 2016-09-16T15:53:41.870

0

Swift(2.2) 44 bytes

I am using x as the input variable here. For example,

let x = [true,false]

¯\_(ツ)_/¯

Golfed

let y = {let b = $0.map({!$0});print(b);}(x)

unGolfed

let y = {
   let b = $0.map({!$0})
   print(b);
}(x)

Danwakeem

Posted 2016-09-15T10:50:45.677

Reputation: 141

0

PHP (231 Bytes)

function flip_bool_array($array) {
  $newarray = array();
  foreach ($array as $bool) {

   if ($bool === true) {
    $bool = false;
   } else {
    $bool = true;
   }

  $newarray[] = $bool;

}

return $newarray;

}

Explanation

The function accepts an array and loops over it testing each value for a true value and setting it to false, if the value is not true then it is set to true. Each boolean is added to a new array and returned.

Nicholas Koskowski

Posted 2016-09-15T10:50:45.677

Reputation: 101

Welcome to the site! You could take a ton of bytes off if you remove the extra whitespace, and shorten your variable names down to one letter each. Since the goal is just short code, readability is not important. Also, there's a great thread here for tips on golfing PHP code down further.

– James – 2016-09-16T21:28:32.300

0

dc, 44 bytes

Append this to a line of space-delimited input and echo it into dc. Output is delimited with newlines and punctuated with error messages (due to the blatant abuse of k). If you quote the stuff, it'll give you even more errors. (When we re-vamp dc in the next version, we should probably do something about that.) I suggest pairing with a 2>nul or other system-specific hack for suppressing whiny programs.

0sz[1r-SAlz1+szz0<a]dsax[lzd1-szLApk0<a]dsax

Explained:

              # "ToS" := "top of stack"
0sz           # Initialise register `z' with 0: this will hold the length of our input
[             # Open macro definition
 1r-          #  Replace ToS with !(ToS): 1-1==0, 1-0==1
 SA           #  Store this result on the top of stack `A'
 lz1+sz       #  Increment z, our length counter
 z0<a         #  If the stack depth is positive, repeat (we still have input to negate)
]dsax         # Store a copy of macro in register `a' and execute it
              # At this point, our input has been negated and stored in A,
              #  first-in-first-out orientation
[             # Open macro definition
 lzd1-sz      #  Decrement z and keep a copy of it for later
 LA           #  Push ToS(A) onto stack; pop from A
 p            #  Peek at ToS
 k            #  `k' is for KILL THE TOP OF STACK BWAHAHAHA
 0<a          #  The value from register `z' is now on top: if positive, we still have
              #   values to print, so repeat macro
]dsax         # I'm in a chaotic mood, so let's just re-use `a'

Joe

Posted 2016-09-15T10:50:45.677

Reputation: 895

If you prefer space-delimited output: s/pk/n32P/ – Joe – 2016-09-17T08:26:03.077

0

dc, 47 bytes

?zsN0sI[z:az0<A]dsAx[lI1+ddsI;a1r-n32PlN>R]dsRx

The actual code to invert a boolean (0 or 1) is 1r-. The rest is for reading the list and printing it in the same order, which is quite hard because of the (LIFO) stack that dc uses to store the input.

Explanation:

?zsN0sI         # read input, LIFO, initialize N = nr_elements and I = 0 (iterator)
[z:az0<A]dsAx   # loop A: move the stack content into array 'a' (I add a[n] first,
                #then a[n-1], ..., then a[1] and a[0] is not used)
[lI1+ddsI;a     # loop R: increment iterator and push a[I] to stack (input order)
   1r-n32P         #invert value and print it with a space separator
lN>R]dsRx       #repeat (R)

Run:

dc -f invert_boolean.dc <<< "1 0 1 1"

Output: there is a trailing separator (space) at the end, but I hope that's ok

0 1 0 0 

Note: my answer is similar in concept to that of @Joe's, but there are differences in terms of I/O handling, stack manipulation (I use arrays) and lack of warnings. Do check his answer as well.

seshoumara

Posted 2016-09-15T10:50:45.677

Reputation: 2 878

0

Emacs Lisp, 25 bytes

(lambda(x)(mapcar'not x))

Not very creative.

Lord Yuuma

Posted 2016-09-15T10:50:45.677

Reputation: 587

0

Racket 11 bytes

(map not l)

Testing:

(define l '(#t #f #t)) ; define a list of booleans

(map not l)

Output:

'(#f #t #f)

rnso

Posted 2016-09-15T10:50:45.677

Reputation: 1 635

0

><> Fish - 9 (16?) Bytes

My second golf and my first in ><> Fish!

l?!;r0=nr

I'm not sure how to count bytes when flags are considered, but this solution works when running the python interpreter with the -v flag and then space-separated 1's and 0's. If this doesn't match spec, I can remove the answer.

Example

Input/Run:

python fish.py --code "l?!;r0=nr" -v 0 1 0 1 1

Output:

10100

If I'm not allowed to use flags, and instead need to take the input from the input stack (such as on https://fishlanguage.com/playground), the code becomes longer as I must read from the input stack (either 1 or 0 without any separation) until there are no more values, and then convert the char value of the input (1 becomes 49 and 0 becomes 48) to their decimal values before my comparison. I'm not sure how to count bytes for ><> but I believe this would be 16 bytes.

i:1+?!;f3*3+-0=n

L. Steer

Posted 2016-09-15T10:50:45.677

Reputation: 57

0

Brainfuck, 72 69 61 bytes

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

Closest i managed to get as BF dosent have Array support

Formatting is stupid, i will fix it when i get a pc... Somehow it wont let me post it as a snippet

Håvard Nygård

Posted 2016-09-15T10:50:45.677

Reputation: 341

You could put all the lines together into one long line, it doesn't really matter for us (because with newlines, the total byte length is 78 bytes). – clismique – 2016-09-22T23:14:34.203

0

Brainfuck, 24 bytes

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

Try it online!

The same as my answer to a similar question.

Relies on 8-bit wrapping cells, the cell size might not matter (untested) but wrapping definitely is. The main part the program is the >++[->++[<]>-]>- does some rather convoluted things to flip the last bit of the number.

A shorter solution of 19 bytes is

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

but this requires the < to noop if the data index is 0, instead of the more typical implementation of going into negative indeces.

KSab

Posted 2016-09-15T10:50:45.677

Reputation: 5 984

0

dimwit 8 bytes (non-competing)

R1,0}0,1

Replaces all 0's with 1's, and vice versa.

Takes input through a string of 0's and 1's, and outputs similarly. Hopefully that's acceptable ;)

Try it here!

MCMastery

Posted 2016-09-15T10:50:45.677

Reputation: 783

1Yes, it is :) ...# – Shaun Wild – 2016-09-23T18:56:12.487