28
\$\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\$
10
  • 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, 2022 at 15:39
  • 11
    \$\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, 2022 at 15:40
  • 1
    \$\begingroup\$ Very related. \$\endgroup\$
    – naffetS
    Jul 4, 2022 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, 2022 at 18:36
  • \$\begingroup\$ @pxeger yes. You may \$\endgroup\$
    – Seggan
    Jul 4, 2022 at 18:38

61 Answers 61

2
\$\begingroup\$

C (gcc), 55 bytes

f(char*s){for(;s-1;s=index(s,32)+1)*s^=s[1]^(s[1]=*s);}

Try it online!

Inputs a pointer to a string.
Performs the reversing in place.

\$\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, 2022 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\$
2
\$\begingroup\$

Python 3, 73 bytes

f=lambda s:' '.join([''.join(list(i[:2])[::-1])+i[2:]for i in s.split()])

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ 51 bytes (although there is already a 48 byte answer) \$\endgroup\$
    – naffetS
    Jul 4, 2022 at 17:26
  • \$\begingroup\$ There's already two other Python answers. I did this to see how far I could get without starting from another answer. \$\endgroup\$ Jul 5, 2022 at 22:32
2
\$\begingroup\$

GolfScript, 17 bytes

' '/{2/(-1%\' '}/

Try it online!

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

Chocolate \$\ge\$ commit 8b0b99b, 5 bytes

γỴD_Ḣ

Try it online!

Previously:

Chocolate, 8 bytes

γC⅃:2_DD

Try it online!

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

Python 3, 44 bytes

lambda s:[x[1]+x[0]+x[2:]for x in s.split()]

Try it online!

Outputs as a list of words.

\$\endgroup\$
2
  • \$\begingroup\$ You may take input as a list of words instead, reducing it to 36 bytes. \$\endgroup\$ Nov 23, 2023 at 17:11
  • \$\begingroup\$ 43 \$\endgroup\$
    – l4m2
    Nov 24, 2023 at 0:34
2
\$\begingroup\$

Japt, 5 bytes

I/O as an array of words.

ËÅíDÎ

Try it

ËÅíDÎ     :Implicit input of array
Ë         :Map each D
 Å        :  Slice off the first character
  í       :  Interleave with
   DÎ     :    First character of D

6 bytes

Ëò vÔ¬

Try it

Ëò vÔ¬     :Implicit input of array
Ë          :Map
 ò         :  Partitions of length 2
   v       :  Modify first element
    Ô      :    Reverse
     ¬     :  Join
\$\endgroup\$
2
\$\begingroup\$

CJam, 16 bytes

{1Se[2/(W%\+}%S*

Try it online!

A function which takes an array of strings as input. Link includes test cases.

Explanation

{1Se[2/(W%\+}%S* # whole function which takes an array of inputs
{           }%   # for each value in the input
   e[            # pad to length
 1               # `1` using
  S              # `S`paces
     2/          # split into chunks of length `2`
       (         # get the first split chunk
        W%       # map by `W` (shorthand for -1), reversing
          \+     # swap to the beginning of the stack and add to the rest of the array
              S* # join this array by `S`paces
\$\endgroup\$
1
\$\begingroup\$

Lexurgy, 23 bytes

a:
[]$1 []$2=>$2 $1/$ _

Performs metathesis on the first 2 characters of each whitespace-delimited series of characters.

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

sed, 23 bytes

s/(^| +)(.)(.)/\1\3\2/g

Can be shortened if one assumes that there are no consecutive spaces, or that the input starts with a space.

Attempt This Online!

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

Rust, 164 bytes

|t:String|t.split(" ").filter(|i|i.len()>0).map(|i|{let k=i.chars().collect::<Vec<_>>();[&k[1..2],&k[0..1],&k[2..],&[' ']].concat()}).flatten().collect::<String>();

Strings will have a extra space at the end.

Attempt This Online!

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

Factor, 51 29 bytes

[ [ 0 1 pick exchange ] map ]

Try it online!

-22 bytes from OP allowing lists after I answered.

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

Java, 148 bytes

class H {public static void main(String[]a){String l="";for(String s:a[0].split(" ")){l+=s.charAt(1);l+=s.charAt(0);l+=s.substring(2)+" ";}a[0]=l;}}
\$\endgroup\$
4
  • 1
    \$\begingroup\$ You can apply quite a bit of golfing here: you don’t need public on the class, you can use the args list instead of hard coding the input, the args variable name can be just “a”. Be sure to check out the Java tips page \$\endgroup\$
    – Seggan
    Jul 4, 2022 at 19:05
  • \$\begingroup\$ @Seggan thank you for the tips \$\endgroup\$
    – isaace
    Jul 4, 2022 at 19:13
  • \$\begingroup\$ Do you need a class? I thought a method was legal. a=> ... \$\endgroup\$
    – JollyJoker
    Jul 5, 2022 at 12:56
  • 1
    \$\begingroup\$ @JollyJoker (That is a lambda expression.) Methods, lambdas, and full programs are allowed. \$\endgroup\$ Jul 6, 2022 at 20:01
1
\$\begingroup\$

Charcoal, 17 bytes

⪫E⪪S ⭆ι⎇‹μ²§ι¬μλ 

Try it online! Link is to verbose version of code. Explanation:

   S                Input string
  ⪪                 Split on spaces
 E                  Map over words
      ι             Current word
     ⭆              Map over letters and join
         μ          Current index
        ‹           Is less than
          ²         Literal integer `2`
       ⎇            If true then
            ι       Current word
           §        Indexed by
              μ     Current index
             ¬      Logical Not (i.e 1 - index)
               λ    Else current letter
⪫                   Join with spaces
                    Implicitly print

Note: A trailing newline is needed in the input field otherwise Charcoal thinks you're supplying multiple inputs.

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

Burlesque, 15 bytes

{2coq<-0ap++}ww

Try it online!

Unfortunately

 q<-"\b.."~a

Doesn't work as expected

{
 2co # Chunks of 2
 q<- # Quoted reverse
 0ap # Apply to first block
 ++  # Concat
}ww  # Apply to each word
\$\endgroup\$
1
\$\begingroup\$

Ly, 18 19 bytes

irf[' =fo[pfoo0]p] 

Try it online!

This relies on the fact that each word will have at least two characters, which is noted in the description. It also assumes the input will not start or end with a space, and that there won't be multiple spaces in a row. That assumption is currently an open question. If that doesn't turn out to be OK, this approach won't work.

ir                 - read input as codepoints, reverse stack
  f                - reverse first two chars
   [             ] - for each char/codepoint on the stack...
    ' =            - is the current char a space?
       fo          - pull char forward and print
         [p   0]p  - if/then
           foo     - flip the top two chars and print them
\$\endgroup\$
1
\$\begingroup\$

Pyth, 6 bytes

+L.(d1

Try it online!

Accepts a list of lists of characters ("words"), and returns a list of lists of characters.

+L.(d1
 L      Left map over the input:
  .(d1  Pop and return the second letter of each word
+       Append the popped letter to the remaining letters

If a list of strings is required as input/output:

Pyth, 7 bytes

m.itdhd

Try it online!

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

SM83, 19 bytes

Input pointer in hl, output pointer in de.

46 23 2A 12 13 78 12 13
2A 12 13 B7 C8 FE 20 20
F7 18 ED
f:
    ld b,[hl]       // 46       // y = *in
    inc hl          // 23       // in++
    ld a,[hl+]      // 2A       // x = *(in++)
    ld [de],a       // 12       // *out = x
    inc de          // 13       // out++
    ld a,b          // 78       // x = y
    ld [de],a       // 12       // *out = x
    inc de          // 13       // out++
l:
    ld a,[hl+]      // 2A       // x = *(in++)
    ld [de],a       // 12       // *out = x
    inc de          // 13       // out++
    or a            // B7       // is x NUL?
    ret z           // C8       // Y: return
    cp ' '          // FE 20    // is x SPACE?
    jr nz,l         // 28 F7    // N: continue copying
    jr f            // 18 ED    // Y: start all over
\$\endgroup\$
1
\$\begingroup\$

Stacked, 14 bytes

[[0 1 exch]"!]

Try it online!

Alternatively, 0 1 can be 0:#+, but it's the same byte count.

Explanation

Uses the classic golf map"! (each execute).

[[0 1 exch]"!]
[            ]    anonymous lambda
 [        ]"!     execute this code on each cell
  0 1 exch        exchange indices 0 and 1
\$\endgroup\$
1
\$\begingroup\$

Lua, 39 bytes

return(...):gsub("%f[%w](.)(.)","%2%1")

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Not every day you see Lua around here. Nice one! \$\endgroup\$
    – Seggan
    Jul 6, 2022 at 21:54
1
\$\begingroup\$

Pip -p, 10 bytes

gR`^..`RV_

Inputs an array as multiple command-line arguments; outputs an array in Pip array syntax. Try It Online!

Explanation

gR`^..`RV_
g           In array of command-line args,
 R          replace
  `   `     all matches of this regex:
   ^         Beginning of string
    ..       followed by two characters
       RV_  with the reverse of the match

An interesting alternate 10-byter can be achieved by porting math junkie's Pyth answer:

{aPK1}._Mg
        Mg  To each command-line arg, map this function:
{aPK1}       Pick the character at index 1 out of the string
      ._     and concatenate it to the rest of the string

Try It Online!

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

GolfScript, 23 bytes

' '/{(\(@[\\]\+}[/]' '*

Try it online!

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

str, 16 bytes

gg~:o;d' =?ogg~:

Try it online!

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

><>, 10 bytes

r$:o84*)0.

Try it online!

Explanation

r           # reverse stack to get input in correct order
 $          # swap the top 2 letters of the stack
  :o        # print a copy of the letter
    84*)0.  # jump to coordinates x=previousLetterCharCode>32, y=0
\$\endgroup\$
1
\$\begingroup\$

Arturo, 34 bytes

$[a][map a'w[t:w\0w\0:w\1w\1:t w]]

Try it

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

morsecco:  110  100 bytes

.    . - ..- - -- - . - .-. - - .-.. --.. --. - .- .   -. - .  -.-.  - . -.-. . -.-. .. --. - .- ---

Saved some bytes by combining three -.-. operations. Explanation:

  • . . - ..- - to Enter an empty cell and Use stdin for Token reading
  • -- - . - .-. to Mark the beginning of the loop and Read next word
  • - - .-.. --.. --. to test the Length of the token to Zeroskip the loop
  • - .- - .- . -. - . drops the length and prepares the C sequence: Cut the first two letters, than Cut the first and Concatenate both in reverse order
  • -.-. - . -.-. . execute that sequence, and Concatenate the swapped word parts
  • -.-. .. --. Concatenates to the previous word and Goes to the mark
  • - .- --- after jumping out of the loop, Output the line
\$\endgroup\$
1
\$\begingroup\$

TypeScript’s type system, 90 bytes

type X<L>=L extends[`${infer A}${infer B}${infer C}`,...infer R]?`${B}${A}${C} ${X<R>}`:""

Try it at the TS playground

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

Gema, 11 characters

\X<L1>?=?$1

Sample run:

bash-5.2$ gema '\X<L1>?=?$1' <<< 'reverse the first two letters of each word'
erverse hte ifrst wto eltters fo aech owrd

Try it online! / Try all test cases online!

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

Uiua SBCS, 8 7 bytes

⍚⍜(↙2)⇌

Try it!

⍚⍜(↙2)⇌
⍚        # apply function to each item in list, unboxing and re-boxing
 ⍜       # apply one function 'under' another
  (↙2)   # take first two
      ⇌  # reverse
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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