# Erverse Hte Ifrst Wto Eltters fo Aech Owrd

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)


/* 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 COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 107299; // This should be the user ID of the challenge author.

/* App */

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

}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(a) {
});
comment_page = 1;
}
});
}

jQuery.ajax({
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
});
else process();
}
});
}

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

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

function process() {
var valid = [];

var body = a.body;
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],
});
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;

.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)

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)
language = jQuery(language);
jQuery("#languages").append(language);
}

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

width: 290px;
float: left;
}

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

font-weight: bold;
}

table td {
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<tr><td>Language</td><td>User</td><td>Score</td></tr>
<tbody id="languages">

</tbody>
</table>
</div>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>

</tbody>
</table>
</div>
<table style="display: none">
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
</tbody>
</table>

• 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") Jul 4 at 15:39
• 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?
Jul 4 at 15:40
• Jul 4 at 16:04
• @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 Jul 4 at 18:36
• @pxeger yes. You may Jul 4 at 18:38

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


# 05AB1E, 765 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.

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

# 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!

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

# 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


# 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"
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.

# JavaScript (ES6), 33 bytes

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


Try it online!

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

• Even more stupid for 8 Jul 7 at 11:00
• @UnrelatedString lmao Jul 8 at 8:41

# Vyxal, 985 4 bytes

- x bytes thanks to @Steffan

ƛḣ$Y  ## Explanation ƛḣ$Y
ƛ     Map through each word
ḣ    Push all but the first letter and the first letter
$Swap the first two elements Y Interleave  • @Steffan ah nice Jul 4 at 18:46 • @Steffan but you still have to output a string? Jul 4 at 19:09 • @Steffan shh hopefully nobody'll notice Jul 4 at 19:20 • @Steffan oh wow Jul 18 at 11:55 • @Steffan the heck I give up Jul 19 at 11:19 # Zsh--extendedglob, 29 bytes <<<${@/(#m)??/rev<<<$MATCH} Attempt This Online! Zsh's pattern matching is pretty limited. -1 byte thanks to @GammaFunction. # 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. • And gsub nicely handles multiple matches so you could take \(x)gsub('( |^)(.)(.)','\\1\\3\\2',x,F,T) to the space-delimited string input. Jul 5 at 0:32 • @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) Jul 5 at 5:41 # 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! • 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. :) Jul 5 at 20:09 • 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! Jul 5 at 20:24 # Piet + ascii-piet, 28 25 bytes (13×2=26 codels) tU?QjCuJsNrMbQvQsQjIJjMmm  Try Piet online! −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. # QuadR, 1814 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 # 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! • There's a tip for abusing the {} created by -p... but not for ;; maybe there should be? – Neil Jul 7 at 6:30 • @Neil Huh. I could've sworn I learned about that from the tips! I'll add something, thanks for the heads up Jul 7 at 8:47 # 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! # 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 # 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. # 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  • 6 Jul 4 at 21:53 # Ruby, 28 bytes ->s{s.map{|w|(w.slice!1)+w}}  Try it online! • Ruby 3+, -1 byte ->s{s.map{(_1.slice!1)+_1}} Attempt This Online! Jul 7 at 3:34 # 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 :(

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

# 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


# sed-r, 17 bytes

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


Try it online!

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

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

• Because Under is pure magic, it also works with Take: 8 bytes Jul 6 at 22:51
• @DLosc - wonderful, thanks! Jul 7 at 5:27

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

# K (ngn/k), 11 bytes

{x@>1=!#x}'


Try it online!

# 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

• Now that I/O can be lists, it's 5 bytes ḣ2Uo) (or something like that) Jul 4 at 19:39

# Python 3, 51 bytes

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


Try it online!

• -3 bytes by using a full program: ato.pxeger.com/… Jul 4 at 16:41

# APL+WIN, 26 bytes

Prompts for sentence

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


Try it online! Thanks to Dyalog Classic

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

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

# 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