The shortest code to invert bit-wise a binary string

80

13

Me thinks there aren't enough easy questions on here that beginners can attempt!

The challenge: Given a random input string of 1's and 0's such as:

10101110101010010100010001010110101001010

Write the shortest code that outputs the bit-wise inverse like so:

01010001010101101011101110101001010110101

ToonAlfrink

Posted 2014-06-07T20:20:54.723

Reputation: 1 122

Answers

88

J, 5 bytes

Assumes the input string is in variable b.

b='0'

This does not do what it would do in most languages...

The J comparison operator is just = (=: and =. are global and local assignment, respectively). However, = doesn't work like the normal == operator: it compares item-by-item. Keep in mind that an array is formed like this: 0 2 3 2 3 1 2 3 4. 2 = 0 2 3 2 3 1 2 3 4 gives 0 1 0 1 0 0 1 0 0 for example. This is similar for a string: 'a'='abcadcadda' doesn't just return 0, it returns 1 0 0 1 0 0 1 0 0 1 (This can be extrapolated to mean 0 with */, which basically means all.) In this case however, this behavior is excelent, since we want a string of ones and zeros, or true's and false's. Since J's bools are 1 and 0, this results in an array of 1's and 0's (They aren't strings, and every other character other than 1 would also result in 0 in this array.) This doesn't need printing: J automatically prints the result of an expression. I hope this was adequate explanation, if not, please ask for something that isn't yet clear in the comments. This answer also could've been '0'&= (or =&'0'), but I felt that b='0' was clearer.

ɐɔıʇǝɥʇuʎs

Posted 2014-06-07T20:20:54.723

Reputation: 4 449

1What? It doesn't return the right result, does it? The result should have been a text string (without spaces), but with my limited knowledge of J, I think this will return a boolean list with a display form of 0 1 0 1 0 ... – Adám – 2015-09-25T15:14:55.553

The answer in J could also just be -.. – FUZxxl – 2016-01-02T17:38:02.123

4This isn't allowed because you can't assume the input is stored in a certain variable. =&'0' works for the same number of bytes. – Esolanging Fruit – 2017-06-13T08:21:06.587

Would you mind explaining how this works? I looked up some docs for J but I can't figure it out. – Jarett Millard – 2014-06-09T19:06:45.147

@Jarett There you go. – ɐɔıʇǝɥʇuʎs – 2014-06-09T19:36:35.767

1I have tried J. Can't bend my mind to it. Guess I haven't found good docs. Here, have a +1 for being a madman. – seequ – 2014-06-09T20:29:04.050

@TheRare I used 'Learning J' from the official J website. I still can't wrap my head around a lot of things, for example control structures and trains... – ɐɔıʇǝɥʇuʎs – 2014-06-09T21:07:16.697

1And this is why I will never use J. – Qix - MONICA WAS MISTREATED – 2014-06-09T23:49:42.857

2@Qix As unreadable as J is, this one actually makes sense to me, and other languages that have operators that take a vector LHS and a scalar RHS do behave similarly. – hvd – 2014-06-10T09:02:39.543

43

GolfScript, 5 bytes

{1^}%

Try it online.

How it works

  • GolfScript reads the entire input from STDIN and places it on the stack as a string.

  • {}% goes through all characters in the string and executes the code block for all of them.

  • 1^ computes the exclusive OR of the characters ASCII code with 1. “0” corresponds to the ASCII code 48, “1” to ASCII code 49.

    Since 48 ^ 1 = 49 and 49 ^ 1 = 48, this turns 0's into 1's and 1's into 0's.

  • Once finished, GolfScript prints the modified string.

Dennis

Posted 2014-06-07T20:20:54.723

Reputation: 196 637

6Wait, golfscript? – ToonAlfrink – 2014-06-07T20:28:09.527

I had misinterpreted your question. Fixed now. – Dennis – 2014-06-07T20:44:44.920

I'm always amazed at what can be accomplished in GolfScript. Would you mind explaining the code? – None – 2014-06-08T00:54:18.273

1@tolos: I've edited my answer. – Dennis – 2014-06-08T01:25:27.630

5@ToonAlfrink Golfing languages such as GolfScript are accepted in all challenges, as long as they are 'general-purpose' meaning that they are not designed for specific challenges. – kitcar2000 – 2014-06-08T13:05:53.930

4@kitcar2000 I think he was more surprised that such a language existed, rather than shock of someone daring to use GolfScript in a code golf question ;) – Chris Cirefice – 2014-06-10T14:56:15.183

35

CJam - 4

q1f^

This xor's every character with 1.
Unlike the other CJam answer, I'm not assuming the input is already on the stack.

Try it at http://cjam.aditsu.net/

aditsu quit because SE is EVIL

Posted 2014-06-07T20:20:54.723

Reputation: 22 326

2So that's how you use f. – Dennis – 2014-06-08T13:44:57.100

@Dennis Indeed. You can use the sf forum to ask questions btw :) – aditsu quit because SE is EVIL – 2014-06-08T15:47:42.043

31

x86 machine code on DOS - 14 13 11 bytes

Well, it did get shorter again! After writing a solution for an unrelated challenge, I noticed that the same trick could be applied even here. So here we go:

00000000  b4 08 cd 21 35 01 0a 86  c2 eb f7                 |...!5......|
0000000b

Commented assembly:

    org 100h

section .text

start:
    mov ah,8        ; start with "read character with no echo"
lop:
    ; this loop runs twice per character read; first with ah=8,
    ; so "read character with no echo", then with ah=2, so
    ; "write character"; the switch is performed by the xor below
    int 21h         ; perform syscall
    ; ah is the syscall number; xor with 0x0a changes 8 to 2 and
    ; viceversa (so, switch read <=> write)
    ; al is the read character (when we did read); xor the low
    ; bit to change 0 to 1 and reverse
    xor ax,0x0a01
    mov dl,al       ; put the read (and inverted character) in dl,
                    ; where syscall 2 looks for the character to print
    jmp lop         ; loop

Previous solution - 13 bytes

I think it doesn't get much shorter than this. Actually, it did! Thanks to @ninjalj for shaving off one more byte.

00000000  b4 08 cd 21 34 01 92 b4  02 cd 21 eb f3           |...!4.....!..|
0000000d

This version features advanced interactivity™ - after running it from the command line, it spits out the "inverted" characters as long as you write the input digits (which are not echoed); to exit, just do a Ctrl-C.

Unlike the previous solution, this has some trouble running in DosBox - since DosBox doesn't support Ctrl-C correctly, you are forced to close the DosBox window if you want to exit. In a VM with DOS 6.0, instead, it runs as intended.

NASM source:

org 100h

section .text

start:
    mov ah,8
    int 21h
    xor al,1
    xchg dx,ax
    mov ah,2
    int 21h
    jmp start

Old solution - 27 25 22 bytes

This accepted its input from the command line; runs smoothly as a .COM file in DosBox.

00000000  bb 01 00 b4 02 8a 97 81  00 80 f2 01 cd 21 43 3a  |.............!C:|
00000010  1e 80 00 7c f0 c3                                 |...|..|

NASM input:

    org 100h

section .text

start:
    mov bx, 1
    mov ah, 2
loop:
    mov dl, byte[bx+81h]
    xor dl, 1
    int 21h
    inc bx
    cmp bl, byte[80h]
    jl loop
exit:
    ret

Matteo Italia

Posted 2014-06-07T20:20:54.723

Reputation: 3 669

1xchg dx,ax is 1 byte shorter than mov dl,al – ninjalj – 2016-11-11T19:35:54.823

@ninjalj: woa, thank you! It did get shorter after all! – Matteo Italia – 2016-11-14T22:30:39.470

2+1 for code probably not many understand. – Knerd – 2014-06-10T15:41:51.547

26

Bash+coreutils, 8 bytes

tr 01 10

Takes input from STDIN.


Or

sed, 8 bytes

y/01/10/

Digital Trauma

Posted 2014-06-07T20:20:54.723

Reputation: 64 644

Thanks for this solution. I didn't know you could do that with tr--it's going to shave a lot from some of my scripts! I used to translate hex digits a-f to caps using six sed statements (it was ugly). – Joe – 2016-07-02T21:11:34.410

2

I recently made a golfing library/alias set for Bash https://github.com/professorfish/bash-shelf/. you can shave off one char with that: y 01 10

– None – 2014-06-08T06:56:03.583

1Where is BASH involved here? What is BASH specific? Every shell can call tr... – None – 2014-06-08T10:48:12.010

1@yeti Not every shell calls commands like bash or zsh. In some shells that code alone is a syntax error – mniip – 2014-06-08T11:20:59.787

5It's probably safe to assume that "shell" means "POSIX-compatible shell" here... – FireFly – 2014-06-08T11:56:06.867

@professorfish you shave off one char, but then add 48 by including the function. How is that a win? – Steven Penny – 2014-06-11T00:50:06.137

@StevenPenny when people use PYG, they don't count the library file towards their score; so in the same way SHELF is a golfing library which counts as a separate language – None – 2014-06-11T07:22:13.300

@professorfish hey use this library! y(){ sed 'y/01/10/'; } Then you can golf it to one char! – Steven Penny – 2014-06-11T12:12:59.607

@StevenPenny You just made that library up after the question was posted. SHELF existed before the question was posted. – None – 2014-06-11T12:42:46.220

@professorfish Does anyone except me actually use PYG? – ɐɔıʇǝɥʇuʎs – 2014-06-13T05:43:56.637

@Synthetica I don't know... – None – 2014-06-13T07:09:20.760

20

CJam, 4 bytes

:~:!

Assumes the original string is already on the stack. Prints the modified string.

Try it online by pasting the following Code:

"10101110101010010100010001010110101001010":~:!

How it works

  • :~ evaluates each character of the string, i.e., it replaces the character 0 with the integer 0.

  • :! computes the logical NOT of each integer. This turns 0's into 1's and 1's into 0's.

Dennis

Posted 2014-06-07T20:20:54.723

Reputation: 196 637

20

Brainfuck (70 71)

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

Explanation:

>,[>,]                       Read characters until there are none left.
<[<]                         Return to start
>[<                          Loop as long as there are characters to invert
  +++++++[>-------<-]        Subtract 49 (ASCII value of 1)
  >[++<]                     If not 0, add 2
  +++[<++++>-]<[>>++++<<-]>> Add 48
  .                          Print
  [-]                        Set current cell to 0
>]                           Loop

kitcar2000

Posted 2014-06-07T20:20:54.723

Reputation: 2 689

1++++++++[<++++++>-] why not this for 48? 86 vs. 44*3 – Cruncher – 2014-06-10T13:30:04.287

@Cruncher Added. – kitcar2000 – 2014-06-10T19:32:58.037

Why did it get longer? is that because of the "bug fixing"? – Cruncher – 2014-06-10T19:52:25.930

1@Cruncher Yes, I had to fix a bug where it would output a for 11. – kitcar2000 – 2014-06-10T20:15:26.313

16

PHP - 19 bytes

<?=strtr($s,[1,0]);

Yea, not really original, I guess!

Blackhole

Posted 2014-06-07T20:20:54.723

Reputation: 2 362

11

Pancake Stack, 532 bytes

Put this tasty pancake on top!
[]
Put this delicious pancake on top!
[#]
Put this  pancake on top!
How about a hotcake?
If the pancake is tasty, go over to "#".
Eat all of the pancakes!
Put this supercalifragilisticexpialidociouseventhoughtheso pancake on top!
Flip the pancakes on top!
Take from the top pancakes!
Flip the pancakes on top!
Take from the top pancakes!
Put this supercalifragilisticexpialidociouseventhoughthes pancake on top!
Put the top pancakes together!
Show me a pancake!
If the pancake is tasty, go over to "".

It assumes the input is terminated by a null character. The strategy is as follows:

  • Take a character of input
  • Subtract the ascii value of 1 from it.
  • Subtract that from 0 (yielding a 1 if we had 0, or a 0 if we had 1)
  • Add the ascii value of 0 to it
  • Print the char.
  • Repeat

Justin

Posted 2014-06-07T20:20:54.723

Reputation: 19 757

10

C: 29

i(char*s){*s^=*s?i(s+1),1:0;}

Try it online here.

Thanks for pointing out the XOR trick, Dennis.

millinon

Posted 2014-06-07T20:20:54.723

Reputation: 590

1i(char*s){*s^=*s&&~i(s+1);} length 27, assuming i never return -1(i is usually the result *s) – l4m2 – 2017-12-15T18:38:26.843

8Simpler & shorter: i(char*s){while(*s)*s++^=1;} – edc65 – 2014-06-08T09:45:19.720

1Thanks, @edc65! I'm not going to use that, though, since it's an iterative solution rather than a recursive one. I wouldn't want to take credit for it. It's worth noting that replacing your while with a for still results of a length of 28 characters. – millinon – 2014-06-09T13:47:55.383

6As you prefer. A recursive solution is not requested, and in my opinion, any time it is possibile, an iterative solution is better than a recursive one. Have fun applying this recursive call to a 10k string. – edc65 – 2014-06-09T14:24:47.313

1Since every call except for the last one is a tail recursive call, I'll bet that a compiler will convert it into a loop in order to re-use the stack frame. – millinon – 2014-06-09T15:28:11.573

1@millinon Proof! – deed02392 – 2014-06-10T13:50:26.397

1Okay, you win. GCC 4.8.3 in Cygwin failed to optimize the tail recursion. – millinon – 2014-06-10T20:25:31.123

9

Python 2.7 – 34*

Oh how much this first one sucks. Pretty ugly, this one is. 63 chars.

print''.join([bin(~0)[3:] if x == '0' else bin(~1)[4:] for x in ''])

This one is a bit better but still not that fancy. 44 chars.

print''.join([str(int(not(int(x)))) for x in ''])

Since int(x) and 1 returns int(x) if it's not 0 and otherwise False. The solution can be further reduced to 36 chars.

print''.join([str(1-int(x)) for x in ''])

Since join() takes a generator the brackets can be removed. 32 chars.

print''.join(str(1-int(x))for x in'')

And backticks can be used instead of str()

print''.join(`1-int(x)`for x in'')

Reduced to 44 from 34 thanks to pointers from @TheRare

Finding one's complement is difficult in python since bin(-int) returns -0bxxx hence the above.

Bassem

Posted 2014-06-07T20:20:54.723

Reputation: 201

A print statement is required, since a REPL cannot be assumed. – mbomb007 – 2015-08-30T20:37:29.537

@mbomb007 correct, added. – Bassem – 2015-08-30T21:25:08.567

2Ya'know, (int(x) and 1) == int(x) – seequ – 2014-06-08T10:47:10.040

@TheRare I didn't, thanks for that :) – Bassem – 2014-06-08T11:33:53.003

As a truth value that is. int(x) and 1 returns int(x) if it's not zero and otherwise False. – seequ – 2014-06-08T11:37:10.177

Because of that you can change int(not(int(x))) -> 1-int(x) – seequ – 2014-06-08T11:38:10.177

Also, you can pass a generator to join (no need for the square brackets) and you don't need spaces around string literals and brackets. – seequ – 2014-06-08T11:40:10.320

@TheRare Awesome! I'm gonna document all the steps above in the answer, as reference, cheers! – Bassem – 2014-06-08T11:42:05.653

Python is my baby, always happy to help. :) – seequ – 2014-06-08T11:43:14.440

1For the record: zero is false and nonzero is true. For any kind of sequence (list, string...) the same rule applies, but it's checked from the length of the sequence. Thus '' == False and 'hi' == True – seequ – 2014-06-08T11:45:09.330

Also, even though it can't be used in this answer, numbers can precede keywords without spaces. print 4if 1else 2 prints 4. – seequ – 2014-06-08T11:48:30.897

1Seems like you missed some spaces. Also, backticks can be used to replace repr(). ''.join(\1-int(x)`for x in'')` – seequ – 2014-06-08T11:53:10.257

1Fyi, repr(x) for x < maxint is equal to str(x) – seequ – 2014-06-08T12:03:07.587

That's all I've got regarding this question. You can find more tricks from my other answers (and do check Tips for golfing in Python). :) – seequ – 2014-06-08T12:09:09.047

7

Perl, 9 characters

'y/10/01/'

The 9th character is the 'p' flag

Usage:

$ echo '10101001' | perl -pe 'y/10/01/'

Zaid

Posted 2014-06-07T20:20:54.723

Reputation: 1 015

2also works as a sed script y/10/01/ but one char shorter because it doesn't need any flags – None – 2014-06-08T06:52:55.730

4You don't need single quotes here. – Konrad Borowski – 2014-06-08T07:12:23.187

7

Javascript (ES6) 36

alert(prompt().replace(/./g,x=>x^1))

nderscore

Posted 2014-06-07T20:20:54.723

Reputation: 4 912

Assuming input in s, s.replace(/./g,x=>x^1) are 22 chars. – Oriol – 2014-06-08T18:37:55.113

2I like to actually output and input. – nderscore – 2014-06-08T19:38:56.693

@nderscore Save 2 chars: p=prompt(p().replace(/./g,x=>x^1)) – Gaurang Tandon – 2014-06-09T05:21:20.083

@GaurangTandon it would have to be (p=prompt)(p().replace(/./g,x=>x^1)) and that's the same length. – nderscore – 2014-06-09T13:19:08.347

@nderscore I too thought it to be that way, but it worked without the parenthesis too, strangely. – Gaurang Tandon – 2014-06-09T13:39:41.103

@GaurangTandon p will be undefined until after prompt is called. Afterwards, it will contain a string. It's definitely not valid. You must have had prompt stored in p before running the code. – nderscore – 2014-06-09T13:44:12.610

@nderscore I think you are right. I was trying it in FF console so might be that p was already defined. – Gaurang Tandon – 2014-06-09T13:47:37.060

7

Labyrinth, 6 bytes

(Labyrinth is newer than this challenge, so this answer doesn't compete - not that it's winning anyway...)

1,
.$@

This code assumes that STDIN contains only the digits (in particular, no trailing newline).

The instruction pointer (IP) starts in the top left corner going right. While there are digits to read it will cycle in a tight loop through the left-hand 2x2 block: 1 push a 1, , read a digit, $ XOR it with 1 to toggle the last bit, . print the result. The IP takes this loop because the top of the stack is positive after the XOR, such that it will take a right-turn. When we hit EOF, , returns -1 instead. Then the XOR will yield -2 and with this negative value the IP takes a left-turn onto the @ and the program ends.

This solution should be optimal for Labyrinth: you need , and . for an I/O loop and @ to terminate the program. You need at least two characters (here 1 and $) to toggle the last bit. And you need at least one newline for a loop which can be terminated.

Unless... if we ignore STDERR, i.e. allow terminating with an error we can save the @ and we also don't need any way to switch between two paths. We just keep reading and printing until we accidentally try to print a negative value (the -2). This allows for at least two 5-byte solutions:

1,
.$
,_1$.

Martin Ender

Posted 2014-06-07T20:20:54.723

Reputation: 184 808

5

Ruby: 23

p $<.read.tr("01","10")

Josh

Posted 2014-06-07T20:20:54.723

Reputation: 49

5

Turing Machine Code, 32 bytes (1 state - 3 colors)

Using the rule table syntax required by this online TM simulator. Borrowed from a post I made to my Googology Wiki user blog a few months back.

0 0 1 r *
0 1 0 r *
0 _ _ * halt

You may also test this using this java implementation.

SuperJedi224

Posted 2014-06-07T20:20:54.723

Reputation: 11 342

4

Python 2.x - 44 bytes

print''.join(`1-int(x)`for x in raw_input())

Why make it complex, or use some cheaty variables?

seequ

Posted 2014-06-07T20:20:54.723

Reputation: 1 714

Its possible to save some extra chars like this: print''.join('1-int(x)'for x in'input()'). I couldn't get the backticks in the comment code so substituted them by '. – Willem – 2014-06-09T09:10:11.627

@willem For future reference, you can escape them with a backslash: \a\`b`` -> a\b`. – nyuszika7h – 2014-06-09T11:03:09.660

@willem That doesn't work for input beginning with 0 or input which is bigger than maxint (in base10). – seequ – 2014-06-09T14:01:17.283

Thanks @nyuszika7h and didn't think about those cases TheRare so your solution is good – Willem – 2014-06-09T14:18:01.873

@willem Real easy to forget about stuff like that. :) – seequ – 2014-06-09T14:26:42.997

4

R, 27 characters

chartr("01","10",scan(,""))

Usage:

> chartr("01","10",scan(,""))
1: 10101110101010010100010001010110101001010
2: 
Read 1 item
[1] "01010001010101101011101110101001010110101"

plannapus

Posted 2014-06-07T20:20:54.723

Reputation: 8 610

4

APL (Dyalog Unicode), 7 bytesSBCS

Full program. Prompts stdin.

∊⍕¨~⍎¨⍞

Try it online!

 prompt stdin

⍎¨ execute each character

~ logical NOT

⍕¨ format each character as text

ϵnlist (flatten)

Adám

Posted 2014-06-07T20:20:54.723

Reputation: 37 779

3

Befunge-98 (PyFunge), 7 bytes

'a#@~-,

For every character, c, in the input, it prints the character with an ascii value of 94 - c, where 94 is the value of ‘0’ +’1’, or ‘a’

Try it online!

MildlyMilquetoast

Posted 2014-06-07T20:20:54.723

Reputation: 2 907

3

PHP > 5.4 -- 37 characters

foreach(str_split($s) as $v)echo 1^$v

$s is the input

Try it online

Alireza Fallah

Posted 2014-06-07T20:20:54.723

Reputation: 151

5Clever abuse of the <kbd> tag. – nyuszika7h – 2014-06-09T11:04:53.837

3

TI-BASIC, 7 bytes

This is a function that takes a binary string (through Ans) as input and returns the output as an inverted (not reversed) string, as specified. For more help, you can read through list application by not( on the TI-BASIC wiki. I'm using the compiled version because it is smaller:

»*r>Õ¸r

In hex:

BB 2A 72 3E D5 B8 72

Explanation

»*r - Take function input as string and convert to list

> - Pipe given list to the next operators

Õ¸r - Return the inverse of the list

Timtech

Posted 2014-06-07T20:20:54.723

Reputation: 12 038

It should be useful to note that:

  1. On the calculator this is displayed as expr(Ans:Returnnot(Ans;
  2. Because the string is not separated by commas, and it does not start with a {, it will evalutate to an integer like 1000010011, not a list;
  3. Return does not work the way you wrote it;
  4. This gives output as a list, not a string.
  5. < – lirtosiast – 2015-05-26T23:41:15.040

what are all of the spaces at the end of »*r>Õ¸r? – kitcar2000 – 2014-07-03T18:28:37.040

@kitcar2000 Oops, I used to have the HEX after that. But after I moved it, I forgot to remove the spaces... I have done it now. – Timtech – 2014-07-04T14:05:51.847

3

Haskell, 22 bytes

map(\c->"10"!!read[c])

I was surprised by the lack of Haskell solutions to this challenge, so here's one. It evaluates to a function that takes a string and returns its inverse.

Explanation

Nothing fancy here.

map(\c->             )  -- For each character c in the input string:
                  [c]   -- wrap c into a string,
              read      -- convert to integer,
        "10"!!          -- and index the string "10" with it.

Zgarb

Posted 2014-06-07T20:20:54.723

Reputation: 39 083

3

Befunge 93, 25 bytes

0>~1+:#v_$>:#,_@
 ^   -1<

Assuming empty stack and EOF both read -1.

0 pushes a \0 as a null terminator

>~1+:#v_ is an input loop, it reads ascii, adds 1, checks for EOF+1=0,

^ -1< else subtracts 1 and leaves the pushed ascii value on the stack.

$>:#,_@ drops the extra copy of zero on top of the stack, then prints the binary string top to bottom

If empty stack reads 0, save 2 bytes with

>~:1+#v_$>:#,_@
^   -1<

A version around 15 bytes is possible using this same algorithm if EOF = 0, but I don't have such an implementation handy to test with.

sig_seg_v

Posted 2014-06-07T20:20:54.723

Reputation: 147

3

Javascript ES6, 26 chars

s=>s.replace(/\d/g,x=>x^1)

Qwertiy

Posted 2014-06-07T20:20:54.723

Reputation: 2 697

3Why /\d/g not /./g – l4m2 – 2017-12-15T18:40:35.957

2

Jelly, 4 bytes

^1Ṿ€

Try it online!

Explanation:

First of all, if you're familiar with Jelly, you might've noticed that I'm trying to bitwise-xor with a string. That sounds all sorts of ridiculous at first, but Jelly actually supports vectorized bitwise-xor'ing with strings, where each char, if it's a digit from 1 to 9, it's treated as such, otherwise it's treated as 0. The only chars in the string will in this case be '0' and '1', being treated as themselves, as previously specified. So, bitwise-xor'ing then with 1 will return 0 ^ 1 = 1 for every '0' and 1 ^ 1 = 0 for every '1' in the string. Right now, our output is a list of 0s and 1s, so it's not yet in the correct format. We right now have to find a way to concatenate the integers into a single string, and we don't have a builtin for that. Fortunately, strings in Jelly are lists of 1-char Python strings, so we can simply take the string representation of each of the integers in the list. But wait! That builtin costs us 2 bytes, so let's see if there's a shorter builtin...and there is! Behold the uneval builtin! Unevaling an integer just takes its Jelly string representation, which, for integers, is equivalent to Python's string representation. So why not use it? That's what we'll do, to actually finish our program.

^1Ṿ€ Main link, monadic
^1   XOR each char with 1, as specified above
  Ṿ€ Uneval each resulting integer

Erik the Outgolfer

Posted 2014-06-07T20:20:54.723

Reputation: 38 134

2

Japt -m, 2 bytes

^1

Try it here

Shaggy

Posted 2014-06-07T20:20:54.723

Reputation: 24 623

2

Vim, 19 keystrokes

:s/./-&/g␤qq␁l@qq@q

is Return and is CtrlA

Explanation

:s/./-&/g␤   Negate every digit (01100 -> -0-1-1-0-0)
qq␁l@qq@q   Increment every number (-0-1-1-0-0 -> 10011)

Herman L

Posted 2014-06-07T20:20:54.723

Reputation: 3 611

You could also increment every digit, 01100 ==> 12211, then swap all 2s for 0s ==> 10011. Save 1 byte doing :s/2/0/g instead of negation – roblogic – 2019-09-08T14:02:19.807

1@roblogic As far as i know there isn't a way to increment single digits in vim. I would have to insert separators in between each character which would waste more bytes than it saves – Herman L – 2019-09-08T19:41:49.540

2

Forth (gforth), 38 36 bytes

: f 0 do dup c@ 1 xor emit 1+ loop ;

Try it online!

-2 bytes thanks to @bubbler

Explanation

Gets the string character by character. For each character:

  1. checks if it's equal to 49 and then adds -1 to the result (forth uses -1 as true).
  2. Prints the space right-aligned in a space of size 1 (removes space after number that . normally outputs)

Code Explanation

: f                \ start a new word definition
  0 do             \ start counted loop from 1 to string-length
    dup c@         \ duplicate the string address and get the ascii value of the char at the beginning
    49 = 1+        \ check if equal to 49 and add 1 to the result (forth uses -1 as true)
    1 .r           \ output right-aligned in a space of size (removes trailing space)
    1+             \ increment the string address
  loop             \ end the loop
;                  \ end the word definition

reffu

Posted 2014-06-07T20:20:54.723

Reputation: 1 361

Using 1 xor emit (charcode output instead of number output) gives 36 bytes.

– Bubbler – 2019-10-12T08:31:38.180

2

brainfuck, 26 bytes

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

This flips the last bit of each byte of input. (Assumes EOF -> 0, assumes nothing about cell size, doesn't go out of bounds to the left.)

Daniel Cristofani

Posted 2014-06-07T20:20:54.723

Reputation: 947

2

Python3, 39

Methinks Python is not the best language for this. :)

for i in input():print(1-int(i),end='')

If you care about having a newline after the output, here's a 43-character alternative:

print(''.join("01"[i<"1"]for i in input()))

DLosc

Posted 2014-06-07T20:20:54.723

Reputation: 21 213

Code will work without the end='' just a , will do :) - unless you care about there being no spaces – Harry Beadle – 2014-06-08T01:29:19.083

@BritishColour, no, that's Python2. Python3's print function requires tweaking the end parameter to suppress a newline at the end of each print. Also, according to OP's specification, I think I do care about there being no spaces. :) Thanks for the comment, though! – DLosc – 2014-06-08T01:46:23.750

Aww, cool, I did't know that! I mainly work in 2.7 :/ – Harry Beadle – 2014-06-08T01:47:29.760

2

J - 11 chars

Boolean values in J are represented as the integers 0 and 1, which of course are also valid indices into arrays (in this case, the 2-character array '01')

'01'{~'0'&=

Dan Bron

Posted 2014-06-07T20:20:54.723

Reputation: 421

I think this answer is technically more correct than the top J answer, which outputs a boolean array instead of a string. – gar – 2014-06-10T11:49:28.860

I actually didn't notice the top-ranked J solution when I posted (don't know how I missed it, but I did). To be fair to that solution, it does explicitly say "this doesn't do what the other solutions do". BTW, another way to express this (literal output) solution in 11 chars is [:,":@=&''0'' . – Dan Bron – 2014-06-10T14:05:39.483

Hi, thanks for another code! I will be learning more J from you guys. About that statement, I think he was referring to the equal sign, that it compares each item instead of assignment. – gar – 2014-06-10T16:23:44.483

2

C#, 131 bytes

A little late to the party, but here's mine. :)

using System;class R{static void Main(string[]a){foreach(var v in a[0].ToCharArray()){Console.Write(int.Parse(v.ToString())^1);}}}

helencrump

Posted 2014-06-07T20:20:54.723

Reputation: 161

2

MATLAB, 13 bytes

@(x)[97-x '']

After running the above, simply call the function with your input string to get the inverted string. For example running:

ans('10101110101010010100010001010110101001010')

prints:

01010001010101101011101110101001010110101

Tom Carpenter

Posted 2014-06-07T20:20:54.723

Reputation: 3 990

2

BotEngine, 4x8=32

Noncompeting as the language postdates the question.

Iv2 0 12
 >e>S SS
    e1e0
   ^< <P

With highlighting:

enter image description here

SuperJedi224

Posted 2014-06-07T20:20:54.723

Reputation: 11 342

2

brainfuck, 24 bytes or 19 bytes

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

Try it online!

or

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

(this one requires an interpreter which will noop on < if the data-index is 0)

Both programs use 8-bit wrapping cells. The main part of the programs are the >++[->++[<]>-]>- and +[<[-->>]<--]< which do some rather convoluted things to flip the last bit of the number.

I'm happy I managed to beat some more 'real' languages like C and Python, not something that happens every day with bf ;)

KSab

Posted 2014-06-07T20:20:54.723

Reputation: 5 984

If you added an initial > to that first one, so it wouldn't go out of bounds, that'd be a very nice solution. One byte shorter than mine, congrats! Works with EOF->0 or EOF->no change, and doesn't assume anything about cell size, with the specified inputs. Good stuff. – Daniel Cristofani – 2020-01-20T07:24:23.833

@DanielCristofani Yeah I thought it was cool that we had two such different looking solutions of such similar size. The reason I didn't add a > at the beginning was just because I usually just use tio as my target implementation and it works there. – KSab – 2020-01-20T14:40:23.310

1

SmileBASIC 3, 40 bytes

Down 10 bytes thanks to suggestions from 12Me21.

While I like 12Me21's answer, it doesn't actually answer the question.

INPUT S$WHILE""<S$?!VAL(SHIFT(S$));
WEND

This doesn't print a linebreak afterwards though, so if you did this on the console you might get something like 001010101OK. Oh well, nothing about it in the question.

INPUT S$             'get string
WHILE ""<S$          'while input string isn't empty:
  ? !VAL(SHIFT(S$)); '-SHIFT a character off our string
                     '-find the opposite value with VAL and !
                     '-print that value, omitting newline
WEND                 'while end

snail_

Posted 2014-06-07T20:20:54.723

Reputation: 1 982

There's a way to do this without using VAL( – 12Me21 – 2017-02-07T19:50:24.067

You could use an infinite loop and let the program end with an error: INPUT S$@L?!VAL(SHIFT(S$));:GOTO@L for 34 bytes – 12Me21 – 2017-10-17T19:15:57.090

1

Noether, 18 bytes

100th Answer! :D

I~sL(1si/W-Pi1+~i)

Try it here!

Loops through each character in the string, inverting each character.

Explanation:

I  - Push input to stack
~s - Store the top of the stack in the variable s
L  - Pop string off the top and push its length
(  - Pop off the stack and repeat code between brackets until stack equals popped value
1  - Push the number 1
s  - Push the value of variable s
i  - Push the value of variable i (all variables are initialised to zero)
/  - Pop a string and number, n, off stack and push the character at index n
W  - Convert string to number
-  - Pop two numbers off stack and push the numbers subtracted
P  - Print top of stack
i  - Push value of variable i
1  - Push number 1
+  - Pop top two numbers and push the addition
~i - Pop top off stack and store in variable i
)  - End loop

Beta Decay

Posted 2014-06-07T20:20:54.723

Reputation: 21 478

1

Cubix, 12 bytes

i?./^\'1c$@O

Try it online!

cube form:

    i ?
    . /
^ \ ' 1 c $ @ O
. . . . . . . .
    . .
    . .

Giuseppe

Posted 2014-06-07T20:20:54.723

Reputation: 21 077

1

Sinclair ZX81, Timex TS1000/1500, ~60 tokenized BASIC bytes

 1 INPUT A$
 2 PRINT A$
 3 FOR I=1 TO LEN A$
 4 PRINT NOT VAL A$(I);
 5 NEXT I

This technique iterates over each byte of the string, taking it's numeric value and printing the NOT equivalent. In ZX81 terms, NOT 1 is 0 and NOT 0 is 1. RUN the program and enter your binary string, followed by NEW LINE (or the Enter key).

Simple test case shown below.

ZX81 flip the bits

Shaun Bebbers

Posted 2014-06-07T20:20:54.723

Reputation: 1 814

1

Pure Bash shell solution. 87 bytes.

while((n<=${#1}));do
case "${1:$n:1}" in
0)printf 1;;1)printf 0;;
esac;n=$((n+1));done

Yokai

Posted 2014-06-07T20:20:54.723

Reputation: 111

1Welcome to PPCG! Nice first solution! – Grant Miller – 2018-02-24T11:14:20.277

1

Perl 6, 11 bytes

{TR/10/01/}

Try it online!

Simple transliterate that turns all 1s to 0s and vice-versa.

Jo King

Posted 2014-06-07T20:20:54.723

Reputation: 38 234

1

05AB1E, 3 bytes

€_J

Try it online.

Explanation:

€      # Map over the digits of the (implicit) input
 _     #  Negative boolean: 0 becomes 1, everything else (so the 1s) becomes 0
  J    # After the map, join everything together (and output implicitly)

Kevin Cruijssen

Posted 2014-06-07T20:20:54.723

Reputation: 67 575

1

Whitespace, 79 bytes

[N
S S N
_Create_Label_LOOP][S S S T T   S S S T N
_Push_49][S N
S _Duplicate_49][S N
S _Duplicate_49][T  N
T   S _Read_STDIN_as_character][T   T   T   _Retrieve][T    S S T   _Subtract][S N
S _Duplicate][N
T   S S N
_If_0_Jump_to_Label_1][S S S T  N
_Push_1][T  S S T   _Subtract][N
T   S T N
_If_0_Jump_to_Label_0][N
N
N
_Exit][N
S S T   N
_Create_Label_0][S S S T    N
_Push_1][N
S S S N
_Create_Label_1][T  N
S T _Print_integer_to_STDOUT][N
S N
N
_Jump_to_Label_LOOP]

Letters S (space), T (tab), and N (new-line) added as highlighting only.
[..._some_action] added as explanation only.

Since Whitespace can only take input as integer or character, we must add a trailing character (other than 0 or 1; like a newline, space, a letter, etc.) to indicate we're done with the input-string after reading it character by character.

Try it online (with raw spaces, tabs and new-lines only).

Example run: input = 100

Command       Explanation                     Stack        Heap      STDIN   STDOUT

NSSN          Create Label_LOOP               []
 SSSTTSSSTN   Push 49                         [49]
 SNS          Duplicate 49                    [49,49]
 SNS          Duplicate 49                    [49,49,49]
 TNTS         Read STDIN as character         [49,49]      {49:49}   1
 TTT          Retrieve                        [49,49]      {49:49}
 TSST         Subtract (49-49)                [0]          {49:49}
 SNS          Duplicate 0                     [0,0]        {49:49}
 NTSSN        If 0: Jump to Label_1           [0]          {49:49}
 NSSSN        Create Label_1                  [0]          {49:49}
  TNST        Print to STDOUT as integer      []           {49:49}           0
  NSNN        Jump to Label_LOOP              []           {49:49}

 SSSTTSSSTN   Push 49                         [49]
 SNS          Duplicate 49                    [49,49]
 SNS          Duplicate 49                    [49,49,49]
 TNTS         Read STDIN as character         [49,49]      {49:48}   0
 TTT          Retrieve                        [49,48]      {49:48}
 TSST         Subtract (49-49)                [1]          {49:48}
 SNS          Duplicate 0                     [1,1]        {49:48}
 NTSSN        If 0: Jump to Label_1           [1]          {49:48}
 SSSTN        Push 1                          [1,1]        {49:48}
 TSST         Subtract (1-1)                  [0]          {49:48}
 NTSTN        If 0: Jump to Label_0           []           {49:48}

 NSSTN        Create Label_0                  []           {49:48}
  SSSTN       Push 1                          [1]          {49:48}
  NSSSN       Create Label_1                  [1]          {49:48}
  TNST        Print to STDOUT as integer      []           {49:48}           1
  NSNN        Jump to Label_LOOP              []           {49:48}

 SSSTTSSSTN   Push 49                         [49]
 SNS          Duplicate 49                    [49,49]
 SNS          Duplicate 49                    [49,49,49]
 TNTS         Read STDIN as character         [49,49]      {49:48}   0
 TTT          Retrieve                        [49,48]      {49:48}
 TSST         Subtract (49-49)                [1]          {49:48}
 SNS          Duplicate 0                     [1,1]        {49:48}
 NTSSN        If 0: Jump to Label_1           [1]          {49:48}
 SSSTN        Push 1                          [1,1]        {49:48}
 TSST         Subtract (1-1)                  [0]          {49:48}
 NTSTN        If 0: Jump to Label_0           []           {49:48}

 NSSTN        Create Label_0                  []           {49:48}
  SSSTN       Push 1                          [1]          {49:48}
  NSSSN       Create Label_1                  [1]          {49:48}
  TNST        Print to STDOUT as integer      []           {49:48}           1
  NSNN        Jump to Label_LOOP              []           {49:48}

 SSSTTSSSTN   Push 49                         [49]
 SNS          Duplicate 49                    [49,49]
 SNS          Duplicate 49                    [49,49,49]
 TNTS         Read STDIN as character         [49,49]      {49:10}   \n
 TTT          Retrieve                        [49,10]      {49:10}
 TSST         Subtract (49-10)                [39]         {49:10}
 SNS          Duplicate 39                    [39,39]      {49:10}
 NTSSN        If 0: Jump to Label_1           [39]         {49:10}
 SSSTN        Push 1                          [39,1]       {49:10}
 TSST         Subtract (39-1)                 [38]         {49:10}
 NTSTN        If 0: Jump to Label_0           []           {49:10}
 NNN          Exit program                    []           {49:10}

Kevin Cruijssen

Posted 2014-06-07T20:20:54.723

Reputation: 67 575

1

C, 34 bytes

Fully portable (not just one or two character encodings).

f(char*s){for(;*s;)*s++^='0'^'1';}

Output is in-place modification of the string.

A less portable version would use a simple number in place of the expression '0'^'1' - e.g. 1 for ASCII or EBCDIC - saving up to 6 bytes.

Demo

#include<stdio.h>
int main(void)
{
    char s[] = "10101110101010010100010001010110101001010";
    f(s);
    printf("%s\n", s);
}

Toby Speight

Posted 2014-06-07T20:20:54.723

Reputation: 5 058

Did you at all read the answer? I did say that you could use 1 for ASCII or EBCDIC systems, but that's not fully portable. – Toby Speight – 2019-01-10T17:04:12.773

1

Reticular, 15 bytes

iSBql[n1~-o]~*;

Try it online!

Explanation

i               # Read input as string.
 S              # Push array of characters in the string.
  B             # Push every character in the array to the stack.
   q            # Reverse the stack.
    l           # Push the size of the stack.
     [     ]    # Push a function that does the following:
      n         # Convert top of stack to int.
       1~-      # Push 1, swap the top two items in the stack and subtract them.
                  This takes a character x in the input string to 1-x, resulting in the bit negation.
          o     # Output the top item of the stack     
            ~   # Swap the top two items in the stack.
             *  # Call the above function the same number of times as length of the input string.
                  (That is, for each bit in the input string, negate the bit and output it.)
              ; # Exit 

Wisław

Posted 2014-06-07T20:20:54.723

Reputation: 554

1

Zsh, 32 30 29 bytes

Shell builtins only: specifically, the XOR operator ^.

29 bytes: <<<$[1&#1^1]${1:+`$0 ${1:1}`}     recursion, by @GammaFunction
30 bytes: for X (${(s::)1})printf $[1^X]   more efficient for, by @GammaFunction
32 bytes: for X in ${(s::)1};printf $[1^X]


Bash, 35 bytes

35 bytes: echo $[1^${1:0:1}]${1:+`$0 ${1:1}`}   recursion, by @GammaFunction
44 bytes: for((;i<${#1};i++));{ printf $[1^${1:i:1}];}

roblogic

Posted 2014-06-07T20:20:54.723

Reputation: 554

135 for Bash using ${:+recursion}. – GammaFunction – 2019-09-08T10:06:02.167

1for X (...) form for 30 in Zsh – GammaFunction – 2019-09-08T10:08:33.000

129 in Zsh using recursion. Note, too many fork calls get denied on TIO. – GammaFunction – 2019-09-08T10:17:52.523

Thanks for the brilliant & creative feedback! – roblogic – 2019-09-08T10:53:57.497

1

naz, 62 bytes

2a2x1v4a8m2x0v1x0f1a1o1f0x1x1f1r3x1v2e3x0v0e1s1o1f0x1x2f0a0x1f

Works for any input file of 1's and 0's terminated with the control character STX (U+0002).

Explanation (with 0x commands removed)

2a2x1v                   # Set variable 1 equal to 2
4a8m2x0v                 # Set variable 0 equal to 48
1x0f1a1o1f               # Function 0
                         # Add 1 to the register, output, then jump to function 1
1x1f1r3x1v2e3x0v0e1s1o1f # Function 1
                         # Read a byte of input
                         # Jump to function 2 if it equals variable 1
                         # Jump to function 0 if it equals variable 0
                         # Otherwise, subtract 1 from the register, output,
                         # then jump back to the start of function 1
1x2f0a                   # Function 2
                         # Add 0 to the register
1f                       # Call function 1

sporeball

Posted 2014-06-07T20:20:54.723

Reputation: 461

1

Cobra - 89

class P
    def main
        r=''
        for i in Console.readLine,r+=if(i==c'1','0','1')
        print r

Οurous

Posted 2014-06-07T20:20:54.723

Reputation: 7 916

1

C# in LINQPad, 64 63

foreach(var c in Console.ReadLine())Console.Write((char)(c^1));

EDIT: removed one character by using XOR 1

Jacob

Posted 2014-06-07T20:20:54.723

Reputation: 1 582

1

Tcl - 23 bytes

string map {0 1 1 0} $s

Not quite the shortest but highly readable.

slebetman

Posted 2014-06-07T20:20:54.723

Reputation: 629

1

ECMAScript (28 bytes)

for(i of prompt(r=''))r+=1-i

Just subtraction.

Alternative 1 (28 bytes)

for(i of prompt(r=''))r+=i^1

A simple bitwise not.

Alternative 2 (29 bytes)

for(i of prompt(r=''))r+=2+~i

~'1' is -2 and ~'0' is -1, so 2+~i gives 0 for 1 and 1 for 0.

Alternative 3 (29 bytes)

for(i of prompt(r=''))r+=+!+i

The last + changes i to a number, ! converts it to a boolean (0 is false and anything else is true) and inverts it, and the first + converts it to a number (false becomes 0 and true becomes 1).

Toothbrush

Posted 2014-06-07T20:20:54.723

Reputation: 3 197

1

Linux amd64 assembly version, 370 bytes, generates small ELF executable (392 bytes after strip --strip-all).

global _start

_start:
        mov rsi, [rsp+16] ; argv[1]
        xor rdx, rdx
loop:
        mov bl, [rsi+rdx]
        test bl, bl
        jz print
        xor bl, 1
        mov [rsi+rdx], bl
        inc rdx
        jmp loop
print:  
        mov rdi, 1 ; stdout
        mov rax, 1 ; write
        syscall
        mov rax, 60 ; exit
        xor rdi, rdi
        syscall

hdante

Posted 2014-06-07T20:20:54.723

Reputation: 181

1

Java - 120 103 94

This is for hdante :)

class I{public static void main(String[]a){for(int
x:a[0].getBytes())System.out.print(49-x);}}

It takes the string as a command-line argument.

aditsu quit because SE is EVIL

Posted 2014-06-07T20:20:54.723

Reputation: 22 326

@aditsu one needs to get 10 points (= at least one answer or 2 question upvotes) on this site – the 100 rep from the association bonus doesn't count. – Paŭlo Ebermann – 2015-11-01T02:55:48.897

a streaming Java 8 solution (takes lines of 0 and 1): class D{public static void main(String[] b){new java.io.BufferedReader(new java.io.InputStreamReader(System.in)).lines().forEach((String i)->System.out.print(i.equals("0")?'1':'0'));}} – Janus Troelsen – 2014-06-11T10:45:55.443

a solution that takes the word "random" in the question literally and makes it's own input: class C{public static void main(String[] b){new java.util.Random().ints(0,2).forEach((int i)->System.out.print(i==0?'1':'0'));}} – Janus Troelsen – 2014-06-11T10:46:42.460

reads ACSII from stdin (143 bytes): class B{public static void main(String[] b)throws java.io.IOException{int c;while((c=System.in.read())!=-1)System.out.print(c=='0'?'1':'0');}} – Janus Troelsen – 2014-06-11T10:47:35.103

reads everything from stdin with the Scanner trick (165 bytes): class A{public static void main(String[] b){for(char a:new java.util.Scanner(System.in).useDelimiter("\\A").next().toCharArray())System.out.print(a=='0'?'1':'0');}} – Janus Troelsen – 2014-06-11T10:48:59.480

2@JanusTroelsen Um, thanks, but why don't you post a separate answer? Also, your solutions are longer. – aditsu quit because SE is EVIL – 2014-06-11T11:08:31.893

The question has been protected. I also think it makes sense to group answers by language. You are correct, they are longer, when expressed in this syntax. – Janus Troelsen – 2014-06-11T11:18:45.523

@JanusTroelsen Protected means you need to have at least 10 reputation to answer, and you have 101. I don't think grouping answers as comments really makes sense. – aditsu quit because SE is EVIL – 2014-06-11T12:14:23.577

Thanks, to tell the truth, it's not as verbose as I expected it to be. – hdante – 2014-06-12T18:36:51.430

1

><> (6 bytes)

Assuming you don't mind the code exiting with an error, the following works:

{2%0=n

Example run:

$ python3 fish.py binary.fish -s "100010101101111001"
011101010010000110
something smells fishy...

This errors when it runs out of values left on the stack. If it has to actually end correctly, 11 bytes works;

{2%0=nl0=?;

Example:

$ python3 fish.py binary.fish -s "10111111101101001"
01000000010010110

Essentially, each piece of code is doing the same thing: { shifts the entire stack to the left, moving the first value entered in the command call to the top of the stack; 2% takes the modulus of the top value with 2 (so "1" -> 49 (ASCII code) -> 1 and "0" -> 48 -> 0); 0= pushes 0 to the stack and pops the top two values off, pushing 1 to the stack if they are equal and 0 otherwise; and n prints the numerical value of the value on top of the stack.
The additional bit in the second piece just checks if there are any values left on the stack and ends if there aren't.

TalkTakesTime

Posted 2014-06-07T20:20:54.723

Reputation: 51

I don't believe this warrants an additional answer since it's so similar, but here's an alternate program to your error-less one: i:0(?;2%0=n. This one doesn't need a flag to populate the stack, so I guess it's technically 3 bytes shorter (or 2 depending on how you want to treat spaces). – cole – 2015-09-26T00:56:02.450

1

PowerShell, 33 29 Bytes

$args-split0-replace1,0-join1

Similar, but distinct, from DarkAjax's answer.

Uses inline operators to split on 0's (which results in a collection of strings of 1's), replace those 1's with 0's, and then join the collection back together with 1's (i.e., replacing the 0's that were removed when we split with 1's).

AdmBorkBork

Posted 2014-06-07T20:20:54.723

Reputation: 41 581

1

Python 3, 60 bytes

Not the shortest solution but i wanted to see if it could be achieved without a loop.

Exclusive or on a binary of ones same length as the input string (equivalent of 2**n - 1 where n is length of input). Padding with zfill was not ideal...

a=input()
print(bin(int(a,2)^2**len(a)-1)[2:].zfill(len(a)))

Todd

Posted 2014-06-07T20:20:54.723

Reputation: 121

1

Chicken Scheme - 85

Me thinks this problem needs more parenthesis!

(display(list->string(map(lambda(s)(if(eqv? s#\0)#\1 \0))(string->list(read-line)))))

Switching display for write saves 2 more characters, at the cost of quotes around the answer.

Fun fact:

A little over 20% of those 85 characters above are parentheses. Achievement unlocked.

Dan the Man

Posted 2014-06-07T20:20:54.723

Reputation: 141

1

><>, 13 10 bytes

i1+:?!;2%n

Explanation:

i1+:?!;2%n

i          Input as code point
 1+        Add one
   :       Duplicate the top item
    ?!;    Terminate if EOF
       2%  Modulo the top item of the stack by two.
           Because we added one earlier, this is effectively flipping the output.
         n Output as integer

Try it here

clap

Posted 2014-06-07T20:20:54.723

Reputation: 834

110 bytes: i1+:?!;2%n. I don't know ><>, but is ? supposed to pop off the stack? – lirtosiast – 2015-09-26T05:01:03.143

Dang. That's clever. Will do :D – clap – 2015-09-26T05:03:38.600

1

Simplex v.0.7, 3 4 bytes

Noncompeting; languages postdates question.

bTng
b    ~~ take string input
 Tn  ~~ applies negation function on each character
   g ~~ clear strip and output it

Conor O'Brien

Posted 2014-06-07T20:20:54.723

Reputation: 36 228

@FryAmTheEggman Oh, a negation. I reade reverse as in, reverse. Editting now – Conor O'Brien – 2015-10-27T19:02:35.497

Yeah a lot of people get that mixed up on this question... anyway cool lang, I hope you get an online interpreter set up soon so I can continue to feed my need to learn esolangs while also being lazy :^) – FryAmTheEggman – 2015-10-27T19:04:32.033

@FryAmTheEggman XD Thanks! You bumped up the interpreter a few spaces on my priority list. (I have quite a lot going on ATM, so I'd expect the interpreter to go online sometime this weekend.) – Conor O'Brien – 2015-10-27T19:09:08.997

1

Python 2, 57 53 52 46 41 bytes

lambda s:''.join(['10'[c>'0']for c in s])

Here's another one, with a different approach:

def b(s):return''.join([str(int(not(int(c))))for c in s])

Shortened with lambda anonymity per the advice of Mego. Shortened with '10' instead of tuple of characters per advice of DLosc

(Thanks!)

James Murphy

Posted 2014-06-07T20:20:54.723

Reputation: 267

1You can turn this into an unnamed lambda to make it shorter: lambda s:''.join([('1','0')[c>'0']for c in s]) – Mego – 2015-10-27T20:15:21.890

1Welcome to PPCG! Here's another 5-byte savings: ('1','0') -> '10'. – DLosc – 2015-10-27T21:43:57.440

Dang! I should've thought of that one! – James Murphy – 2015-10-27T21:47:39.440

You can pass a generator object to ''.join, so you don't need square brackets. – FlipTack – 2017-02-07T19:50:34.650

1

Lua, 66 bytes

function a(b)return b:gsub("1","2"):gsub("0","1"):gsub("2","0")end

Digital Veer

Posted 2014-06-07T20:20:54.723

Reputation: 241

1

Burlesque, 9 bytes

)-.'/'1r~

Try online here.

Explanation:

)-. -- decrement every character (1 -> 0, 0 -> /)
'/'1r~ -- replace / with 1

mroman

Posted 2014-06-07T20:20:54.723

Reputation: 1 382

1

Prolog, 73, 71, 67 bytes

q(X):-X='0',write(1);write(0).
p(X):-atom_chars(X,L),maplist(q,L).

Not an optimal language for this challenge.
Having input in string-form makes for an expensive conversion to list.
Could probably be improved on though.

Testing:
Try it out here

Emigna

Posted 2014-06-07T20:20:54.723

Reputation: 50 798

1

Java 8, 85 bytes

void i(String s) {s.chars().mapToObj(c->(char)49-(int)c).forEach(System.out::print);}

I like Java. I like streams. Gotta do both.

Seims

Posted 2014-06-07T20:20:54.723

Reputation: 631

Hello, and welcome to PPCG! Why is this noncompeting? – NoOneIsHere – 2016-05-26T16:27:14.287

Want to be calm just now. – Seims – 2016-05-26T16:39:02.520

1Golfed: void j(String s){s.chars().map(c->49-c).forEach(System.out::print);} (-17) Good job otherwise. – mrco – 2016-09-26T13:24:47.890

1

PHP, 48 41 bytes

foreach(str_split($argv[1])as$c)echo+!$c;

Saved 7 bytes thanks to Jörg Hülsermann!

Test online

Mario

Posted 2014-06-07T20:20:54.723

Reputation: 3 043

wrong inversion :^( – Destructible Lemon – 2016-09-20T02:30:10.517

@DestructibleWatermelon thanks, It sounded a bit obvious to me but because I didn't get the proper meaning of the question... I'm going to fix the answer. – Mario – 2016-09-20T06:10:54.780

'+!$cinstead of($c>0?0:1)` for the output and delete the space in the loop – Jörg Hülsermann – 2016-09-26T12:01:53.337

@JörgHülsermann Great thanks! I tried to use !$cbut only 1 printed in the output, no 0, I didn't know about the + thing. Brilliant. – Mario – 2016-09-26T13:01:44.813

1

Racket 71 bytes

(λ(s)(list->string(map(λ(x)(if(eq? x #\0)#\1 #\0))(string->list s))))

Detailed version:

(define f
  (λ(s)
    (list->string
     (map
      (λ(x)
        (if(eq? x #\0)
           #\1
           #\0))
      (string->list s)))))

(f "1010111")

Output:

"0101000"

rnso

Posted 2014-06-07T20:20:54.723

Reputation: 1 635

1

Clora, 6 bytes (Noncompeting)

<0I?01

Explanation:

<0I Means, if 0 < I (Current input character), set flag as true

?01 If the flag is true (I is 1), output 0, else output 1

OPSXCQ

Posted 2014-06-07T20:20:54.723

Reputation: 151

Looks like 6 bytes to me... – DLosc – 2016-11-11T20:52:28.960

1

VBA, 74 44 Bytes

VBE immediate window function that takes input from cell [A1] and inverts the binary sting by replacement

?Replace(Replace(Replace([A1],1,2),0,1),2,0)

Taylor Scott

Posted 2014-06-07T20:20:54.723

Reputation: 6 709

0

Java, 39 bytes

s->{for(int i=s.length;i-->0;)s[i]^=1;}

Testing

import java.util.Arrays;
import java.util.function.Consumer;

public class Pcg30361 {
  public static void main(String[] args) {
    Consumer<char[]> f = s->{for(int i=s.length;i-->0;)s[i]^=1;};

    char[] s = "10101110101010010100010001010110101001010".toCharArray();

    char[] expected = "01010001010101101011101110101001010110101".toCharArray();

    f.accept(s);
    System.out.println(Arrays.equals(s, expected));

  }
}

Olivier Grégoire

Posted 2014-06-07T20:20:54.723

Reputation: 10 647

0

Python 3.5, 54 Bytes

print(''.join('1'if a=='0' else '0' for a in input()))

Much longer now ;-; (but it depends how you interpret the Q, invert can mean "reverse" as well as "opposite")

Zachary Smith

Posted 2014-06-07T20:20:54.723

Reputation: 21

This is problematic for two reasons. 1) doesn't do what the challenge asks this reverses a binary string instead of inverting it, 2) it assumes input from a predefined variable which is not considered a valid form of input, relevant meta.

– Post Rock Garf Hunter – 2017-02-07T19:12:43.053

"Invert" has more than one possible interpretation, so it's a simple mistake. Other than that, your right, changes'll be applied later – Zachary Smith – 2017-02-07T19:28:43.037

0

Python 2.7, 69 bytes

Full Program:

b=raw_input();a=''
for i in b:
    if i=='1':a+='0'
    else:a+='1'
print a

Try it online!

Koishore Roy

Posted 2014-06-07T20:20:54.723

Reputation: 1 144

1Its not clear from the specifications but this probably doesn't do what the question wants. It does not work on the one test case provided. – Post Rock Garf Hunter – 2017-06-11T18:11:30.880

@WheatWizard- My bad. I didn't understand the question. Correcting it. – Koishore Roy – 2017-06-12T07:40:15.403

I wouldn't say its your bad, the question is extremely unclear, only providing a test case. – Post Rock Garf Hunter – 2017-06-12T13:19:11.173

0

Braingolf, 12 bytes

i{#0-}n&,{_}

Try it online!

Explanation

i{#0-}n&,{_}
i             Read line from STDIN, convert each char to ordinal and push to stack
 {...}        Foreach, runs on each item in stack
  #0-         Subtract 48 from each ordinal
      n       Negate, all truthy values become 0, all falsey values become 1
       &,     Flip entire stack
         {_}  Print each item

Or...

Braingolf, 7 bytes [kinda double non-competing]

dn&,{_}

Try it online!

Kinda non-competing because braingolf cannot accept integer input from command-line arguments, it will always implicitly convert it to an integer if the input is only digits.

Explanation

dn&,{_}  Implicit input from command-line args
d        Split number into digits
 n       Negate, all truthy values become 0, all falsey values become 1
  &,     Flip entire stack
    {_}  Print each item

Skidsdev

Posted 2014-06-07T20:20:54.723

Reputation: 9 656

0

q/kdb+, 8 bytes

Solution:

"01""0"=

Example:

q)"01""0"="1010101100010011"
"0101010011101100"

Explanation:

Same vein as the J answers, use a boolean list to index into an array of "01"

/ return list of bools where list = "0" (thus inverted)
q)"0"="1010101100010011"
0101010011101100b
/ index into array of "01" at indexes 0 or 1
q)"01" 0101010011101100b
"0101010011101100"

streetster

Posted 2014-06-07T20:20:54.723

Reputation: 3 635

0

C++, 39 bytes

void f(string s){for(v:s)cout<<(v<49);}

Michiel uit het Broek

Posted 2014-06-07T20:20:54.723

Reputation: 131

0

Befunge-98, 12 bytes

'0:~\-!+:,j@

Try it online!

ovs

Posted 2014-06-07T20:20:54.723

Reputation: 21 408

0

Check, 27 bytes

Non-competing as language postdates the question.

   :,r>#v
#d=!pd)##.:+&:R-?

Check is my new esolang. It uses a combination of 2D and 1D semantics. Stack manipulation is done in 1D, while control flow is done in 2D.

This program assumes that the input bits were passed as a command-line argument.

Esolanging Fruit

Posted 2014-06-07T20:20:54.723

Reputation: 13 542

0

Aceto, 7 bytes non-competing

-i
1,p>

Push 1, read a character and cast it to an int, subtract, print, go back to the start.

Non-competing because the challenge predates the language.

L3viathan

Posted 2014-06-07T20:20:54.723

Reputation: 3 151

0

Chip, 6 bytes

A~ae*f

Try it online!

A       Take bit 0x01 of input
 ~      Invert it
  a     Set bit 0x01 of output to that value
    *   Provide a constant 1 value to neighbors
   e f  Set bits 0x10 and 0x20 to 1

So, in English, this prints '0' if the low bit of input is on, and '1' if the low bit is off.

(Chip is a 2D language, which is why the * sends a signal both left and right. It sends the same up and down too. a and e don't interact, so no whitespace is needed there.)

We can handle raw binary data too, in 31 bytes:

A~a B~b C~c D~d E~e F~f G~g H~h

This simply inverts all bits.

Phlarx

Posted 2014-06-07T20:20:54.723

Reputation: 1 366

0

SmileBASIC, 38 bytes

INPUT S$WHILE""<S$?SHIFT(S$)<"1";
WEND

12Me21

Posted 2014-06-07T20:20:54.723

Reputation: 6 110

0

Jq 1.5, 29 bytes

./""|map("\(1-tonumber)")|add

Expanded

  ./""                   # split into array of one character strings
| map("\(1-tonumber)")   # invert each element
| add                    # join array back into a single string

Try it online!

jq170727

Posted 2014-06-07T20:20:54.723

Reputation: 411

0

J-uby, 14 bytes

~:tr&'01'&'10'

equivalent to lambda { |x| x.tr("01","10")}; literally replaces 1 with 0 and 0 with 1.

Cyoce

Posted 2014-06-07T20:20:54.723

Reputation: 2 690

0

SQL 2017, 35 bytes

The TRANSLATE keyword is only available starting in SQL 2017 (is the "non-competing" rule still a thing?), and replaces all instances of characters from the second string with the corresponding character in the third.

SELECT TRANSLATE(a,'01','10')FROM t

Input is via pre-existing table t, per our input standards.

The triple replace for older SQL versions is nearly twice as long (65 bytes):

SELECT REPLACE(REPLACE(REPLACE(a,'0','2'),'1','0'),'2','1')FROM t

BradC

Posted 2014-06-07T20:20:54.723

Reputation: 6 099

0

RProgN 2, 5 bytes

³n¬w;

Try it online!

ATaco

Posted 2014-06-07T20:20:54.723

Reputation: 7 898

0

ARBLE, 23 bytes

join(a|"."|#floor(1-a))

Try it online!

ATaco

Posted 2014-06-07T20:20:54.723

Reputation: 7 898

0

OML, 10 bytes

1(j1^oee)L

Try it online!

Explanation

1(j1^oee)L
1(    ee)    while stdin is not empty
  j          take a character of input
   1^        xor it with 1
     o       and output it
        L    clear the stack (stack is displayed implicitly otherwise)

Conor O'Brien

Posted 2014-06-07T20:20:54.723

Reputation: 36 228

0

R, 49 bytes,

bitwXor(strtoi(unlist(strsplit(scan(,""),""))),1)

Not the shortest answer, but eh !

Here, we :

  • take as input the sequence as a character string scan(,""),
  • split it into its digits strsplit(x, ""), creating a list (an R object),
  • flatten the list unlist(x), creating a vector (another R object).

The items in the vector are converted to integers strtoi, on which the XOR logical operation is applied bitwXor, with respect to 1.

Here we're taking advantage of R's recycling. Both elements of the fonction bitwXor are vectors, but have different length. The function reuse the shortest vector to apply the operation to each element of the longest vector.


Briefly, XOR (⊕) table of truth is :

1 ⊕ 1 = 0
1 ⊕ 0 = 1
0 ⊕ 1 = 1
0 ⊕ 0 = 0

Frédéric

Posted 2014-06-07T20:20:54.723

Reputation: 2 059

0

Excel VBA, 15 Bytes

y=StrReverse(x)

Assuming that x is a String Input, StrReverse Function can be used and the output is y As String. (Credit: Grant Peters)

A code to test the result:

Sub test()
    Dim x As String, y As String
    x = "10101110101010010100010001010110101001010"
    y = StrReverse(x)
    Debug.Print y
    'Output: 01010010101101010001000101001010101110101
End Sub

danieltakeshi

Posted 2014-06-07T20:20:54.723

Reputation: 139

0

Pyth, 6 bytes

jkms!s

Try it!

Takes input as a string. New at this so it probably isn't optimal but the shortest pyth one here so far!

cdd004

Posted 2014-06-07T20:20:54.723

Reputation: 1

0

J, 5 Bytes

That is, if array input is allowed:

i=:-.

Defines the verb i to be the 'not' function.

If string input is mandatory, there's this 10 byte solution:

i=:-.@"."0

If string output is also mandatory, there's this 18 byte solution:

i=:,@:(":@-.@"."0)

Bolce Bussiere

Posted 2014-06-07T20:20:54.723

Reputation: 970

0

Excel, 51 bytes

Performs 3 substitutions: 0 -> 5, 1 -> 0, 5 -> 1

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,0,5),1,0),5,1)

For fun, replacing the third substitution (5 -> 1) eith a /5 works for input where first character is 0. But for others, need to pad with for length. Resulting in 59 bytes:

=TEXT(SUBSTITUTE(SUBSTITUTE(A1,0,5),1,0)/5,REPT(0,LEN(A1)))

Wernisch

Posted 2014-06-07T20:20:54.723

Reputation: 2 534

0

Charcoal, 6 bytes

FθI¬Iι

Try it online!

Link is to the verbose version of the code. Explanation:

Fθ             for each character in the input as string
                implicitly print
      Iι       the character as a number,
     ¬          inverted
   I           and casted again as string

Charlie

Posted 2014-06-07T20:20:54.723

Reputation: 11 448

0

Ahead, 10 bytes

Or is it 01 bytes?

~O!-84i@j~

Try it online!

snail_

Posted 2014-06-07T20:20:54.723

Reputation: 1 982

0

C# (Visual C# Interactive Compiler), 39 bytes

b=>b.Aggregate("",(c,d)=>c+(char)(d^1))

Try it online!

Shortest of all the C# solutions! You can make it even shorter with Select instead of Aggregate if the rules allow you to return a sequence of chars instead of a string.

Embodiment of Ignorance

Posted 2014-06-07T20:20:54.723

Reputation: 7 014

0

Keg, 4 bytes

÷(¬"

Try it online!

  • ÷ splits the number into individual bits
  • ( does the following length of stack times
  • .... ¬ logically not the top
  • .... " right shifts to the next item

Uses latest github interpreter.

Lyxal

Posted 2014-06-07T20:20:54.723

Reputation: 5 253

0

Ruby, 37 32

$*[0].each_char{|x|p x==?0?1:0}

Mhmd

Posted 2014-06-07T20:20:54.723

Reputation: 2 019

132: $*[0].each_char{|x|p x==?0?1:0} – Doorknob – 2014-06-09T13:35:47.177

0

Scala, 33 bytes

print(readLine map(c=>"10"(c&1)))

Dan Getz

Posted 2014-06-07T20:20:54.723

Reputation: 533

0

Powershell 41

(($args-split''-ne'')|%{1-bxor$_})-join''

Explanation:

It reads the input and splits it to turn it into an array. Then it iterates through every element of the array and uses the bitwise exclusive or to turn 1 to 0 and 0 to 1, and then joins the result and prints it to console...

DarkAjax

Posted 2014-06-07T20:20:54.723

Reputation: 669

0

JavaScript 56

a=prompt()
for(b='',r=/./g;c=r.exec(a);b+=c^1);
alert(b)

wolfhammer

Posted 2014-06-07T20:20:54.723

Reputation: 1 219

0

Batch - 167 Bytes

@echo off&setlocal enabledelayedexpansion&set l=-1&set s=%~1&set o=%~1
:c
if defined s set/al+=1&set s=%s:~1%&goto c
for /l %%a in (%l%,-1,0)do set/p=!o:~%%a,1!<nul

Could be cut down a bit by using Powershell to get the length of the input - then again, it could be cut down a lot by using a different language.

unclemeat

Posted 2014-06-07T20:20:54.723

Reputation: 2 302

0

Groovy - 31 28 chars

edit thanks to cfrick's insightful comment:

print args[0].tr("01","10")

previous:

args[0].each{print it=="1"?0:1}

Michael Easter

Posted 2014-06-07T20:20:54.723

Reputation: 585

1groovy also has tr. e.g. b.tr('01','10') – cfrick – 2014-06-10T14:27:47.583

0

Python 3 - 50 bytes

r=str.replace
r(r(r(input(),'1','a'),'0','1'),'a','0')

It's not as short as some of the other ones, but it takes a different approach.

daviewales

Posted 2014-06-07T20:20:54.723

Reputation: 271

0

php, 41 bytes

Where $s is the string:

str_replace(array(1,0,2),array(2,1,0),$s)

This works because the str_replace() function is just a loop when given an array. This works like this:

  • replace all 1 with 2
  • then all 0 with 1
  • then the 2 back to 0

Martijn

Posted 2014-06-07T20:20:54.723

Reputation: 713

0

Java, 101 bytes

class R{String r(String s){return s.replaceAll("0", "2").replaceAll("1", "0").replaceAll("2", "1");}}

Ungolfed

class R{
    String r(String s){
        return s.replaceAll("0", "2").replaceAll("1", "0").replaceAll("2", "1");
    }
}

The Coder

Posted 2014-06-07T20:20:54.723

Reputation: 279

1I think you misunderstood the task ... it was not to reverse the order, but to swap 1 and 0. – Paŭlo Ebermann – 2015-11-01T02:51:38.613

@PaŭloEbermann, corrected it.. Thanks – The Coder – 2015-11-02T04:50:35.067

0

Vitsy, 13 12 Bytes

Byte size reduced by newest version ending execution on end of file*.

I\[i1+2M]l\N
I\             Repeat everything in the [] for input stack's length.
  [i1+2M]      Grab an item from the input, add 1 and modulo 2 (to invert the number).
         l\    Repeat the next character for the currently active program stack's length.
           N   Output the top item of the stack as a number.

*In situations that don't involve special cases.

Addison Crump

Posted 2014-06-07T20:20:54.723

Reputation: 10 763

0

Mathematica / Wolfram Language

Three solutions here, all of which assume that the argument is being passed as a string in a variable "b". If it is being passed in another format (as I think some of the other solutions here assume), shorter solutions are possible.

Method 1, using bitwise operator for 64 char

StringJoin[ToString[BitNot[#] + 2] & /@ ToExpression[Characters@b]]

Method 2 using If/Then for 45 char

StringJoin[If[# == "0", "1", "0"] & /@ Characters@b]

Method 3, operating directly on the string, for 34 char

StringReplace[b, {"0" -> "1", "1" -> "0"}]

I suspect some Mathematica wizard is going to breeze in here and do it in 15 bytes.

Michael Stern

Posted 2014-06-07T20:20:54.723

Reputation: 3 029

@FryAmTheEggman within Mathematica, each of the -> right arrows become single →s. My character count is correct. Mathematica preps copied code for pasting by adding spaces and replacing Unicode with ASCII characters, hence the representation above. – Michael Stern – 2015-10-27T21:31:20.200

We count in bytes, not characters. is 3 bytes. – mbomb007 – 2016-09-16T20:07:03.673

And, they're snippets as opposed to functions or complete programs. http://chat.stackexchange.com/transcript/message/32365215#32365215

– mbomb007 – 2016-09-16T20:35:52.833

0

, 13 chars / 23 bytes (non-competing)

ô⟦ï]ć⇝a^1)ø⬯)

Try it here (Firefox only).

Mama Fun Roll

Posted 2014-06-07T20:20:54.723

Reputation: 7 234

2I think this is technically invalid, because the language was invented after the challenge. – lirtosiast – 2015-10-28T05:27:38.603

1But it doesn't have any advantage specific to the challenge... – Mama Fun Roll – 2015-10-28T13:37:48.860

0

TeaScript, 8 bytes

xl(#l^1)

x       //input
 l(#    //loops through every character of the input
    l^1 //find the inverse of each character
       )

Try it online at its online interpreter (DOES NOT WORK IN CHROME).

user41805

Posted 2014-06-07T20:20:54.723

Reputation: 16 320

With TeaScript 3 this can be xl#l^1 – Downgoat – 2016-02-05T05:34:14.370

0

C, 42 bytes

main(c){for(;c=~getchar();putchar(~c^1));}

xsot

Posted 2014-06-07T20:20:54.723

Reputation: 5 069

0

Ruby, 48 bytes

$<.each_char{|i|print (i.ord-1).chr.gsub"/","1"}

Not the shortest, but somewhat interesting

CocoaBean

Posted 2014-06-07T20:20:54.723

Reputation: 309

0

Python 3, 57 bytes

print(''.join(['0' if i=='1' else '1' for i in input()]))

Dhruv Ramani

Posted 2014-06-07T20:20:54.723

Reputation: 173

0

Pyth, 8 bytes

VwpCxCN1

Vw       for every char in input
     CN  compute char code of char
    x  1 xor with 1
   C     convert from int to char
  p      print

clap

Posted 2014-06-07T20:20:54.723

Reputation: 834

0

pb, 46 bytes (non-competing)

^w[B!0]{w[B=48]{vb[1]^b[0]}>}vw[X!0]{<b[48+B]}

pb is newer than this challenge is, so it can't compete. Oh well.

In pb, the input lives at Y=-1. This program loops over the whole input, putting a 1 below any bytes in the input with a value of 48, or '0'. At the end of the input, it goes back to Y=0 and heads right, adding 48 to everything. Spaces that were left alone become 48=='0', spaces with a 1 value become 49=='1'.

Explained:

^w[B!0]{        # For each byte of input:
    w[B=48]{      # While byte == '0':
        vb[1]^      # Place a 1 on the canvas below it
        b[0]        # Clear input char (just to break loop)
    }
>}

vw[X!0]{<       # For each point on the canvas below the input:
    b[48+B]       # Add 48 to the existing value (convert digit to ASCII)
}

undergroundmonorail

Posted 2014-06-07T20:20:54.723

Reputation: 5 897

0

Beam, 54 bytes

While I having some fun playing with beam, hears the shortest I've managed to do for this one so far. All the unused spaces are a wee bit annoying, but I might be able to compress this a wee bit more.

'''''''>`+++++\
v+<--n<rSP(++ /
 Hu(`<
(@   r^
>@pS r^

Boiled down it compares the the ascii value of STDIN to the ascii value of 1 and decrements if 1 or increments otherwise. It doesn't throw errors or anything if non zeros or ones are encountered.

Try it in the snippet

var ITERS_PER_SEC = 100000;
var TIMEOUT_SECS = 50;
var ERROR_INTERRUPT = "Interrupted by user";
var ERROR_TIMEOUT = "Maximum iterations exceeded";
var ERROR_LOSTINSPACE = "Beam is lost in space";

var code, store, beam, ip_x, ip_y, dir, input_ptr, mem;
var input, timeout, width, iterations, running;

function clear_output() {
document.getElementById("output").value = "";
document.getElementById("stderr").innerHTML = "";
}

function stop() {
running = false;
document.getElementById("run").disabled = false;
document.getElementById("stop").disabled = true;
document.getElementById("clear").disabled = false;
document.getElementById("timeout").disabled = false;
}

function interrupt() {
error(ERROR_INTERRUPT);
}

function error(msg) {
document.getElementById("stderr").innerHTML = msg;
stop();
}

function run() {
clear_output();
document.getElementById("run").disabled = true;
document.getElementById("stop").disabled = false;
document.getElementById("clear").disabled = true;
document.getElementById("input").disabled = false;
document.getElementById("timeout").disabled = false;

code = document.getElementById("code").value;
input = document.getElementById("input").value;
timeout = document.getElementById("timeout").checked;
 
code = code.split("\n");
width = 0;
for (var i = 0; i < code.length; ++i){
 if (code[i].length > width){ 
  width = code[i].length;
 }
}
console.log(code);
console.log(width);
 
running = true;
dir = 0;
ip_x = 0;
ip_y = 0;
input_ptr = 0;
beam = 0;
store = 0;
mem = [];
 
input = input.split("").map(function (s) {
  return s.charCodeAt(0);
 });
 
iterations = 0;

beam_iter();
}

function beam_iter() {
while (running) {
 var inst; 
 try {
  inst = code[ip_y][ip_x];
 }
 catch(err) {
  inst = "";
 }
 switch (inst) {
  case ">":
   dir = 0;
   break;
  case "<":
   dir = 1;
   break;
  case "^":
   dir = 2;
   break;
  case "v":
   dir = 3;
   break;
  case "+":
   if(++beam > 255)
    beam = 0;
   break;
  case "-":
   if(--beam < 0)
    beam = 255;
   break;
  case "@":
   document.getElementById("output").value += String.fromCharCode(beam);
   break;
  case ":":
   document.getElementById("output").value += beam;
   break;
  case "/":
   dir ^= 2;
   break;
  case "\\":
   dir ^= 3;
   break;
  case "!":
   if (beam != 0) {
    dir ^= 1;
   }
   break;
  case "?":
   if (beam == 0) {
    dir ^= 1;
   }
   break;
  case "_":
   switch (dir) {
   case 2:
    dir = 3;
    break;
   case 3:
    dir = 2;
    break;
   }
   break;
  case "|":
   switch (dir) {
   case 0:
    dir = 1;
    break;
   case 1:
    dir = 0;
    break;
   }
   break;
  case "H":
   stop();
   break;
  case "S":
   store = beam;
   break;
  case "L":
   beam = store;
   break;
  case "s":
   mem[beam] = store;
   break;
  case "g":
   store = mem[beam];
   break;
  case "P":
   mem[store] = beam;
   break;
  case "p":
   beam = mem[store];
   break;
  case "u":
   if (beam != store) {
    dir = 2;
   }
   break;
  case "n":
   if (beam != store) {
    dir = 3;
   }
   break;
  case "`":
   --store;
   break;
  case "'":
   ++store;
   break;
  case ")":
   if (store != 0) {
    dir = 1;
   }
   break;
  case "(":
   if (store != 0) {
    dir = 0;
   }
   break;
  case "r":
   if (input_ptr >= input.length) {
    beam = 0;
   } else {
    beam = input[input_ptr];
    ++input_ptr;
   }
   break;
  }
 // Move instruction pointer
 switch (dir) {
  case 0:
   ip_x++;
   break;
  case 1:
   ip_x--;
   break;
  case 2:
   ip_y--;
   break;
  case 3:
   ip_y++;
   break;
 }
 if (running && (ip_x < 0 || ip_y < 0 || ip_x >= width || ip_y >= code.length)) {
  error(ERROR_LOSTINSPACE);
 }
 ++iterations;
 if (iterations > ITERS_PER_SEC * TIMEOUT_SECS) {
  error(ERROR_TIMEOUT);
 }
}
}
<div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;">Code:
    <br>
    <textarea id="code" rows="8" style="overflow:scroll;overflow-x:hidden;width:90%;">'''''''>`+++++\
v+<--n<rSP(++ /
 Hu(`<
(@   r^
>@pS r^</textarea>
    <br>Input:
    <br>
    <textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;">10101110101010010100010001010110101001010</textarea>
    <p>Timeout:
        <input id="timeout" type="checkbox" checked="checked">&nbsp;
        <br>
        <br>
        <input id="run" type="button" value="Run" onclick="run()">
        <input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="disabled">
        <input id="clear" type="button" value="Clear" onclick="clear_output()">&nbsp; <span id="stderr" style="color:red"></span>
    </p>Output:
    <br>
    <textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea>
</div>

MickyT

Posted 2014-06-07T20:20:54.723

Reputation: 11 735

0

Javascript, 81 Bytes:

function(s){return s.replace(/1/g,'a').replace(/0/g,'b').replace(/a/g,0).replace(/b/g,1)}

Test

=>"1001101"

<="0110010"

Fuzzyzilla

Posted 2014-06-07T20:20:54.723

Reputation: 51

function(s){return s.replace(/1/g,'a').replace(/0/g,'1').replace(/a/g,'0')} is shorter. – mbomb007 – 2016-09-16T20:00:55.287

@mbomb007 Oh thanks! I didn't notice that redundancy in mine. Mind if I add that to my original post? – Fuzzyzilla – 2016-09-17T21:34:53.617

0

Clojure, 41 bytes

(fn[b](apply str(map #(if(= %\1)\0\1)b)))

mark

Posted 2014-06-07T20:20:54.723

Reputation: 251

0

Hoon, 34 bytes

|*(* `tape`(turn +< (cury mix 1)))

Stole Dennis' method for using char xor 1 to switch between '0' and '1'.

Return a gate that maps over the tape given, and calls (mix n 1) (binary xor) for each element, then cast the resulting list back to a tape.

In Hoon, the entire memory model is a binary tree of bignums. All code is evaluated on this tree, called the 'subject'. +< is "tree navigation syntax"; instead of specifying a name for the compiler to resolve into an axis of the subject, you can provide the axis yourself with alternating characters of +/- and </> to walk the tree. Code within a gate is evaluated on a subject that has the arguments it was called with placed at +<, so we can reference the arguments directly without having to assign a name to them.

|* creates a wet gate, essentially a generic function, that is typechecked at the callsite with a monomorphized version of the gate. This lets us use * as the sample for the gate instead of having to use |=(tape code) - as long as the type of the arguments at the callee are a valid list, so that ++turn typechecks.

> %.  "10101110101010010100010001010110101001010"
  |*(* `tape`(turn +< (cury mix 1)))
"01010001010101101011101110101001010110101"

RenderSettings

Posted 2014-06-07T20:20:54.723

Reputation: 620

Answers using languages and language features that are newer than the challenge are not allowed and must be marked "non-competing". Is anything you're using from newer than Jun 7 '14 at 20:20? https://github.com/urbit/urbit/commits/master?page=48

– mbomb007 – 2016-09-16T19:56:31.257

@mbomb007 I first started using Urbit on 9/28/14, and the only major Hoon update was recently (164k to 151k), which doesn't affect that snippet. I'll have to check, but I'm quite sure that this is valid. – RenderSettings – 2016-09-19T18:00:54.007

0

C#, 47 44 bytes

as an anonymous function takes a string and returns a string

s=>s.Aggregate("",(a,b)=>a+(b>'0'?'0':'1'));

or as an anonymous function takes a string and prints the inverted, also in 47 bytes

s=>{foreach(var c in s)Write(c=='0'?'1':'0');};

hstde

Posted 2014-06-07T20:20:54.723

Reputation: 159

0

Swift 3 (40 bytes)

As a closure expression that takes x as input and returns a String:

{x in String(cString:x.utf8.map{$0^1})}

Explanation

// make a function…
let invert = { (x: String) in

  // …that will xor each UInt8 character in the input string
  let y = x.utf8.map { $0 ^ 1 }

  // …and create String from the resultant [UInt8]
  String(cString: y)
}

mklbtz

Posted 2014-06-07T20:20:54.723

Reputation: 151

0

Gogh, 5 bytes

{n!}m

This takes the logical not of the integer value of each character in the string.

Zach Gates

Posted 2014-06-07T20:20:54.723

Reputation: 6 152

0

Java, 55 bytes

a->a.replace('0','2').replace('1','0').replace('2','1')

This is a java.util.function.UnaryFunction<String>.

user8397947

Posted 2014-06-07T20:20:54.723

Reputation: 1 242

0

Turtlèd, 24 bytes (non-competing)

' !-[*+.(1'0r)(0'1r)_]' 

[note trailing space]

beating the non golf langs, in a task this language is not really designed for :)

Explanation

'[space]                      write space over initial square
  !                           take input into string variable
   -                          decrement the string pointer (used when writing char from string)
    [*               ]        while current cell is not *
      +.                      increment string pointer, write pointed char from string
        (1'0r)                if cell is 1, write 0, move right
              (0'1r)          if cell is 0, write 1, move right
                    _         EOF checker: if end of string var, write *, else [space]
                      '[space]write space on cell (asterisk must be here)
          [implicit]     remove trailing and leading spaces and newlines, print grid.

Destructible Lemon

Posted 2014-06-07T20:20:54.723

Reputation: 5 908

0

Python 3 - 59 41 bytes

( -18 bytes thanks to @Mego)

lambda s:''.join(str(1-int(c))for c in s)

user59855

Posted 2014-06-07T20:20:54.723

Reputation:

Welcome to PPCG! This solution is valid in both Python 2 and Python 3. There's quite a few improvements you can make, though. 1) By using a lambda function instead of a named function, you can omit the return statement: lambda s:''.join('1'if c=='0'else'0'for c in list(s)). 2) Strings are iterable, so you can replace list(s) with simply s). 3) Using boolean arithmetic on integer values is shorter: str(1-int(c)) instead of '1'if c=='0'else'0'. If you're willing to restrict your answer to Python 2 only, \1-int(c)`` is even shorter. – Mego – 2016-09-20T04:43:56.533

How'd you know I'm new here! Thanks for your suggestions, editing my answer now! I'd rather keep it compatible to both py3 and py2 though. – None – 2016-09-20T11:10:42.443

1I know you're new here because I found your answer in the review queue for answers posted by new users. – Mego – 2016-09-20T11:11:35.447

0

Reticular, 13 bytes

iSBl[:0Eo]~*;

Try it online! Obviously non-competing, as language postdates question.

Explanation

iSBl[:0Eo]~*;
i              take one line of input
 S             convert string to array of chars
  B            merge array with stack
   l           push the length
    [    ]~*   active the inside (length) times
     :0        push the string "0"
       E       check for equality
        o      output
            ;  terminate program

Conor O'Brien

Posted 2014-06-07T20:20:54.723

Reputation: 36 228

0

Java, 97 bytes

Inspired by a comment from 2 years ago @hdante ...

Golfed version:

String d(String s){String r="";for(int i=0;i<s.length();)r(s.charAt(i++)=='0')?"1":"0";return r;}

Ungolfed version:

String d(String s)
{
    String r = "";
    for (int i = 0; i < s.length();)
        r += (s.charAt(i++) == '0') ? "1" : "0";
    return r;
}

Nothing too fancy ...

peech

Posted 2014-06-07T20:20:54.723

Reputation: 309

0

Befunge 98, 13 bytes

#@~1+:'1`2*-,

Increments each character, and substracts 2 if the result is greater than '1' (using a multiply instead of a conditional, i.e. using 2 * <greater than '1'>).

Commented version:

v / Skip the next byte
  |
  |/ End
  ||
  ||/ getc, reflect IP on EOF
  |||
  |||/ push 1
  ||||
  ||||/ add
  |||||
  |||||/ duplicate TOS
  ||||||
  ||||||/ character literal
  |||||||
  |||||||/ push '1'
  ||||||||
  ||||||||/ greater than
  |||||||||
  |||||||||/ push 2
  ||||||||||
  ||||||||||/ multiply
  |||||||||||
  |||||||||||/ substract
  ||||||||||||
  ||||||||||||/ putc
  |||||||||||||
> #@~1+:'1`2*-,

ninjalj

Posted 2014-06-07T20:20:54.723

Reputation: 3 018

0

Binary-Encoded Golfical, 31 bytes

Noncompeting, language postdates the question.

This encoding can be converted back to Golfical's standard graphical format using the encoder/decoder provided in the Golfical github repo, or run directly by using the -x flag.

Hex dump of binary encoding:

00 80 03 00 30 14 14 0C 01 14 14 1B 14 1A 16 14
14 26 14 14 25 1B 14 00 30 00 31 17 1C 1C 1D

Original image:

enter image description here

Scaled up 45x:

enter image description here

SuperJedi224

Posted 2014-06-07T20:20:54.723

Reputation: 11 342

0

Lithp, 61 bytes + 3 for -v1 flag

#S::((replace S (regex "\\d" "g") (js-bridge #X::((^ X 1)))))

Requires the -v1 flag to run.js, as js-bridge is not part of the standard library yet.

Exploits the JavaScript's String.replace function by passing a bridge function, allowing Lithp code to handle the replacement.

Usage:

(
    (def i #S::((replace S (regex "\\d" "g") (js-bridge #N::((^ N 1))))))
    (print (i "01010101111000"))
)

Andrakis

Posted 2014-06-07T20:20:54.723

Reputation: 361

0

Python 3, 39 bytes

Taking input from stdin and printing to stdout:

for c in input():print(1-int(c),end="")

Aryaman

Posted 2014-06-07T20:20:54.723

Reputation: 161

0

Logicode, 9 bytes

out ~ainp

Try it online!

clismique

Posted 2014-06-07T20:20:54.723

Reputation: 6 600

-1

TI-BASIC, 3 bytes

B=0

Same "feature" as J; assuming the binary is stored in B, it will display the output. Here is an explanation:

The TI-BASIC comparison operator is =. However, = doesn't work like the normal == operator: it compares item-by-item. Keep in mind that an array is formed like this: {0,2,3}. 2={0,2,3} returns {0,1,0} for example. Since TI-BASIC's bools are 1 and 0, this results in a list of 1's and 0's (They aren't strings, and every other character other than 1 would also result in 0.)

Timtech

Posted 2014-06-07T20:20:54.723

Reputation: 12 038

4Works only on lists, not strings; B isn't even a list or string variable. – lirtosiast – 2015-06-08T02:27:46.507

As a side note, not(B would do the same thing. – Timtech – 2014-06-11T11:06:17.850