52
\$\begingroup\$

Challenge

Given a non-empty string S of length L consisting entirely of printable ASCII chars, output another string of length L that consists entirely of printable ASCII chars, but is not equal to S.

For the purposes of this challenge, a printable ASCII char is one between U+0020 and U+007E, inclusive; that is, from (space) to ~ (tilde). Newlines and tabs are not included.

For example, given "abcde", some valid outputs could be:

  • "11111"
  • "abcdf"
  • "edcba"

But these would be invalid:

  • "abcde"
  • "bcde"
  • "abcde0"

Test cases

"asdf"
"1111"
"       "
"~~~~~"
"abcba"
"1"
" "
"~"
" ~"
"~ "
"  0"
"!@#$%^&*()ABCDEFGhijklmnop1234567890"
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"

Rules

  • You may assume the input consists entirely of printable ASCII chars.
  • You may not assume that the input does not contain all 95 printable chars.
  • You may assume the input contains at least one character and is less than 256 chars long.
  • The output must also consist entirely of printable ASCII chars. You could not, for example, output the byte \x7F for input "~".
  • The output must be different than the input with probability 1; that is, you may generate random strings until one is different than the input, but you can't just output L random characters and hope it's different.
  • Newlines are disallowed in the output, but you may output one trailing newline which is not counted toward the string.

Scoring

This is , so the shortest code in bytes in each language wins.

\$\endgroup\$
  • \$\begingroup\$ Note that "positive" excludes the empty string. For extra clarity, maybe replace "positive" with "nonzero"? \$\endgroup\$ – CalculatorFeline May 30 '17 at 20:30
  • 4
    \$\begingroup\$ @CalculatorFeline But that would include negative-length strings /s \$\endgroup\$ – ETHproductions May 30 '17 at 20:36
  • 1
    \$\begingroup\$ ...Those don't exist. \$\endgroup\$ – CalculatorFeline May 30 '17 at 20:38
  • \$\begingroup\$ (that's the point) \$\endgroup\$ – ETHproductions May 30 '17 at 20:38
  • 2
    \$\begingroup\$ Another simple but not trivial challenge. \$\endgroup\$ – Weijun Zhou Apr 4 '18 at 15:03

69 Answers 69

34
\$\begingroup\$

Python 2, 21 bytes

lambda s:`s`[:len(s)]

Try it online!

Takes the string representation of the input string and truncates it to the length of the input string. For a typical string, this puts it in ' quotes and chops off the end:

abc  ->   'abc'  ->  'ab
     rep        chop

Note that the new string starts with '. Let's show that the output always differs from the input.

  • If the input has no ', then the output starts with ' and the input does not.

  • If the input contains a ' and but no ", then Python will use " for the outer quotes, giving a first character " that's not in the input string.

  • If the input has both ' and ", then the outer quotes are ' and each ' is escaped as \'. Wherever the first " appears in the input, it's shifted right by the initial ' in the output and by any possible escaping. This means it cannot match with a " in the corresponding position in the output.

Finally, note that quoting the input and possibly escaping characters always increases the number of characters, so truncating the output makes it the same length as the input.

Note that it was crucial that Python adaptively switches to " in the second case. If it didn't do so, it would fail on the three-character input '\'. Or, any longer prefix of the fix show string using '. So, this method won't work for most languages.

\$\endgroup\$
  • \$\begingroup\$ What's the reasoning for indexing 'til len(s) rather than -2? \$\endgroup\$ – Julian Wolf May 31 '17 at 0:09
  • 1
    \$\begingroup\$ @JulianWolf For an input containing both ' and ", more than 2 characters will have been added because the quotes need to be escaped. \$\endgroup\$ – Anders Kaseorg May 31 '17 at 0:20
  • \$\begingroup\$ Makes sense; hadn't considered that. Thanks! \$\endgroup\$ – Julian Wolf May 31 '17 at 2:31
  • \$\begingroup\$ You can use [2:] instead of [:len(s)] to get down to 16 chars. \$\endgroup\$ – xbarbie Apr 4 '18 at 8:02
  • \$\begingroup\$ @xbarbie That doesn't always give the same length, if there are characters needing escaping. \$\endgroup\$ – xnor Apr 4 '18 at 8:39
16
\$\begingroup\$

05AB1E, 3 bytes

ÇÈJ

Try it online!

Ç   # Convert to ASCII values
 È  # is even? (0 is 48 and 1 is 49 therefore 0 -> 1 and 1 -> 0)
  J # Join
\$\endgroup\$
  • \$\begingroup\$ Nice, very clever \$\endgroup\$ – Adnan May 30 '17 at 17:35
15
\$\begingroup\$

JavaScript (ES6), 37 33 36 29 26 18 21 19 bytes

s=>s.slice(1)+ +!+s

Try it online!

-4 bytes thanks to ETHProductions

-7 + -5 + -2 bytes thanks to CalculatorFeline

-3 bytes thanks to Rick Hitchcock

Moves the first character to the end and sets it to 0 if it's numeric and non-zero, and 1 otherwise.

Explanation

s=>                    anonymous function with parameter s
                 +s    convert s to a number
                !      not (converts to boolean; relevant: 0->true,1->false)
               +       convert !+s back to number (true->1, false->0)
   s.slice(1)+         prefix the rest of the string
              ␣        needed to avoid the +s combining

Proof

Because the second char becomes the first, the third char becomes the second, etc. all chars would have to be identical. The last remaining char can only be a 0 or a 1, so the repeated char would have to be either 0 or 1. But any string of 0s produces a 1 at the end, and vice-versa; therefore, it is impossible to create an input that is equal to its output. -ETHProductions

See edits for former versions and explanations.

f=
s=>s.slice(1)+ +!+s

console.log(f("000"))
console.log(f("111"))
console.log(f("001"))
console.log(f("110"))
console.log(f("~"))
console.log(f("111111111111111111111111111111111111111111111111111"))
console.log(f("Hello world!"))
console.log(f("23"))
console.log(f(" "))
console.log(f("1x"))

\$\endgroup\$
13
\$\begingroup\$

Jelly, 3 bytes

~Ṿṁ

Output is a string of digits, commas and hypen-minus characters, whose first character will differ from the first character of the input string.

Try it online!

How it works

~Ṿṁ  Main link. Argument: s (string)

~    Map bitwise NOT over the characters c in s.
     This attempts to cast c to int and then apply bitwise NOT, mapping
     '0', ..., '9' to 0, ..., 9 (before ~), then -1, ..., -10 (after ~).
     For non-digits, the attempt fails, mapping c to 0.
 Ṿ   Uneval, yielding a comma-separated string of integers in [-10, ..., 0].
     The first character will be '-' if s starts with a digit and '0' if not.
  ṁ  Mold; truncate the result to the length of s.
\$\endgroup\$
6
\$\begingroup\$

Haskell, 20 bytes

map$head.show.(<'M')

Try it online!

Converts to a string of F and T. What matters is that the characters F and T converts to each other. This is done by checking if the character is less than M to get True or False, then taking the first character of the string representation.


Haskell, 23 bytes

q '~'=' '
q _='~'
map q

Try it online

Replaces every character with ~, except ~ becomes a space.

\$\endgroup\$
  • \$\begingroup\$ What is the significance of the space in q '~'? Why can't it be removed? \$\endgroup\$ – Cyoce Sep 6 '17 at 7:23
  • \$\begingroup\$ @Cyoce Haskell permits ' as a character in identifiers, so q'~'=' ' would be parsed as q' ~ '=' ' (reporting a lexical error because the last ' is unmatched.) \$\endgroup\$ – Ørjan Johansen Dec 27 '17 at 2:36
5
\$\begingroup\$

Whitespace, 59 bytes

Visible representation

NSSNSSSTSSSSSNSNSSNSSNSTNTSTTTTSSTNTTSNSNSTSSSNSSSNTNSSNSNN

What it does:

For every character it reads it prints a space, except when it's a space, then it prints a @.

Disassembly:

loop:
    push 32
     dup
      dup
       dup
        ichr
       get
       sub
      jn not_32
     dup
      add
not_32:
     pchr
    jmp loop
\$\endgroup\$
  • \$\begingroup\$ Always nice to see a solution in Whitespace. Especially when you normally are unable to actually see it. +1 \$\endgroup\$ – Josiah Winslow Sep 6 '17 at 2:05
  • \$\begingroup\$ Nice answer! I tried to come up with something shorter to the structure, but couldn't find anything. But you can golf 2 bytes by changing the SSSTSSSSSN (push 32) to SSSTSSTN (push 9) and the TSSS (add) to TSSN (multiply). It will print a tab for every character with a unicode value above 9, and a Q (9*9=81) for every character with a unicode value of 0..9. Try it online raw 57 bytes, or Try it online with added highlighting and explanation \$\endgroup\$ – Kevin Cruijssen Apr 3 '18 at 8:59
  • \$\begingroup\$ Ignore my comment above. For the challenge a tab isn't considered as a printable ASCII character.. \$\endgroup\$ – Kevin Cruijssen Apr 3 '18 at 9:23
5
\$\begingroup\$

MATL, 6 5 bytes

Qo!V!

Try it online!

Explanation

Q     % Implicitly input a string. Add 1 to each code point.
o     % Parity: 0 if odd, 1 if even. Note that '0' has ASCII code 48, so after
      % having added 1 it now gives 1. Similarly. '1' has ASCII code 49, so it
      % now gives 0. All other chars give 0 or 1. 
!V!   % Convert each number to the corresponding char. Implicitly display
\$\endgroup\$
  • \$\begingroup\$ That's 5 in CJam: l'0f= (if it does what I think it does) \$\endgroup\$ – Martin Ender May 30 '17 at 16:17
  • \$\begingroup\$ @MartinEnder Yes, it's exactly that :-) I've just added an explanation \$\endgroup\$ – Luis Mendo May 30 '17 at 16:19
5
\$\begingroup\$

Haskell, 19 bytes

An anonymous function which takes and returns a String. Use as (map$(!!1).show.succ) "1111".

map$(!!1).show.succ

Try it online! (Using @xnor's testing harness.)

  • For each character in the input string, increments the character, then converts that to character literal format, then takes the second character of the literal, which is the character just after the starting ' quote.
  • For nearly all printable characters, this results in simply the incremented character. The exceptions are & and ~, which instead give \, because their successors ' and \DEL get escaped in character literals.
\$\endgroup\$
  • \$\begingroup\$ pretty sure head can be used in place of (!!1) for an extra byte \$\endgroup\$ – Julian Wolf May 31 '17 at 16:21
  • \$\begingroup\$ No, head is (!!0), not (!!1). It would fail on the character '. \$\endgroup\$ – Ørjan Johansen May 31 '17 at 16:48
  • \$\begingroup\$ Ah, right. I'd just been reading the python answer and forgot that quotes usually needed special treatment. \$\endgroup\$ – Julian Wolf May 31 '17 at 16:52
4
\$\begingroup\$

05AB1E, 5 bytes

žQDÀ‡

Try it online!

Explanation

Replaces each char with the next printable ascii char, wrapping from tilde to space.

žQ     # push a string of printable acsii chars (space to tilde)
  D    # duplicate
   À   # rotate left
    ‡  # translate
\$\endgroup\$
4
\$\begingroup\$

V, 7 bytes

íÁ/a
g?

Try it online! or Verify all test cases!

How does it work?

Consider all strings consisting of printable ASCII. Every string must either 1) Contain alphabetic characters, or 2) Contain no alphabetic characters.

So the way this program works is by first converting one non-alphabetic character into 'a', and then performing ROT13 on the input string.

í       " Substitute:
 Á      "   A non-alphabetic character ([^a-zA-Z])
  /     "   with
   a    "   the letter 'a'
g?      " Perform ROT13 on...
        "   (Implicit) the current line.
\$\endgroup\$
  • \$\begingroup\$ This breaks if you have a number like 9 alone, where incrementing it adds another character to the string \$\endgroup\$ – nmjcman101 May 30 '17 at 19:23
  • \$\begingroup\$ @nmjcman101 Ah, that's a good point. I've reverted \$\endgroup\$ – DJMcMayhem May 30 '17 at 19:23
  • \$\begingroup\$ I like the ROT13 thing though, I didn't know V(im) could do that \$\endgroup\$ – nmjcman101 May 30 '17 at 19:24
4
\$\begingroup\$

C (gcc), 22 bytes

f(char*s){*s=65+*s%2;}

Takes a string pointer and modies the first char in place.

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Shorter: *s=159-*s. Always changes the last bit, therefore never gives the same character. Note that 159 = ' ' + '~' \$\endgroup\$ – celtschk May 31 '17 at 11:31
  • \$\begingroup\$ I think you mean 158 = ' ' + '~'. 159-32 = 127, which would be a character out of scope. But good idea. \$\endgroup\$ – Computronium May 31 '17 at 13:51
  • \$\begingroup\$ @celtschk Involutions cannot work, as there's an odd amount (95) of printable chraracters, so at least one of them will map to itself. \$\endgroup\$ – Dennis May 31 '17 at 15:43
  • \$\begingroup\$ @Computronium: Oops, you're right, I got the character code of ~ wrong. \$\endgroup\$ – celtschk May 31 '17 at 18:58
4
\$\begingroup\$

C (gcc), 20 bytes

Saw Dennis's answer, thought of a 2 byte essential improvement.

f(char*s){*s^=*s/3;}

Try it online! (Footer by Dennis.)

Like the original, modifies the first character of the string in place, but xors it with its value divided by 3 (the smallest number that works. 2 fails on the single character 'U' which gives 127, not printable.)

\$\endgroup\$
4
\$\begingroup\$

Python 2, 25 bytes

lambda s:`s<'T'`[0]+s[1:]

Try it online!

Anders Kaseorg saved a byte by extracting the first character from True or False.

\$\endgroup\$
  • \$\begingroup\$ I'd suggest changing '?' to a 2 digit charcode, but Python isn't one of those languages where you can do that :( \$\endgroup\$ – CalculatorFeline May 30 '17 at 21:21
  • \$\begingroup\$ Variants saving a byte (but dropping Python 3 compatibility): lambda s:`+(s<'1')`+s[1:] or lambda s:`s<'T'`[0]+s[1:] \$\endgroup\$ – Anders Kaseorg May 31 '17 at 0:14
3
\$\begingroup\$

Haskell, 30 26 bytes

f ' '='~'
f c=pred c
map f

Try it online!

Replaces each char with its predecessor and space with tilde.

\$\endgroup\$
3
\$\begingroup\$

Octave, 19 18 bytes

@(s)['',(s<66)+65]

Try it online!

Explanation:

@(s)                 % Anonymous function taking a string s as input
         s<66        % A boolean vector with `1` for all characters below ASCII-66.
        (s<66)+65    % Add 65 to this, so that all elements that are 32-65 are now 66.
                     % All other elements are 65 
    ['',         ]   % Implicitly convert the list of 65 and 66 to the letters A and B
\$\endgroup\$
3
\$\begingroup\$

CJam, 5 bytes

l)iA%

Try it online!

Converts the last character to its code point and takes that modulo 10. This is clearly different for non-digit characters in the last position. But the digits start at code point 48, so taking those mod 10 will shift them left cyclically and hence the last character is always changed.

\$\endgroup\$
3
\$\begingroup\$

Retina, 10 6 bytes

4 bytes golfed thanks to @Neil

T`p`~p

Try it online!

This transliterates to ~, ! to , " to !, ..., ~ to }.

\$\endgroup\$
3
\$\begingroup\$

Japt, 4 bytes

®c v

Try it online!

Explanation:

®c v
®    At each char:
 c     Convert to its ASCII value
   v   Return 1 if divisible by 2, otherwise return 0
\$\endgroup\$
3
\$\begingroup\$

Cubix, 10 bytes

..@|i?2%)O

Try it online! or Watch it run!

For each char, prints 1 if the char has an even code point, 2 otherwise; 1 has an odd code point and 2 an even, so the output will never equal the input.

Explanation

This code corresponds to the following cube net:

    . .
    @ |
i ? 2 % ) O . .
. . . . . . . .
    . .
    . .

The IP (instruction pointer) starts at the top-left corner of the far-left face, heading east. It follows this series of instructions:

i     Grab a char-code from STDIN and push it to the stack (-1 if there is no more input).
?     If the top item is negative, turn left and hit @ which ends the program.
      If it's positive (any printable ASCII char), turn right. The IP runs through a bunch
        of no-ops, then hits:
)     Increment the top item.
|     Mirror the IP's direction horizontally (turns it around).
)     Increment the top item again. The IP then wraps around again until it hits:
?     The top item is positive, so turn right.
2     Push a 2 to the stack.
%     Push the modulus of the top two items (0 for even char-code, 1 for odd).
)     Increment the result (now 1 for even char-code, 2 for odd).
O     Output as a number. The IP wraps back around to the i and the process starts again.
\$\endgroup\$
3
\$\begingroup\$

Alice, 9 bytes

#oi/
t i@

Try it online!

Explanation

The idea was taken from Martin Ender's CJam submission. The first character is taken as a code point, reduced mod 10, and moved to the end of the output. Since exactly one character was changed, permuting the characters cannot result in getting the same string back.

#   skip next command
o   (skipped)
i   push first byte onto stack
    STACK: [97]
/   reflect to SE, switch to ordinal mode (implicit reflect to SW)
i   push remaining input onto stack as string (implicit reflect to NW)
    STACK: [97, "sdf"]
o   output top of stack (implicit reflect to SW)
    STACK: [97]
t   implicitly convert code point to decimal string, and extract last character
    (implicit reflect to NE)
    STACK: ["9", "7"]
o   output this last digit (implicit reflect to SE)
i   push empty string, since there is no more input to take (implicit reflect to NE)
/   reflect to S, switch to cardinal mode
@   terminate
\$\endgroup\$
  • \$\begingroup\$ Using t for mod 10 is really clever, nice. :) \$\endgroup\$ – Martin Ender Jun 1 '17 at 12:26
3
\$\begingroup\$

Pushy, 1 byte

Q

Try it online!

This converts the given string into list of ASCII character codes, indexes them (modular indexing) into the uppercase alphabet, then prints the result. Essentially, each character n is mapped to chr(ord(n) % 26 + 65). You can use this program to see how the mapping works.

The output:

  • Will always be the same length as the input, as the characters are directly mapped into new ones.
  • Will always comprise only printable ASCII characters (as it only contains uppercase letters)
  • Will always be different to the input, as there is no possible input character n such that chr(ord(n) % 26 + 65) == n, as for this to be true there must be an integer x such that 26x = 65, for which there is no solution.

1 byte

q

Try it online!

This answer is exactly the same, except that it maps to lowercase alphabet characters rather than uppercase alphabet characters. This is still valid as there is no possible input character n such that chr(ord(n) % 26 + 97) == n.

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

Brain-Flak, 53 bytes

Includes +1 for -c

([(((()()()()){}){}){}()]({}())){{}(<({}[()()])>)}{}

This will decrement the first character unless it is a space, in that case it will increment the first character.

Try it online!

([(((()()()()){}){}){}()]      )                     # Push: input + 1 != 33 on top of...
                         ({}())                      #    input + 1
                                {{}(<          >)}{} # If (input + 1 != 33)
                                     ({}[()()])      #   Push: (input + 1) - 2
\$\endgroup\$
2
\$\begingroup\$

Jelly, 4 bytes

^1Ṿ€

Outputs a digit string. No output character will be equal to the corresponding input character.

Try it online!

How it works

^1Ṿ€  Main link. Argument: s (string)

^1    XOR each character c in with 1.
      This attempts to cast c to int, mapping '0', ..., '9' to 0, ..., 9.
      For non-digits, the attempt fails, mapping c to 0.
      After XORing with 1, we get 1, 0, 3, 2, 5, 4, 7, 6, 9, 8 for '0', ..., '9', 
      and 1 for all non-digits.
  Ṿ€  Uneval each; mapping 0, ..., 9 to '0', ..., '9'. This yields a character
      array, which is Jelly's string type.
      Note that no character is mapped to itself.
\$\endgroup\$
2
\$\begingroup\$

Bash + coreutils, 13

tr \ -~ ~\ -}

Transliterates the characters to ~ (0x20 - 0x7e) with ~, then to } (0x7e, 0x20 - 0x7d).

Try it online.

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

PHP, 30 27

<?=strtr($a=$argn,$a,$a^1);

Changes every each char equal to the first char with the char that has the least significant bit flipped.

\$\endgroup\$
  • \$\begingroup\$ Does "~" work?. \$\endgroup\$ – CalculatorFeline May 30 '17 at 21:23
  • \$\begingroup\$ It doesn't actually flip the least significant bit of the first char; it converts it to an integer and flips the least significant bit of that. So yes, @CalculatorFeline, ~ does work, outputting 1. \$\endgroup\$ – ETHproductions May 30 '17 at 22:52
  • \$\begingroup\$ Oh. Does !$a or ~$a work? \$\endgroup\$ – CalculatorFeline May 30 '17 at 23:13
  • \$\begingroup\$ @ETHproductions I did the last edit shortly before going to bed and didn't have the time to update it. Of course your right it first converts to integer and therefore might not even change the first char but maybe the second e.g. "12" becomes "13". \$\endgroup\$ – Christoph May 31 '17 at 5:36
  • \$\begingroup\$ @CalculatorFeline sadly both fail !$a turns "12" into "12" because false is converted to an empty string so that nothing gets replaced and ~$a turns everything into unprintables because ~"12" doesn't convert to int first but literally flips all bits in the string. \$\endgroup\$ – Christoph May 31 '17 at 5:43
2
\$\begingroup\$

Ruby, 20+1 = 21 bytes

Uses the -p flag.

sub(/./){$&=~/1/||1}

Try it online!

Replaces the first character in the input with a 0 if it is 1, or 1 otherwise.

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

Brachylog, 9 bytes

{¬Ṣ|∧Ịh}ᵐ

Try it online!

Explanation

This replaces all chars by a space, except spaces which it replaces with "0".

{      }ᵐ      Map on each char of the Input
 ¬Ṣ              The Input char is not " ", and the Output char is " "
   |             Or
    ∧Ịh          The Output char is "0"
\$\endgroup\$
2
\$\begingroup\$

PHP<7.1, 31 Bytes

for(;~$c=$argn[$i++];)echo$c^1;

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Please remove the 66 byte solution because it's invalid. \$\endgroup\$ – CalculatorFeline May 30 '17 at 20:20
  • \$\begingroup\$ Fails for inputs "1", "10", "101" etc. You can't only depend on the string length. \$\endgroup\$ – CalculatorFeline May 30 '17 at 20:26
  • \$\begingroup\$ @CalculatorFeline "1" outputs "0", "10" outputs "01", "101" outputs "010". Where's the problem? \$\endgroup\$ – Christoph May 30 '17 at 20:31
  • \$\begingroup\$ @CalculatorFeline "1"=>0, "10"=>01, "101"=>010 Where fails it? \$\endgroup\$ – Jörg Hülsermann May 30 '17 at 20:31
  • 1
    \$\begingroup\$ PHP 7.1 yields A non-numeric value encountered. And You can use ~ instead of a&. \$\endgroup\$ – Titus May 31 '17 at 15:56
2
\$\begingroup\$

Golfscript, 3 bytes

Try it online!

)5%

Take the last character's ASCII value modulo 5, and replace the last character with the result. This obviously works for non-digit characters, but if the last character is a digit, it also changes ("0" mod 5 = 3, "1" mod 5 = 4, etc).

This would also work with 7 or 9 while still keeping the same length.

Also, yay! I have a Golfscript solution as good as the best solutions here!

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

Funky, 26 22 bytes

s=>s::gsub("."a=>1&~a)

Calculates ~a which for non-digits will return NaN. Then 1& limits it to either 0 or 1, for the digit 0, this will be 1, and for 1 this will be 0. So this string is always unique.

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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