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

2
\$\begingroup\$

Perl 6, 9 bytes

*.map: !*

Usage:

say (*.map: !*)((0, 1, 1)) # (True False False)
\$\endgroup\$
2
\$\begingroup\$

Actually, 2 bytes

♂Y

Try it online!

Map () Boolean negate (Y)

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

Clojure, 12 bytes

#(map not %) 

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

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

Pyth, 2 bytes

!M

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ m! works aswell and makes more sense to me since you map the not over the input array. \$\endgroup\$ – KarlKastor Sep 15 '16 at 12:25
  • 1
    \$\begingroup\$ @KarlKastor They compile down to the same thing, assign("Q", eval_input()); imp_print(Pmap(lambda d: Pnot(d), Q)) \$\endgroup\$ – Steven H. Sep 15 '16 at 12:38
1
\$\begingroup\$

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

Groovy (19 Bytes)

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

Simple mapping function in a closure.

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

Stata, 20 bytes

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

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

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

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

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

Scala, 27 bytes

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

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

\$\endgroup\$
  • \$\begingroup\$ The type annotation isn't required is it? Shouldn't it be able to infer the type from !? \$\endgroup\$ – Carcigenicate Sep 16 '16 at 13:22
  • \$\begingroup\$ @Carcigenicate Sadly, Scala can't infer the types of method arguments. \$\endgroup\$ – corvus_192 Sep 16 '16 at 22:14
  • \$\begingroup\$ Damn. Forgot about that. That's 9 bytes right there! \$\endgroup\$ – Carcigenicate Sep 16 '16 at 22:15
  • \$\begingroup\$ @Carcigenicate I can't use Int*, because that's neither truthy nor falsey. \$\endgroup\$ – corvus_192 Sep 16 '16 at 22:20
1
\$\begingroup\$

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.

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

sed 8

y,01,10,

Takes input as 1s and 0s.

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

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

Pyke, 2 bytes

m!

Try it here!

map(not, input)
\$\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\$

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

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

\$\endgroup\$
  • 6
    \$\begingroup\$ 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). \$\endgroup\$ – Martin Ender Sep 15 '16 at 12:48
  • 1
    \$\begingroup\$ As alternative, you can use streams directly: s->s.map(b->!b). I'm currently asking on meta if this is acceptable or not. \$\endgroup\$ – Olivier Grégoire Sep 15 '16 at 13:58
  • 2
    \$\begingroup\$ Hmmm... Also, you don't reference the packages, either in import or full text. \$\endgroup\$ – Olivier Grégoire Sep 15 '16 at 14:29
  • \$\begingroup\$ 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 ;). \$\endgroup\$ – Kevin Cruijssen Jan 24 '18 at 15:24
0
\$\begingroup\$

PHP , 45 Bytes

<?foreach($_GET[a]as$v)$a[]=1-$v;print_r($a);
\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – gabe3886 Sep 15 '16 at 16:13
  • \$\begingroup\$ Okay I'll try it \$\endgroup\$ – Jörg Hülsermann Sep 15 '16 at 16:22
  • 1
    \$\begingroup\$ You 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. \$\endgroup\$ – Ismael Miguel Sep 15 '16 at 20:43
0
\$\begingroup\$

 Common Lisp, 7

bit-not

Negate bits on a bit array.

Example

(bit-not #*00101010010100101001010010101)
=> #*11010101101011010110101101010
\$\endgroup\$
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\$
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
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
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
0
\$\begingroup\$

Emacs Lisp, 25 bytes

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

Not very creative.

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

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.