Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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 inverse like so:

01010001010101101011101110101001010110101
share|improve this question
    
There is a shell utility rev that does this, so technically all it takes is a 3-byte shell script, although I see such answers are implicitly disallowed. –  David Z 6 hours ago
add comment

22 Answers

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.

share|improve this answer
3  
Wait, golfscript? –  ToonAlfrink yesterday
    
I had misinterpreted your question. Fixed now. –  Dennis yesterday
    
I'm always amazed at what can be accomplished in GolfScript. Would you mind explaining the code? –  tolos yesterday
1  
@tolos: I've edited my answer. –  Dennis yesterday
2  
@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 17 hours ago
add comment

J (5)

Assumes the input string is in variable b.

b='0'

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

share|improve this answer
5  
+1 for a underhanded –  Kroltan 20 hours ago
add comment

Bash+coreutils, 8 bytes

tr 01 10

Takes input from STDIN.


Or

sed, 8 bytes

y/01/10/
share|improve this answer
    
I recently made a golfing library/alias set for Bash github.com/professorfish/bash-shelf. you can shave off one char with that: y 01 10 –  professorfish yesterday
    
Where is BASH involved here? What is BASH specific? Every shell can call tr... –  yeti 20 hours ago
    
@yeti Not every shell calls commands like bash or zsh. In some shells that code alone is a syntax error –  mniip 19 hours ago
3  
It's probably safe to assume that "shell" means "POSIX-compatible shell" here... –  FireFly 19 hours ago
add comment

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.

share|improve this answer
add comment

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/

share|improve this answer
    
So that's how you use f. –  Dennis 17 hours ago
    
@Dennis Indeed. You can use the sf forum to ask questions btw :) –  aditsu 15 hours ago
add comment

C: 29

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

Try it online here.

Thanks for pointing out the XOR trick, Dennis.

share|improve this answer
4  
Simpler & shorter: i(char*s){while(*s)*s++^=1;} –  edc65 21 hours ago
add comment

Brainfuck (70)

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

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
share|improve this answer
add comment

Perl, 9 characters

'y/10/01/'

The 9th character is the 'p' flag

Usage:

$ echo '10101001' | perl -pe 'y/10/01/'
share|improve this answer
1  
also works as a sed script y/10/01/ but one char shorter because it doesn't need any flags –  professorfish yesterday
2  
You don't need single quotes here. –  xfix 23 hours ago
add comment

Javascript (ES6) 36

alert(prompt().replace(/./g,x=>x^1))
share|improve this answer
    
Assuming input in s, s.replace(/./g,x=>x^1) are 22 chars. –  Oriol 12 hours ago
    
I like to actually output and input. –  nderscore 11 hours ago
    
@nderscore Save 2 chars: p=prompt(p().replace(/./g,x=>x^1)) –  Gaurang Tandon 1 hour ago
add comment

Python 2.7 – 29

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

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

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

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

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

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

And backticks can be used instead of str()

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

Reduced to 44 from 29 thanks to pointers from @TheRare

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

share|improve this answer
1  
Ya'know, (int(x) and 1) == int(x) –  TheRare 20 hours ago
    
@TheRare I didn't, thanks for that :) –  BassemDy 19 hours ago
1  
For 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 –  TheRare 19 hours ago
1  
Seems like you missed some spaces. Also, backticks can be used to replace repr(). ''.join(`1-int(x)`for x in'') –  TheRare 19 hours ago
1  
Fyi, repr(x) for x < maxint is equal to str(x) –  TheRare 18 hours ago
show 7 more comments

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()))
share|improve this answer
    
Code will work without the end='' just a , will do :) - unless you care about there being no spaces –  British Colour yesterday
    
@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 yesterday
    
Aww, cool, I did't know that! I mainly work in 2.7 :/ –  British Colour yesterday
add comment

Cobra - 89

class P
    def main
        r=''
        for i in Console.readLine,r+=if(i==c'1','0','1')
        print r
share|improve this answer
add comment

Ruby: 23

p $<.read.tr("01","10")
share|improve this answer
add comment

C# in LINQPad, 64

foreach(var c in Console.ReadLine())Console.Write((char)(97-c));
share|improve this answer
add comment

PHP > 5.4 -- 37 characters

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

$s is the input

Try it online

share|improve this answer
add comment

Python 2.x - 44 bytes

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

Why make it complex, or use some cheaty variables?

share|improve this answer
add comment

PHP - 19 bytes

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

Yea, not really original, I guess!

share|improve this answer
    
+1 for the (ab)use of numeric array keys. –  Ilmari Karonen 1 hour ago
add comment

x86 machine code on DOS - 27 25 bytes

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

Can be easily run in DosBox as a .COM file; expects the input on the command line.

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:
    mov ah, 4ch
    int 21h
share|improve this answer
add comment

Ruby, 37

ARGV[0].each_char{|x|p x.to_i==0?1:0}
share|improve this answer
add comment

Scala, 33 bytes

print(readLine map(c=>"10"(c&1)))
share|improve this answer
add comment

Tcl - 23 bytes

string map {0 1 1 0} $s

Not quite the shortest but highly readable.

share|improve this answer
add comment

python, 34

''.join([str(int(c)^1)for c in s])
share|improve this answer
add comment

protected by Community 16 hours ago

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.