Same length, different string

53

4

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.

ETHproductions

Posted 2017-05-30T15:57:37.327

Reputation: 47 880

Note that "positive" excludes the empty string. For extra clarity, maybe replace "positive" with "nonzero"? – CalculatorFeline – 2017-05-30T20:30:21.220

5@CalculatorFeline But that would include negative-length strings /s – ETHproductions – 2017-05-30T20:36:04.070

1...Those don't exist. – CalculatorFeline – 2017-05-30T20:38:07.607

@CalculatorFeline Better now? – ETHproductions – 2017-05-30T20:40:09.867

....really? -_- Also yes. – CalculatorFeline – 2017-05-30T20:40:10.143

Related – TheLethalCoder – 2017-05-31T12:53:18.420

3Another simple but not trivial challenge. – Weijun Zhou – 2018-04-04T15:03:52.190

Answers

34

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.

xnor

Posted 2017-05-30T15:57:37.327

Reputation: 115 687

What's the reasoning for indexing 'til len(s) rather than -2? – Julian Wolf – 2017-05-31T00:09:00.987

1@JulianWolf For an input containing both ' and ", more than 2 characters will have been added because the quotes need to be escaped. – Anders Kaseorg – 2017-05-31T00:20:37.237

Makes sense; hadn't considered that. Thanks! – Julian Wolf – 2017-05-31T02:31:32.897

You can use [2:] instead of [:len(s)] to get down to 16 chars. – xbarbie – 2018-04-04T08:02:38.133

@xbarbie That doesn't always give the same length, if there are characters needing escaping. – xnor – 2018-04-04T08:39:11.973

@xnor Oh, I see now, '\"\'' is such example... Thank you! – xbarbie – 2018-04-04T08:55:52.207

16

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

Riley

Posted 2017-05-30T15:57:37.327

Reputation: 11 345

Nice, very clever – Adnan – 2017-05-30T17:35:15.490

15

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"))

Stephen

Posted 2017-05-30T15:57:37.327

Reputation: 12 293

13

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.

Dennis

Posted 2017-05-30T15:57:37.327

Reputation: 196 637

6

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.

xnor

Posted 2017-05-30T15:57:37.327

Reputation: 115 687

What is the significance of the space in q '~'? Why can't it be removed? – Cyoce – 2017-09-06T07:23:02.537

@Cyoce Haskell permits ' as a character in identifiers, so q'~'=' ' would be parsed as q' ~ '=' ' (reporting a lexical error because the last ' is unmatched.) – Ørjan Johansen – 2017-12-27T02:36:40.550

5

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

Luis Mendo

Posted 2017-05-30T15:57:37.327

Reputation: 87 464

That's 5 in CJam: l'0f= (if it does what I think it does) – Martin Ender – 2017-05-30T16:17:31.280

@MartinEnder Yes, it's exactly that :-) I've just added an explanation – Luis Mendo – 2017-05-30T16:19:38.087

5

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

CensoredUsername

Posted 2017-05-30T15:57:37.327

Reputation: 951

Always nice to see a solution in Whitespace. Especially when you normally are unable to actually see it. +1 – Josiah Winslow – 2017-09-06T02:05:19.253

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

– Kevin Cruijssen – 2018-04-03T08:59:55.097

Ignore my comment above. For the challenge a tab isn't considered as a printable ASCII character.. – Kevin Cruijssen – 2018-04-03T09:23:15.437

5

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.

Ørjan Johansen

Posted 2017-05-30T15:57:37.327

Reputation: 6 914

pretty sure head can be used in place of (!!1) for an extra byte – Julian Wolf – 2017-05-31T16:21:22.890

No, head is (!!0), not (!!1). It would fail on the character '. – Ørjan Johansen – 2017-05-31T16:48:20.700

Ah, right. I'd just been reading the python answer and forgot that quotes usually needed special treatment. – Julian Wolf – 2017-05-31T16:52:59.150

4

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

Emigna

Posted 2017-05-30T15:57:37.327

Reputation: 50 798

4

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.

xnor

Posted 2017-05-30T15:57:37.327

Reputation: 115 687

I'd suggest changing '?' to a 2 digit charcode, but Python isn't one of those languages where you can do that :( – CalculatorFeline – 2017-05-30T21:21:05.513

Variants saving a byte (but dropping Python 3 compatibility): lambda s:`+(s<'1')`+s[1:] or lambda s:`s<'T'`[0]+s[1:] – Anders Kaseorg – 2017-05-31T00:14:53.440

4

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.

James

Posted 2017-05-30T15:57:37.327

Reputation: 54 537

This breaks if you have a number like 9 alone, where incrementing it adds another character to the string – nmjcman101 – 2017-05-30T19:23:00.693

@nmjcman101 Ah, that's a good point. I've reverted – James – 2017-05-30T19:23:59.303

I like the ROT13 thing though, I didn't know V(im) could do that – nmjcman101 – 2017-05-30T19:24:02.527

4

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!

Dennis

Posted 2017-05-30T15:57:37.327

Reputation: 196 637

1Shorter: *s=159-*s. Always changes the last bit, therefore never gives the same character. Note that 159 = ' ' + '~' – celtschk – 2017-05-31T11:31:08.090

I think you mean 158 = ' ' + '~'. 159-32 = 127, which would be a character out of scope. But good idea. – Computronium – 2017-05-31T13:51:17.437

@celtschk Involutions cannot work, as there's an odd amount (95) of printable chraracters, so at least one of them will map to itself. – Dennis – 2017-05-31T15:43:04.763

@Computronium: Oops, you're right, I got the character code of ~ wrong. – celtschk – 2017-05-31T18:58:32.647

4

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

Ørjan Johansen

Posted 2017-05-30T15:57:37.327

Reputation: 6 914

3

Retina, 10 6 bytes

4 bytes golfed thanks to @Neil

T`p`~p

Try it online!

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

user41805

Posted 2017-05-30T15:57:37.327

Reputation: 16 320

3

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

Stewie Griffin

Posted 2017-05-30T15:57:37.327

Reputation: 43 471

3

Haskell, 30 26 bytes

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

Try it online!

Replaces each char with its predecessor and space with tilde.

nimi

Posted 2017-05-30T15:57:37.327

Reputation: 34 639

3

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.

Martin Ender

Posted 2017-05-30T15:57:37.327

Reputation: 184 808

3

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

Oliver

Posted 2017-05-30T15:57:37.327

Reputation: 7 160

3

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.

ETHproductions

Posted 2017-05-30T15:57:37.327

Reputation: 47 880

3

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

Nitrodon

Posted 2017-05-30T15:57:37.327

Reputation: 9 181

Using t for mod 10 is really clever, nice. :) – Martin Ender – 2017-06-01T12:26:11.657

3

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.

FlipTack

Posted 2017-05-30T15:57:37.327

Reputation: 13 242

2

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

Riley

Posted 2017-05-30T15:57:37.327

Reputation: 11 345

2

PHP<7.1, 31 Bytes

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

Try it online!

Jörg Hülsermann

Posted 2017-05-30T15:57:37.327

Reputation: 13 026

Please remove the 66 byte solution because it's invalid. – CalculatorFeline – 2017-05-30T20:20:26.457

Fails for inputs "1", "10", "101" etc. You can't only depend on the string length. – CalculatorFeline – 2017-05-30T20:26:49.317

@CalculatorFeline "1" outputs "0", "10" outputs "01", "101" outputs "010". Where's the problem? – Christoph – 2017-05-30T20:31:38.870

@CalculatorFeline "1"=>0, "10"=>01, "101"=>010 Where fails it? – Jörg Hülsermann – 2017-05-30T20:31:55.800

for(;a&$c=$argn[$i++];)echo$c^"\1"; btw this has different output but also works. – Christoph – 2017-05-30T20:33:07.277

@Christoph Take this as your own approach and I can upvote it – Jörg Hülsermann – 2017-05-30T20:34:33.077

Oh. I thought you meant "ord" as in position, not charcode. Nevermind '~' – CalculatorFeline – 2017-05-30T20:34:39.387

I'm trying to make an answer without loop. If I fail I might post it :) – Christoph – 2017-05-30T20:37:19.850

I did it 30 bytes.

– Christoph – 2017-05-30T20:42:26.717

@Christoph I have improve you idea – Jörg Hülsermann – 2017-05-30T20:43:05.923

Yeah I saw it sadly it doesn't work for my own approach because "101"^1 would be 100 while "101"^"\1" is "0". – Christoph – 2017-05-30T20:45:04.180

1PHP 7.1 yields A non-numeric value encountered. And You can use ~ instead of a&. – Titus – 2017-05-31T15:56:18.343

@Christoph ^"\1" fails for ~ in the input; ^"1" would fail for N. That´d better be "\2", "\4" or "\8". – Titus – 2017-05-31T15:57:02.163

@Titus I have added the PHP Version must be under 7.1 . Thank You – Jörg Hülsermann – 2017-05-31T16:18:35.543

2

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.

Dennis

Posted 2017-05-30T15:57:37.327

Reputation: 196 637

2

Bash + coreutils, 13

tr \ -~ ~\ -}

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

Try it online.

Digital Trauma

Posted 2017-05-30T15:57:37.327

Reputation: 64 644

2

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.

Christoph

Posted 2017-05-30T15:57:37.327

Reputation: 1 489

Does "~" work?. – CalculatorFeline – 2017-05-30T21:23:57.317

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. – ETHproductions – 2017-05-30T22:52:56.547

Oh. Does !$a or ~$a work? – CalculatorFeline – 2017-05-30T23:13:07.303

@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". – Christoph – 2017-05-31T05:36:41.860

@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. – Christoph – 2017-05-31T05:43:25.520

2

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.

Value Ink

Posted 2017-05-30T15:57:37.327

Reputation: 10 608

2

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"

Fatalize

Posted 2017-05-30T15:57:37.327

Reputation: 32 976

2

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!

Josiah Winslow

Posted 2017-05-30T15:57:37.327

Reputation: 725

2

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!

ATaco

Posted 2017-05-30T15:57:37.327

Reputation: 7 898

2

C/C++, 29 bytes

void m(char*s){(*s%=26)+=65;}

Code to test :

#include <iostream>
#include <string>
#include <cassert>

#ifdef _MSC_VER
#pragma warning(disable:4996)
#endif

void m(char*s){(*s%=26)+=65;}

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

    for (auto&a : test) {
        char* t = new char[a.size() + 1];
        std::strcpy(t, a.c_str());
        m(t);
        assert(a != t);
        std::cout << a << " => " << t << '\n';
        delete[] t;
    }
}

HatsuPointerKun

Posted 2017-05-30T15:57:37.327

Reputation: 1 891

2

brainfuck, 35 27 bytes

Edit: switched to a better way of generating an odd number thanks to the brainfuck constants page

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

Try It Online

Prints out a string of semi-random Vs and Us. If the first character of the input is a V it will print out a U instead and vice versa.

How it Works

,[ Gets first inputted char 
  [[>]+<[-<]>] Converts the ASCII value to binary
  -[>+<---] Adds 85 to the last digit of that binary, which is the original value mod 2. 
            This converts a V (value 86) into a U (value 85) and vice versa
  >. Print the value
,] Get a new value and repeat. 
   Note that the binary of the previous value is still in memory, 
     so it no longer prints specific chars for odd or even values

Another version with the same bytecount:

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

Only changes the first character to a V or a U, but doesn’t handle empty input (which is still valid)

Jo King

Posted 2017-05-30T15:57:37.327

Reputation: 38 234

1Great algorithm--it's tricky to find short algorithms to do things in BF. Don't think the second one works though; shouldn't the last bit be [.,]? – ETHproductions – 2017-12-26T19:50:26.890

2

Brain-Flak, 42 bytes

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

Try it online!

Replaces the first character of the string with a space, or a ! if the first character is already a space.

Jo King

Posted 2017-05-30T15:57:37.327

Reputation: 38 234

2

Perl 6, 14 bytes

{.ord%7~.chop}

Try it online!

Bare block, implicit lambda with input $_. The ordinal of the first character .ord modulo 7 is a different character: Non-numeric first character becomes numeric, numeric first characters map to a different character. If we append the input sans the last character (~ $_.chop), we match the length. It can never match the input because the first character never matches.

Perl 6, 15 bytes

{S/./{.ord%7}/}

Performs S/// substitution (which returns the result of substituting on $_), matching . (any character) once, and replacing it with the ordinal of the first character in $_ - the same character - modulo 7. Non-numeric first character becomes numeric, numeric first characters map to a different character.

Try it online!

Phil H

Posted 2017-05-30T15:57:37.327

Reputation: 1 376

2

str, 2 bytes

XV

Try it online!

Explanation

XV
       over each character:
X         increment it  ("~" becomes "\x7f" and "@" becomes "A")
 V        wrap to printable ascii ("\x7f" becomes " ")

Alternatively, YV to decrement instead of increment.

Conor O'Brien

Posted 2017-05-30T15:57:37.327

Reputation: 36 228

2

R, 40 bytes

function(s)substr(shQuote(s),1,nchar(s))

This uses the shell quoting function shQuote to place appropriate quotes around a string and escape quotes within the string (similar to @xnor's answer). Then take a substring that's as long as the original string (because the string might have multiple escaped characters, we need to take a substring of the correct length, so we can't just use substring(...,3)). sQuote is shorter, but converts to ‘‘’.

Another approach, using more 'core' R stuff is 46 bytes:

function(s)sub(".",letters[grepl("^a",s)+1],s)

Substitute the first character with 'a', unless it is 'a', then substitute it for 'b'. sub only substitutes the first match, so we don't need ^. letters is constant and a slightly shorter way of doing c("a","b"). grepl returns a boolean, and adding 1 converts it to a number that indexes letters. The ^ is needed to correctly convert "ba".

Code to test

x = function(s)substr(shQuote(s),1,nchar(s))

test = function(t){
  t2 = x(t)
  t2!=t & nchar(t)==nchar(t2)
}

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

all(sapply(testStrings,test))

Sean Roberts

Posted 2017-05-30T15:57:37.327

Reputation: 21

Welcome to PPCG! This answer is not, at the moment, valid, because it assumes input is given as a hard-coded variable s. You can either submit this as an anonymous function, function(s)substr(shQuote(s),1,nchar(s)), or take input via scan(,""), readLines() or similar. I've upvoted this to give you enough rep to post in the R golfing chatroom; feel free to ping me there if you have any questions! This is a very well-explained answer :)

– Giuseppe – 2018-04-06T17:26:58.800

@Giuseppe A ha, thanks! I've edited the answer. – Sean Roberts – 2018-04-08T10:40:48.490

2

PowerShell, 37 26 bytes

Thanks Mazzy for -11 bytes

-join($args|% t*y|%{$_%9})

Try it online!

Does alright. Uses the ToCharArray trick to save some bytes. Through a conversion chain, mods the ASCII value of each character by 9 then joins up the value.

Veskah

Posted 2017-05-30T15:57:37.327

Reputation: 3 580

? 6+3*($_-eq6) – mazzy – 2018-12-28T05:52:15.150

1? $_%9 :))))) – mazzy – 2018-12-28T07:52:20.423

1

><>, 11 bytes

i:0(?;'0'=n

Try it online!

Explanation

Like my MATL answer, this transforms character '0' into '1' and all other characters into '0'.

i       Input one char, or push -1 if there aren't any more chars
:       Duplicate
0(      Is it less than 0?
?;      If so, end program. Else:
'0'     Push character '0'
=       Is it equal? Gives 1 or 0
n       Output as a number. Go back to the beginning

Luis Mendo

Posted 2017-05-30T15:57:37.327

Reputation: 87 464

9 bytes if you just print the number modulo 5 – Jo King – 2017-12-27T10:17:16.887

@JoKing Thanks! But U think you should post that as a separate answer – Luis Mendo – 2017-12-29T16:16:28.213

1

JavaScript (ES6), 24 bytes

f=
s=>s.replace(/./,s[0]^1)
<input oninput=o.textContent=f(this.value)><pre id=o>

Changes the first character of the string according to this table:

1   0
2   3
3   2
4   5
5   4
6   7
7   6
8   9
9   8

Everything else becomes 1.

Neil

Posted 2017-05-30T15:57:37.327

Reputation: 95 035

@RickHitchcock As I understand it, only one character needs to be different. – Neil – 2017-05-30T19:50:18.170

@RickHitchcock The very first rule states that the string can be assumed to only contain printable characters... – Neil – 2017-05-30T21:00:01.907

Head-slap, +1!! – Rick Hitchcock – 2017-05-30T21:05:30.657

1

Chip, 5 bytes

g*A~a

Try it online!

Maps all characters to either @ or A, so that the lowest bit always differs from the input:

0, @, ~, etc. map to A
1, a, A, etc. map to @

Phlarx

Posted 2017-05-30T15:57:37.327

Reputation: 1 366

1

x86 Assembly, 19 bytes

Alternates the first character of the string between '@' and 'A'

_diffstr:
  00000000: 8B 54 24 04        mov         edx,dword ptr [esp+4]
  00000004: 8A 02              mov         al,byte ptr [edx]
  00000006: 3C 41              cmp         al,41h
  00000008: 75 04              jne         0000000E
  0000000A: B0 40              mov         al,40h
  0000000C: EB 02              jmp         00000010
  0000000E: B0 41              mov         al,41h
  00000010: 88 02              mov         byte ptr [edx],al
  00000012: C3                 ret

Govind Parmar

Posted 2017-05-30T15:57:37.327

Reputation: 828

1

Perl 5, 49 bytes

sub{$_="a"x length $_[0];$_++while $_ eq$_[0];$_}

Explanation:

  • starts with string of letter "a" as long as input
  • keeps incrementing that until it's different from input

Starting from "a"s was to avoid incrementing to point where Perl lengthens the string; with only one strings to avoid being same as, it couldn't overflow.

This is shamelessly cribbed (and simplified) from my answer to the "related" problem "The Third String".

Execute with:

perl -e '$s = ' -E 'sub{$_="a"x length $_[0];$_++while $_ eq$_[0];$_}' -E ';say $s->("z")'

Ed.

Posted 2017-05-30T15:57:37.327

Reputation: 141

How can it need to increment more than once? – Phil H – 2018-04-04T15:01:12.950

1

><>, 9 3 bytes

5%n

Try it online!

Takes input through the -s flag. Mods each digit with 5 and prints the integer, ending when the stack is empty. This results in only 5 possible output characters, 0-4. Each of those numbers when inputted will produce themselves plus 3, as the ASCII value of 0 is 48, which mod 5 is 3. While the output is reversed, no number is equivalent to another.

Both 7, 9 and a(10) also work as they are not factors of 48 and print single digits.

Jo King

Posted 2017-05-30T15:57:37.327

Reputation: 38 234

1

x86 opcode, 6 bytes

    and     byte [ecx], 0xF1
    inc     byte [ecx]
    ret     

l4m2

Posted 2017-05-30T15:57:37.327

Reputation: 5 985

1

Java 8, 39 38 bytes

s->(s.charAt(0)<49?9:0)+s.substring(1)

Try it online.

Explanation:

If the first character has a unicode value below 49 (space, or one of !"#$%&'()*+'-./0), change it to a '9', else change it to a '0'.

s->                 // Method with String as both parameter and return-type
  (s.charAt(0)<49?  //  If the first character has a unicode value below 49:
    9               //   Change the first character to a '9'
  :                 //  Else
   0)               //   Change the first character to a '0'
  +s.substring(1)   //  And return the rest of the input-String (if any)

Kevin Cruijssen

Posted 2017-05-30T15:57:37.327

Reputation: 67 575

1

Python 3, 29 26 bytes

lambda s:'a~'[s<'~']+s[1:]

Try it online!

  • Replacing first character with ~, if the first character is ~ already, it is replaced by a.

xbarbie

Posted 2017-05-30T15:57:37.327

Reputation: 91

1

Pyth, 9 bytes

*h-+QGhQl

Try it here

Explanation

*h-+QGhQl
   +QG      Stick the alphabet to the end of the input.
  -   hQ    Delete all instances of the first character.
 h          Take the first remaining character.
*       lQ  Multiply by the length of the (implicit) input.

user48543

Posted 2017-05-30T15:57:37.327

Reputation:

1

SmileBASIC, 27 25 bytes

DEF D S
S[0]=@1[S>"2"]END

Creates a function named D that is called like:

STRING$="abcde"
D STRING$
'STRING$ is now "1bcde"

The first character is replaced with either @ or 1

12Me21

Posted 2017-05-30T15:57:37.327

Reputation: 6 110

1

Quantum64

Posted 2017-05-30T15:57:37.327

Reputation: 371

1

C (gcc), 22 bytes

f(char*s){*s=~1&*s^2;}

Try it online!

MegaTom

Posted 2017-05-30T15:57:37.327

Reputation: 3 787

0

Perl 6,  48  28 bytes

{(->{[~] (' '..'~').roll(.chars)}...*ne$_).tail}

Generates a sequence of random strings, stopping when one of them doesn't match the input. Returns the last string produced

Test it

{first *ne$_,(0,1 Xx.chars)}

Generates two strings one consisting of only 0s, the other of 1s. Returns the first that is not stringwise equal to (ne) the input ($_).

Test it

Expanded

{             # bare block lambda with implicit parameter 「$_」

  first       # return the first value where the following is true

    * ne $_,  # WhateverCode lambda ( 「*」 is the parameter )

    (
      0, 1    # list of 0 and 1
      X[x]    # cross 「X」 that using the string repetition operator 「x」
      .chars  # with the number of characters in 「$_」
    )
}

Brad Gilbert b2gills

Posted 2017-05-30T15:57:37.327

Reputation: 12 713

0

Convex, 4 bytes

'0f=

Try it online!

GamrCorps

Posted 2017-05-30T15:57:37.327

Reputation: 7 058

This appears to fail (on TIO, at least) if the input is purely numeric: RuntimeException: Long Character f= not implemented – brhfl – 2017-12-26T21:53:36.567

0

Aceto, 16 12 9 bytes

=01`
,'pO

Run with -F to see immediate output (but works without).

Explanation:

We read a character, then push the character 0 on the stack and test for equality:

=0
,'

If equal, we push a 1.

  1`

We now print the top element (either a one or an implicit zero), and go back to the start:

  pO

This prints zeroes for any characters that aren't zeroes, and ones for zeroes, e.g.:

Input  |  Output
----------------
abcde  |  00000
11111  |  00000
10010  |  01101

L3viathan

Posted 2017-05-30T15:57:37.327

Reputation: 3 151

0

Charcoal, 8 bytes

FSIX⁰⁼ι1

Try it online! Link is to verbose version of code. Works by comparing each character to 1, then taking the result as the exponent of zero, then converting to string. This results in an output 0 for each 1 in the input and a 1 for each other character. Edit: Changes in Charcoal now mean that I can directly cast the result of Equals saving 2 bytes: FSI⁼ι0 Try it online! Link is to verbose version of code. Edit: Actually there was a 6-byte solution all along: FS§α℅ι Try it online! Link is to verbose version of code. Port of @FlipTack's Pushy answer. (Also works with lower case of course.)

Neil

Posted 2017-05-30T15:57:37.327

Reputation: 95 035

0

Braingolf, 12 bytes

.#~e1-:1+|&@

Subtracts 1 from the last char's ordinal if it is a tilde, otherwise adds one.

Explanation:

.#~e1-:1+|&@  Implicit input of string, convert each char to ordinal and push to stack
.             Duplicate last item
 #~           Push tilde ordinal
   e          If last 2 items are equal (consumes last 2 items)
    1-        ..then subtract one
      :       else
       1+     ..add one
         |    endif
          &@  Print entire stack as chars

Skidsdev

Posted 2017-05-30T15:57:37.327

Reputation: 9 656

0

C#, 46 bytes

_=>(char)(_[0]>32?_[0]-1:_[0]+1)+_.Remove(0,1)

Changes first letter to next to previous letter on ASCII table unless it is the first letter, in which case it takes the next one.

LiefdeWen

Posted 2017-05-30T15:57:37.327

Reputation: 3 381

0

SAS, 34

substr(s,1,1)=ifc(s=:'z','a','z');

If the first character of the string s is z, change it to a, otherwise change it to z. Rubbish compared to the proper golfing languages, but at least it beats C#!

user3490

Posted 2017-05-30T15:57:37.327

Reputation: 809

0

T-SQL, 45 bytes

SELECT STUFF(S,1,1,CHAR(ASCII(S)%7+48))FROM t

Takes input from pre-existing table t with VARCHAR field S, per our IO standards.

Modifies the first character by taking the remainder MOD 7 of the ASCII value, then converting that back into a digit between 0 and 6. But ASCII(0)=48, which is 6 MOD 7, so the first character never maps back onto itself.

BradC

Posted 2017-05-30T15:57:37.327

Reputation: 6 099

0

Cubically, 23 bytes

(~-61/1=7&6:7>4?6@4!@5)

Converts the string into $s and -s.

TehPers

Posted 2017-05-30T15:57:37.327

Reputation: 899

0

Implicit, 15 14 bytes

'_._` !{+32}*-

Found about 10 interpreter bugs writing this. Try it online!

'_._` !{+32}*-
'                « read string                              »;
 _               « push last char onto stack                »;
  .              « increment                                »;
   _`            « mod by 127 (the "` " evaluates to 127)   »;
      !{...}     « if falsy (char was ~)                    »;
        +32      «  add 32 (make it a space)                »;
            *    « stick char at beginning of string        »;
             -   « pop last char off string                 »;

MD XF

Posted 2017-05-30T15:57:37.327

Reputation: 11 605

0

BrainFuck, 49 47 Bytes

,>++++[-<-------->]++[<]++++[->++++++++<]>-[.,]
x           0   (x-32) 2                (x-32||2)+31
^           ^(x>32) ^(x==32)

Assuming EOF as zero

l4m2

Posted 2017-05-30T15:57:37.327

Reputation: 5 985

You can cut out the first set of ., and just go straight into the loop – Jo King – 2017-12-26T15:54:42.317

Thanks – l4m2 – 2017-12-27T00:26:05.217

0

Perl 5, 23 + 1 (-p) = 24 bytes

s/./chr 65+ord($&)%26/e

Try it online!

Blatantly steals @FlipTack's method to change the first character to a different upper case letter.

Xcali

Posted 2017-05-30T15:57:37.327

Reputation: 7 671

You can drop one of the digits in 26, at least. – Ørjan Johansen – 2018-01-11T00:51:03.700

0

Julia 0.6, 26 bytes

s->map(x->x<'b'?'b':'a',s)

Try it online!

gggg

Posted 2017-05-30T15:57:37.327

Reputation: 1 715

0

Swift 3, 76 68 bytes

let s=readLine()!;print(s.characters.map{$0=="a" ?"b":"a"}.joined())

Try it online!

Tamás Sengel

Posted 2017-05-30T15:57:37.327

Reputation: 211

0

Fortran (GFortran), 77 bytes

CHARACTER(256)A
READ*,A
A(1:1)=CHAR(MOD(IACHAR(A(1:1))+1,94)+33)
PRINT*,A
END

Try it online!

It does what was required... well, with some issues...

1) If the first character is "or <space>, they will be ignored;

2) If there is /, it will be understood as something like "end of transmission";

3) There will be a leading space (which is not part of the output (so do I think), because Fortran always prints a leading space if the output is not formated) and up to 255 trailing spaces. This last problem (i.e., the trailing spaces) can be solved using no more then six bytes.

rafa11111

Posted 2017-05-30T15:57:37.327

Reputation: 310

0

SNOBOL4 (CSNOBOL4), 71 bytes

	INPUT LEN(1) . X REM . S
	X =IDENT(X) 1	:S(O)
	X =0
O	OUTPUT =X S
END	

Try it online!

Replaces the first character of S with a 0 unless it's already, 0 in which case it swaps it with 1.

Giuseppe

Posted 2017-05-30T15:57:37.327

Reputation: 21 077

0

Pyth, 12 bytes

+C+%ChQlG32t

Test suite

Python 3 translation:
Q=eval(input())
print(chr(ord(Q[0])%26+32)+Q[1:])

hakr14

Posted 2017-05-30T15:57:37.327

Reputation: 1 295

0

Gol><>, 6 bytes

iE;5%n

Try it online!

Direct translation of Jo King's ><> answer.

Bubbler

Posted 2017-05-30T15:57:37.327

Reputation: 16 616

0

Tcl, 56 bytes

proc C s {join [lmap x [split $s ""] {expr {$x==0}}] ""}

Try it online!

Approach very similar to last one: replaces every non-zero by a zero and every zero by one.


Tcl, 62 bytes

proc C s {puts [expr {[string in $s 0]==0}][string ra $s 1 e]}

Try it online!

Approach replaces first character by 1 if it is a 0, else it replaces anything else by a 0.

Tcl, 83 bytes

proc C s {scan [string in $s 0] %c f
puts "[format %c [incr f]][string ra $s 1 e]"}

Try it online!

sergiol

Posted 2017-05-30T15:57:37.327

Reputation: 3 055