24
\$\begingroup\$

Inspired by this accidental misspelling

If you could read the title, then you already know what the challenge is about. If not, then I'll tell you. Easy: simply take each word (single space delimited), and swap the positions of the first two letters. You may assume that the input will contain only lowercase ASCII letters and spaces and that there will be no one-letter words. You many optionally take a list of words instead of a sentence.

Testcases

hello world -> ehllo owrld
this is an easy challenge -> htis si na aesy hcallenge
reverse the first two letters of each word -> erverse hte ifrst wto eltters fo aech owrd
pptx is one of ooxml format -> pptx si noe fo ooxml ofrmat
(empty) -> (empty)

Leaderboard

/* Configuration */

var QUESTION_ID = 249523; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 107299; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery('<a>'+lang+'</a>').text();
    
    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/all.css?v=ffb5d0584c5f">
<div id="language-list">
  <h2>Shortest Solution by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
8
  • 3
    \$\begingroup\$ Can we assume there are no consecutive spaces, and/or that the string does not start or end with a space? (i.e. there are no "zero-length words") \$\endgroup\$
    – pxeger
    Jul 4 at 15:39
  • 10
    \$\begingroup\$ If the input is just single-space-separated words, why not simply allow a list of words? And if so, why require list processing and not just give a single word as input? \$\endgroup\$
    – Adám
    Jul 4 at 15:40
  • 1
    \$\begingroup\$ Very related. \$\endgroup\$
    – Steffan
    Jul 4 at 16:04
  • \$\begingroup\$ @Adám I’ll do the word list but tbh I wasn’t planning to add any fluff to this challenge, it’s just the way I thought of it. Besides, I’m not gonna change the specs with 15 answers already lol \$\endgroup\$
    – Seggan
    Jul 4 at 18:36
  • \$\begingroup\$ @pxeger yes. You may \$\endgroup\$
    – Seggan
    Jul 4 at 18:38

52 Answers 52

16
\$\begingroup\$

x86-64 machine code, 12 bytes

B0 20 66 C1 07 08 AE 72 FD 74 F7 C3

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the address of the input, as a null-terminated byte string, in RDI, and modifies the string in place.

In assembly:

f:
    mov al, ' '     # Set AL to the ASCII code of the space.
nextword:
    rol WORD PTR [rdi], 8   # Rotate 2 bytes at the address RDI left by 8 bits.
                            # This swaps the current and next characters.
nextletter:
    scasb           # Compare AL with the current character, advancing the pointer.
    jb nextletter   # Jump back if AL is less than the character read.
    je nextword     # Jump back further if AL is equal to the character read.
    ret             # Return (if AL is greater than the character read).
\$\endgroup\$
8
\$\begingroup\$

05AB1E, 7 6 5 4 bytes

εΣN≠

-1 byte thanks to @CommandMaster

Try it online.

Explanation:

ε     # Map over each word of the (implicit) input-list:
 Σ    #  (Stable) sort its characters by:
  N   #   Where the 0-based index
   ≠  #   Is not 1
      # (after which the list of modified words is output implicitly)

The N≠ will make the 0-based indices of the characters in each word [1,0,1,1,1,...], basically putting the second character at the front.

\$\endgroup\$
4
  • \$\begingroup\$ alternative 6 bytes: εR`sJR, and εΣNNiÍ \$\endgroup\$ Jul 5 at 4:54
  • 1
    \$\begingroup\$ 5 bytes: εΣN<Ä or equivalently εΣN1α \$\endgroup\$ Jul 5 at 4:59
  • 1
    \$\begingroup\$ alternative 5 bytes: εć.ιJ \$\endgroup\$ Jul 5 at 5:49
  • \$\begingroup\$ @CommandMaster Thanks for the 5-byters. And the sort-by approach actually opened up another save with εΣN≠. :) \$\endgroup\$ Jul 5 at 6:32
8
\$\begingroup\$

Brainfuck, 30 bytes

Thanks to tsh for -4 bytes.

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

Explanation:

,[                loop every word
  >,.             print second character of word
  <[              loop through next letters of word including first one
    .             print next letter
    [-<++++++++>] multiply the letter by 8 (8*32=256; 256%256=0)
    <[            check if the result is zero
      ,>          if not then load next letter
    ]<
  ]
,]

Characters @ and ` can also be used as word separators as 8*64=512; 512%256=0 and 8*96=768; 768%256=0.

Attempt This Online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Is ,[>,.<.,[.[-<++++++++>]<[,>]<],] works? \$\endgroup\$
    – tsh
    Jul 5 at 6:43
  • \$\begingroup\$ Thank you, it works. I think it might cause issues after 15k words, but that can probably be ignored. \$\endgroup\$
    – Jiří
    Jul 5 at 13:03
8
\$\begingroup\$

V (vim), 4 bytes

òxpW

Try it online!

Explanation:

ò       # Recursively...
 x      #   Delete one letter
  p     #   Paste the last deleted letter
   W    #   Move forward one word
\$\endgroup\$
7
\$\begingroup\$

Jelly, 4 bytes

żḢF)

A monadic Link that takes, as allowed in the comments, a list of words and yields a list of words.

Try it online!

How?

żḢF) - Link: list of lists of characters, words  e.g. [..., "upend", ...]
   ) - for each word:                                       
 Ḣ   -   head (word) -> remove and get the first character  "u"
ż    -   (beheaded word) zip with (head character)          ["pu","e","n","d"]
  F  -   flatten that back into to a list of characters     "puend"

Also requires no empty words, also allowed in the comments (as would yield a zero).

Note: I would say that the F is necessary since without this flatten a callable link would return each new word as a list of lists of characters while as a full program it would smash the characters together when it prints.

\$\endgroup\$
6
\$\begingroup\$

JavaScript (ES6), 33 bytes

s=>s.replace(/\b(\S)(.)/g,'$2$1')

Try it online!

\$\endgroup\$
6
\$\begingroup\$

Brachylog, 9 8 bytes

{pᶠkt↔}ᵐ

Try it online!

An extremely stupid solution but shorter than my initial, more straightforward idea.

-1 byte thanks to @UnrelatedString with an event stupider idea

Explanation

{     }ᵐ    Map for each word:
 pᶠ           Find all permutations of the word
   kt         Get the penultimate one
     ↔        Reverse it

This works because p will always try permutations in the same order, and it happens that the penultimate one is the input in reverse order, with the last two characters swapped. It also works for 2 letter words because the penultimate permutation here will be the first one, i.e. the identity, and reversing it is the same as swapping the two characters.

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

Vyxal, 9 8 5 4 bytes

- x bytes thanks to @Steffan

ƛḣ$Y

Try it Online! | S Flag to join by spaces

Explanation

ƛḣ$Y
ƛ     Map through each word
 ḣ    Push all but the first letter and the first letter
  $   Swap the first two elements
   Y  Interleave
\$\endgroup\$
5
  • \$\begingroup\$ @Steffan ah nice \$\endgroup\$
    – mathcat
    Jul 4 at 18:46
  • \$\begingroup\$ @Steffan but you still have to output a string? \$\endgroup\$
    – mathcat
    Jul 4 at 19:09
  • 1
    \$\begingroup\$ @Steffan shh hopefully nobody'll notice \$\endgroup\$
    – mathcat
    Jul 4 at 19:20
  • \$\begingroup\$ @Steffan oh wow \$\endgroup\$
    – mathcat
    Jul 18 at 11:55
  • \$\begingroup\$ @Steffan the heck I give up \$\endgroup\$
    – mathcat
    Jul 19 at 11:19
5
\$\begingroup\$

Zsh --extendedglob, 29 bytes

<<<${@/(#m)??/`rev<<<$MATCH`}

Attempt This Online!

Zsh's pattern matching is pretty limited.

-1 byte thanks to @GammaFunction.

\$\endgroup\$
0
5
\$\begingroup\$

R, 28 bytes

\(x)sub("(.)(.)","\\2\\1",x)

Attempt This Online!

Simple regex-breast, errr..., I mean... regex-based solution.

Takes input as a vector of words - this works nicely as sub is vectorised over the 3rd argument.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ And gsub nicely handles multiple matches so you could take \(x)gsub('( |^)(.)(.)','\\1\\3\\2',x,F,T) to the space-delimited string input. \$\endgroup\$
    – Cong Chen
    Jul 5 at 0:32
  • 1
    \$\begingroup\$ @CongChen you're right, but it's code-golf and it's shorter that way ;-) (Also \(x)gsub('\\b(\\S)(.)','\\2\\1',x,,T) would be shorter for the whole sentence input) \$\endgroup\$
    – pajonk
    Jul 5 at 5:41
5
\$\begingroup\$

Python 3, 35 bytes

Thanks to steffan for -34 bytes.

lambda a:[x[1::-1]+x[2:]for x in a]

Try it out

p.s. This is my first serious attempt at Code Golf all feedback is appreciated!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome to Code Golf! Nice first answer. You've already golfed things great, but you can remove a bit of whitespace, remove the list(...), and use a list comprehension (and save 2 more bytes with a generator comprehension) for 55. Or with input and output as a list of words, 35. :) \$\endgroup\$
    – Steffan
    Jul 5 at 20:09
  • \$\begingroup\$ Thanks @Steffan I've been a lurker here for over a year now lol I've always seen you around in the comments. Thanks for the great work and helping out! \$\endgroup\$ Jul 5 at 20:24
5
\$\begingroup\$

Piet + ascii-piet, 28 25 bytes (13×2=26 codels)

tU?QjCuJsNrMbQvQsQjIJjMmm

Try Piet online!

Diagram

−3 by switching to a vertical layout, allowing two white codels to be removed and one black codel to be implicit.

The program starts with in(char), in(char), out(char), out(char), taking the first two letters from the input and outputting them in reversed order.

After that, it enters a loop:

  • in(char), duplicate, out(char): Read the next character from the input, and output it while leaving a copy on the stack.
  • push[3], duplicate, multiply, duplicate, multiply, push[1], add: Create the value 82 on the stack.
  • divide: Divide the character code by 82. This produces 1 for lowercase letters (97–122) and 0 for a space (32).
  • pointer: Rotate the Direction Pointer clockwise by the value on the stack.
    • For lowercase letters, this sends execution rightwards and executes subtract, out(char), which does nothing with the stack empty, before repeating the loop.
    • For spaces, execution continues upwards into the white area and returns to the start of the program to process the next word.
    • When the end of the input is reached, in(char), duplicate, out(char) does nothing and leaves the stack empty. The calculation of 82 still works, but then the divide does nothing because there is only one value on the stack, and the pointer rotates the Direction Pointer by 82, which is congruent to 2 modulo 4, sending it downwards. None of the reversed instructions are pushes, so they all do nothing (because the stack is empty), and execution reaches the halting structure at the bottom.
\$\endgroup\$
4
\$\begingroup\$

QuadR, 18 14 9 bytes

\b\w.
⌽⍵M

Try it online!

PCRE Replace:

\b a word boundary

\w any word character, and then

. any character

with:

⌽⍵M the reversed Match

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

Perl 5 + -p040, 13 bytes

Uses -040 to work on each space separated section so that the replacement can be one off avoiding the need for /g, which makes it possible to use the implicit ; from -p as the terminating separator.

s;(.)(.);$2$1

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ There's a tip for abusing the {} created by -p... but not for ;; maybe there should be? \$\endgroup\$
    – Neil
    Jul 7 at 6:30
  • \$\begingroup\$ @Neil Huh. I could've sworn I learned about that from the tips! I'll add something, thanks for the heads up \$\endgroup\$ Jul 7 at 8:47
3
\$\begingroup\$

Python, 48 bytes

Thanks to user Kalobi for -3 bytes and pxeger for another -3 bytes.

print(*(i[1::-1]+i[2:]for i in input().split()))

Attempt This Online!

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

APL (dzaima/APL), 6 bytes

OP seems to have allowed input as a list, so here goes…

⌽@1 2¨

Try it online!

 reverse

@ at indices

1 2 one and two

¨ for each word

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

Retina, 7 bytes

V`\b\w.

Try it online! Link includes test cases. Explanation: A simple use of Retina's reVerse command on the first two letters of each word.

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

Jelly, 10 7 6 bytes

U2œ?U)

Attempt This Online!

-3 bytes by doing I/O as a list rather than a space-separated string, now that the OP has allowed that.

-1 thanks to @Unrelated String

Explanation:

Given a word \$ a_n \cdots a_3 a_2 a_1 \$, the permutation \$ a_n \cdots a_3 a_1 a_2 \$ is at index 2 in the list of permutations of that word.

     )       map over each word:
U            reverse
 2œ?         index 2 into all permutations of the reversed input
    U        (un-)reverse
\$\endgroup\$
1
3
\$\begingroup\$

Ruby, 28 bytes

->s{s.map{|w|(w.slice!1)+w}}

Try it online!

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

Java (OpenJDK 8), 38 37 bytes

s->s.replaceAll("\\b(\\S)(.)","$2$1")

Try it online!

-1 thanks to @KevinCruijssen

Couldn't come up with a less boring version. The shortest other idea I had was just swapping i+1 and i+2 in an array where index i is a space, but just toCharArray() is 13 chars :(

\$\endgroup\$
3
  • 1
    \$\begingroup\$ You can remove the space for -1 byte. \$\endgroup\$ Jul 5 at 14:32
  • \$\begingroup\$ Also I think the rules allow for taking a char[][] instead of a String[] if needed \$\endgroup\$
    – Seggan
    Jul 5 at 14:41
  • \$\begingroup\$ @KevinCruijssen lol, I'm an idiot! Thanks! \$\endgroup\$
    – JollyJoker
    Jul 5 at 14:49
3
\$\begingroup\$

Nibbles, 5 bytes (10 nibbles)

:\<2@>2@
           # implicit map over input:
:          # append
 \         # the reverse of
  <2@      # take first 2 characters of each arg
           # onto
     >2@   # drop first 2 characters from each arg

screenshot

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

sed -r, 17 bytes

s/\<(.)(.)/\2\1/g

Try it online!

Uses the rare 'start of word' marker \<.

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

BQN, 10 8 bytes

Edit: -2 bytes thanks to DLosc

⌽⌾(2⊸↑)¨

Try it at BQN REPL

         ¨   # for each element of input
⌽            # reverse
 ⌾           # under
  (2⊸↑)      # take first 2 elements

The BQN 'under' modifier applies a function (here, take first 2 elements) and then applies another function on the result (here, reverse), and finally undoes the first function (so, it 'undoes' taking elements 1&2, thereby putting the result back into these positions).
Think 'operating under anaesthetic', where the anaesthetic is done before the operation and undone afterwards.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Because Under is pure magic, it also works with Take: 8 bytes \$\endgroup\$
    – DLosc
    Jul 6 at 22:51
  • \$\begingroup\$ @DLosc - wonderful, thanks! \$\endgroup\$ Jul 7 at 5:27
3
\$\begingroup\$

Java (JDK), 36 bytes

l->l.peek(s->s[0]^=s[1]^(s[1]=s[0]))

Try it online!

  • Takes input as Stream<char[]>, and returns another Stream<char[]>, with each char[] being a word.
\$\endgroup\$
3
\$\begingroup\$

K (ngn/k), 11 bytes

{x@>1=!#x}'

Try it online!

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

Jelly, 8 bytes

Ḳµḣ2Uo)K

Try it online!

How it works

Ḳµḣ2Uo)K - Main link. Takes a string
Ḳ        - Split by spaces
 µ    )  - Over each word:
  ḣ2     -   Take the first two characters
    U    -   Reverse them
     o   -   Logical Or, overwriting the first two characters of the word
       K - Join with spaces
\$\endgroup\$
1
  • \$\begingroup\$ Now that I/O can be lists, it's 5 bytes ḣ2Uo) (or something like that) \$\endgroup\$
    – Steffan
    Jul 4 at 19:39
2
\$\begingroup\$

Python 3, 51 bytes

lambda s:' '.join(w[1::-1]+w[2:]for w in s.split())

Try it online!

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

APL+WIN, 26 bytes

Prompts for sentence

(⌽¨2↑¨s),¨2↓¨s←(s≠' ')⊂s←⎕

Try it online! Thanks to Dyalog Classic

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

Prolog (SWI), 34 bytes

[[X,Y|R]|A]^[[Y,X|R]|O]:-A^O.
A^A.

Try it online!

-6 bytes thanks to Jo King

I/O as list of list of codepoints.

\$\endgroup\$
1
  • \$\begingroup\$ g can be replaced with + like so. Actually, you can avoid maplist and the second function altogether for 34 bytes \$\endgroup\$
    – Jo King
    Jul 7 at 1:05
2
\$\begingroup\$

Desmos, 90 bytes

k=l.length
i=\{k=0:[],[1...k]\}
L=join(32,l)
f(l)=\{L[i-1]=32:L[i],L[i]=32:L[i+2],L[i+1]\}

Takes in space separated words as a list of codepoints, and returns another list of codepoints.

Probably a terrible way of doing this but whatever.

Here's a Python program that takes in a string as input and outputs a list of codepoints that Desmos can read. (e.g.: hello world -> o\to f\left(\left[104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100\right]\right))

Here's a Python program that takes in the outputted list of codepoints from Desmos and converts it into a string. (e.g.: \left[104,116,105,115,32,115,105,32,110,97,32,97,101,115,121,32,104,99,97,108,108,101,110,103,101\right] -> htis si na aesy hcallenge)

Try It On Desmos!

Try It On Desmos! - Prettified

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