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

0
\$\begingroup\$

Tcl, 31 bytes

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

Try it online!

\$\endgroup\$
0
\$\begingroup\$

FALSE, 13 bytes

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

Input is a list of 0 and 1 characters.

\$\endgroup\$
0
\$\begingroup\$

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

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[].

\$\endgroup\$
  • \$\begingroup\$ For the suggested edit: making this a function would require a return type \$\endgroup\$ – Karl Napf Nov 15 '16 at 0:22
1
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ Yes, it is :) ...# \$\endgroup\$ – Shaun Wild Sep 23 '16 at 18:56
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
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
0
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ 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). \$\endgroup\$ – Qwerp-Derp Sep 22 '16 at 23:14
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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.

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

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

\$\endgroup\$
  • 2
    \$\begingroup\$ ! (1 byte) is enough. ! vectorizes automatically. \$\endgroup\$ – Dennis Sep 15 '16 at 21:36
  • \$\begingroup\$ In the console I had it didnt let me do that :(, plus thats a snippet, is it not? \$\endgroup\$ – Magic Octopus Urn Sep 16 '16 at 2:03
  • 1
    \$\begingroup\$ 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])). \$\endgroup\$ – Dennis Sep 16 '16 at 2:24
  • \$\begingroup\$ That's neat, technically 3 bytes for f=! though, unless just saying "!" is its own function works. \$\endgroup\$ – Magic Octopus Urn Sep 19 '16 at 15:09
  • \$\begingroup\$ By community consensus, ! is a valid answer on ois own. \$\endgroup\$ – Dennis Sep 19 '16 at 15:22
0
\$\begingroup\$

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

Racket 11 bytes

(map not l)

Testing:

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

(map not l)

Output:

'(#f #t #f)
\$\endgroup\$
0
\$\begingroup\$

Emacs Lisp, 25 bytes

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

Not very creative.

\$\endgroup\$
1
\$\begingroup\$

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]
}
\$\endgroup\$
1
\$\begingroup\$

Pyke, 2 bytes

m!

Try it here!

map(not, input)
\$\endgroup\$
2
\$\begingroup\$

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));
            }
        }
    }
\$\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
0
\$\begingroup\$

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'
\$\endgroup\$
  • \$\begingroup\$ If you prefer space-delimited output: s/pk/n32P/ \$\endgroup\$ – Joe Sep 17 '16 at 8:26
1
\$\begingroup\$

Racket, 15 bytes

(curry map not)

Basically the Haskell answer.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Carcigenicate Sep 22 '16 at 22:12
  • \$\begingroup\$ 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. \$\endgroup\$ – Winny Sep 24 '16 at 20:18
  • \$\begingroup\$ It actually uses a lambda symbol? Damn. That seems needlessly complicated :/ \$\endgroup\$ – Carcigenicate Sep 24 '16 at 21:09
  • \$\begingroup\$ (There is also lambda, but that's not applicable to code golfing at all.) \$\endgroup\$ – Winny Sep 25 '16 at 9:48
1
\$\begingroup\$

Gogh, 4 bytes

{!}m

Usage:

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

Scala, 36 35 34 bytes

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

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

\$\endgroup\$
0
\$\begingroup\$

Ruby, 30 bytes

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

"true,false" outputs false,true.

\$\endgroup\$
  • \$\begingroup\$ @EasterlyIrk Sorry didn't know about that. Newbie here \$\endgroup\$ – Jatin Dhankhar Sep 16 '16 at 15:53
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ This isn't a function or program, and preassumes x exists. \$\endgroup\$ – Carcigenicate Sep 16 '16 at 13:16
  • \$\begingroup\$ How is that different from the other examples? \$\endgroup\$ – user3810626 Sep 16 '16 at 23:08
  • \$\begingroup\$ 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. \$\endgroup\$ – Carcigenicate Sep 16 '16 at 23:16
0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – DJMcMayhem Sep 16 '16 at 21:28
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
0
\$\begingroup\$

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