Flippign Lettesr Aroudn

33

3

In chat, we are often fast-typers and don't really look at the order of letters before posting a message. Since we are lazy, we need a program that automatically swaps the last two letters in our words, but since we don't want to respond too late, the code must be short.

Your task, if you wish to accept it, is to write a program that flips the last two letters of each word in a given string (so the word Thansk turns into Thanks). A word is a sequence of two or more letters in the English alphabet delimited by a single space.

  • The string / list of characters you receive as input is guaranteed to only contain alphabetic characters and spaces (ASCII [97 - 122], [65 - 90] and 32).

  • You can take input and provide output through any standard method, in any programming language, while taking note that these loopholes are forbidden by default.

  • The output may have one trailing space and / or one trailing newline.

  • The input will always contain words only (and the corresponding whitespace) and will consist of at least one word.

This is code-golf, so the shortest submission (scored in bytes), in each language wins!

Test cases

Note that the strings are surrounded with quotes for readability.

Input -> Output

"Thansk"                                 -> "Thanks"
"Youer welcoem"                          -> "Youre welcome"
"This is an apple"                       -> "Thsi si na appel"
"Flippign Lettesr Aroudn"                -> "Flipping Letters Around"
"tHe oDd chALlEneg wiht swappde lettesR" -> "teH odD chALlEnge with swapped letteRs"

Or, for test suite convenience, here are the inputs and their corresponding outputs separately:

Thansk
Youer welcoem
This is an apple
Flippign Lettesr Aroudn
tHe oDd chALlEneg wiht swappde lettesR
Thanks
Youre welcome
Thsi si na appel
Flipping Letters Around
teH odD chALlEnge with swapped letteRs

Thanks to DJMcMayhem for the title. This was originally a CMC.

Mr. Xcoder

Posted 2017-12-27T19:45:19.603

Reputation: 39 774

May we output an array of words? – Shaggy – 2017-12-27T22:03:51.200

@Shaggy No, the output must be a string (or a list of characters by default) – Mr. Xcoder – 2017-12-27T22:04:47.303

May we request a trailing space on each input? – FlipTack – 2017-12-29T12:23:21.853

@FlipTack It was allowed in the initial version, but I have removed that rule before any of the answers that would use that had been posted. (partly because some users in chat told me I'm making this too easy otherwise, and I agree with them). No, it's not allowed.

– Mr. Xcoder – 2017-12-29T12:25:39.667

Whta shoudl eb doen wiht oen lettre worsd liek "a"? – Fabian Röling – 2017-12-29T14:08:09.893

1@Fabian *A word is a sequence of two or more letters* – Mr. Xcoder – 2017-12-29T14:12:13.543

Answers

16

V, 4 5 bytes

òeXp

Try it online!

|| denotes the cursor

The buffer starts with |w|ord and more words and the cursor being on the first character.

Recursively ò

go to the end of a word

wor|d| and more words

remove X the character to the left of the cursor

wo|d| and more words

paste it over the next character

wod|r| and more words

Implicit ending ò, repeat the same process for other words until the end of the buffer is reached

user41805

Posted 2017-12-27T19:45:19.603

Reputation: 16 320

2The right language for the task :) – James – 2017-12-27T22:52:26.460

Do you mean "Repeatedly" instead of "Recursively"? – NieDzejkob – 2017-12-30T15:09:36.473

@NieDzejkob The V wiki uses the word "recursively" to describe the ò command https://github.com/DJMcMayhem/V/wiki/Normal-Mode-Commands

– user41805 – 2017-12-30T18:06:54.963

10

Jelly, 7 bytes

Ḳœ?@€2K

A monadic link taking and returning lists of characters

Try it online!

How?

Ḳœ?@€2K - Link: list of characters
Ḳ       - split at spaces
     2  - literal two
    €   - for €ach:
   @    -   with sw@pped arguments:
 œ?     -     nth permutation (the 2nd permutation has the rightmost elements swapped)
      K - join with spaces

Jonathan Allan

Posted 2017-12-27T19:45:19.603

Reputation: 67 804

That's a nice abuse of permutations. Alternative

– Mr. Xcoder – 2017-12-27T20:21:22.410

@Mr.Xcoder Ḳ2œ?ЀK also works and uses a single quick. – Dennis – 2017-12-28T03:40:12.380

7

Brain-Flak, 122 bytes

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

Try it online!

The worst language for the job :)

Readable Slightly more readable version:

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

    {
        {}
        <>

        (({}({}))[({}[{}])])

        (<>)
    }
    {}

    ({}<>)<>

}<>

(({}({}))[({}[{}])])

{

    ({}<>)
    <>
}<>

James

Posted 2017-12-27T19:45:19.603

Reputation: 54 537

I can't believe this is longer than the Brainfuck version... – Pureferret – 2017-12-28T12:46:12.430

@pureferret Brain-flak tends to be longer than brainfuck. Mostly cause it requires two bytes per primitive command, where brain-flak requires two. – James – 2017-12-28T13:21:40.657

7

Haskell, 40 bytes

(f=<<).words
f[a,b]=b:a:" "
f(x:r)=x:f r

Try it online! Usage example: (f=<<).words $ "abc xyz" yields "acb xzy ".

Laikoni

Posted 2017-12-27T19:45:19.603

Reputation: 23 676

So you're telling me the shortest approach is both the approaches combined? >_< – totallyhuman – 2017-12-27T21:16:54.070

7

Retina, 13 bytes

(.)(.)\b
$2$1

Try it online! Link includes test cases.

Neil

Posted 2017-12-27T19:45:19.603

Reputation: 95 035

6

Python 3, 50 bytes

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

Try it online!

This answer abuses Python 3's behavior of print: Multiple arguments are printed with a single space between them. Of course, we can't just give it multiple arguments because we don't know how many words will be in the input. So we use the splat operator. Basically

print(*[a,b,c])

is exactly the same thing as

print(a,b,c)

Abusing that makes a full program turn out shorter than a function/lambda where we'd have to use ' '.join or something similar.

James

Posted 2017-12-27T19:45:19.603

Reputation: 54 537

Looks like Python 2 saves 2 bytes by writing for w in input().split():print w[:-2]+w[:-3:-1],. In Python 3, extracting the last two characters would work well with print(*(''.join(a)+c+b for*a,b,c in input().split())) except that a needs to be remade into a string. – xnor – 2017-12-28T04:01:29.950

5

C,  62   58  54 bytes

Thanks to @Dennis for saving  four  eight bytes!

f(char*s){s[1]>32||(*s^=s[-1]^=*s^=s[-1]);*++s&&f(s);}

Try it online!

Steadybox

Posted 2017-12-27T19:45:19.603

Reputation: 15 798

ah, the xor-based swap – Snowbody – 2017-12-29T14:52:30.430

5

Matlab (R2016b), 51 50 bytes

Saved 49 50 (!) bytes thanks to @Giuseppe.

function s(a),regexprep(a,'(\w)(\w)( |$)','$2$1 ')

And my previous answer:

Matlab (R2016b), 100 bytes

(Just for the fun of it :P)

function s(a),a=regexp(a,' ','split');for i=1:length(a),fprintf('%s ',a{i}([1:end-2 end end-1])),end

Explanation:

function s(a) % Defining as a function...
a=regexp(a,' ','split'); % Splits the input string at the spaces
for i=1:length(a) % Loops through each word
    fprintf('%s ',a{i}([1:end-2 end end-1])) % And prints everything with the last two characters swapped.
end

Thiago Oleinik

Posted 2017-12-27T19:45:19.603

Reputation: 341

1one character words can't happen, as a word is defined to be at least two characters. – Giuseppe – 2017-12-27T20:30:49.860

would regexprep work here? Something like regexprep(a,'(\w*)(\w)(\w)','\1\3\2')? – Giuseppe – 2017-12-27T20:53:50.680

D= This. Was. Epic! I think you should post this answer, since it's totally different from mine. The only thing is that Matlab references the matches with $1, and not \1, so it would be regexprep(a,'(\w*)(\w)(\w)','$1$3$2'). – Thiago Oleinik – 2017-12-27T20:59:37.587

1you should post it as a separate answer / in this answer; it's always good to see if a regex would help or not on a string challenge!

Besides, I clearly don't understand MATLAB's regex engine, so it wouldn't quite be fair for me to take credit for it. – Giuseppe – 2017-12-27T21:02:16.280

Thanks a lot @Giuseppe! And it doesn't even break with the 1 letter words! – Thiago Oleinik – 2017-12-27T21:07:53.150

1function s(a),regexprep(a,'(\w)(\w)( |$)','$2$1 ') is still another byte shorter! – Giuseppe – 2017-12-27T23:30:32.193

4

Prolog (SWI), 60 bytes

[A,B]+[B,A].
[A,B,32|U]+[B,A,32|Y]:-U+Y,!.
[A|U]+[A|Y]:-U+Y.

Try it online!

Explanation

First we define the base case:

p([A,B],[B,A]).

This means that the last two letters will always be swapped.

Then we define what happens if we are right next to a space:

p([A,B,32|U],[B,A,32|Y]):-p(U,Y),!.

Two strings match if right before a space the letters before the space are swapped and the remainder if the strings match. We then use ! to cut.

Our last case is if we are not next to a space the first two letters need to match.

p([A|U],[A|Y]):-p(U,Y).

Post Rock Garf Hunter

Posted 2017-12-27T19:45:19.603

Reputation: 55 382

4

R, 111 51 41 bytes

Courtesy of @Giuseppe, a regex approach which blows my old method out of the water.

cat(gsub("(.)(.)\\b",'\\2\\1',scan(,"")))

rturnbull

Posted 2017-12-27T19:45:19.603

Reputation: 3 689

1

regex are much more efficient here: Try it online!

– Giuseppe – 2017-12-27T20:48:12.213

(not that I don't appreciate the guts it takes to do a pure string manipulation approach in R) – Giuseppe – 2017-12-27T20:50:47.943

84 byte golf of your approach – Giuseppe – 2017-12-27T23:22:11.510

@Giuseppe Wow, nice work! I've edited them into my answer, although if you'd prefer to make your own answer please go ahead! – rturnbull – 2017-12-28T01:10:54.407

1

nah, don't worry about it. I golfed down another 10 bytes: porting another regex approach, and a 70 byte of your old approach

– Giuseppe – 2017-12-28T15:14:18.103

4

Wolfram Language, 117 bytes

StringReplace[RegularExpression["\\b[[:alpha:]]{2,}\\b"]:>StringDrop[StringInsert["$0",StringTake["$0",{-1}],-3],-1]]

Try it online!

Applied to the test strings.

StringReplace[
  RegularExpression["\\b[[:alpha:]]{2,}\\b"] :> 
   StringDrop[StringInsert["$0", StringTake["$0", {-1}], -3], -1]] /@
 {"Thansk", "Youer welcoem", "This is an apple", 
  "Flippign Lettesr Aroudn", "tHe oDd chALlEneg wiht swappde lettesR"} // Column
Thanks
Youre welcome
Thsi si na appel
Flipping Letters Around
teH odD chALlEnge with swapped letteRs

Edmund

Posted 2017-12-27T19:45:19.603

Reputation: 141

4Welcome to PPCG! – Steadybox – 2017-12-27T21:06:31.153

@Steadybox Thanks. – Edmund – 2017-12-27T23:25:00.523

4

APL (Dyalog Classic), 28 bytes

1↓∊((¯2↓⊢),2↑⌽)¨' '(,⊂⍨⊣=,)⍞

⎕ML and ⎕IO are both 1,

Try it online!

Explanation

  • ... (,⊂⍨⊣=,) ... Split (while keeping borders, and appending a border to the beginning) ...
  • ... ⍞ ... the input ...
  • ... ' ' ... ... at spaces.
  • ... ( ... )¨ ... Then, to each element of that:
    • ... , ... Concatenate ...
    • ... (¯2↓⊢) ... ... every item except the last two ...
    • ... 2↑⌽ ... ... with the reverse of the last two elements.
  • 1↓∊ ... Finally, return all but the first element of the flattened result.

Zacharý

Posted 2017-12-27T19:45:19.603

Reputation: 5 710

*return all but the first* – Adám – 2018-02-01T11:18:58.473

3

Haskell, 45 bytes

-2 bytes thanks to H.PWiz.

(r.g.r=<<).words
g(x:y:z)=' ':y:x:z
r=reverse

Try it online!

totallyhuman

Posted 2017-12-27T19:45:19.603

Reputation: 15 378

3

Funky, 34 bytes

s=>s::gsub("(.)(.)( |$)","$2$1$3")

Try it online!

ATaco

Posted 2017-12-27T19:45:19.603

Reputation: 7 898

3

J, 20 19 11 bytes

Credit to @Bolce Bussiere

1&A.&.>&.;:

Try it online!

       &.;:      on words
    &.>          on each
  A.             apply the permutation
1&               number 1, swap the last two elements

FrownyFrog

Posted 2017-12-27T19:45:19.603

Reputation: 3 112

113 Bytes with (1&A.&.>)&.;: – Bolce Bussiere – 2017-12-31T19:24:44.050

@BolceBussiere perfect – FrownyFrog – 2018-01-01T18:27:23.187

Could you add an explanation? Wondering if I can port it to K to reduce the embarrassing byte count of my solution! – streetster – 2018-01-01T21:18:09.540

3

Alice, 24 bytes

/0RR'.%$1\' o
\ix*o ne@/

Try it online!

Explanation

/...\' o
\.../

This forms a loop where the loop body is a linear Ordinal snippet and we execute ' o in Cardinal mode between every two loop iterations. The latter just prints a space.

Unfolding the zigzag structure of the Ordinal code, the linear loop body actually looks like this:

iR*' %e10xRo.n$@

Breaking this down:

i     Read all input. On subsequent iterations, this will push an empty string.
R     Reverse.
*     Join. On the first iteration, this joins the input to an implicit empty string,
      which does nothing. On subsequent iterations, it will join the empty string to
      the word on top of the string, thereby getting rid of the empty string.
' %   Split around spaces. On the first iteration, this will split the input
      into individual words. On subsequent iterations, this does nothing.
e10   Push "10".
x     Use this to permute the (reversed) word on top of the stack. In
      particular, the word is rearranged with the same permutation that is
      required to sort the string "10", which means the first two letters
      get swapped (which correspond to the last two letters of the actual
      word).
R     Reverse the swapped word.
o     Print it.
.n$@  If there are no words left on the stack, terminate the program.

Martin Ender

Posted 2017-12-27T19:45:19.603

Reputation: 184 808

Just noticed that the letter swap can be done in three bytes (h~Z) instead of four (e10x), but I'm not seeing a way to adjust the layout to actually save a byte overall with that. – Martin Ender – 2018-01-03T13:52:32.177

2

brainfuck, 109 100 bytes

Edit: don’t have to handle one letter words

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

Try it online!

Prints a trailing space

How It Works

,[>++++[-<-------->],] Puts input on the tape and subtracts 32 from each character
                       This separates each word

>+[- Start the loop
   <[>++++[<++++++++>-]<[->>+<<]<] Add 32 to each letter of the word
                                   Skip this on the first iteration for the last word

   <<[->>+<<]>[[-<+>]>] Swaps the last two letters of the word
   <<[>+>+>]- If there is another word to the left continue loop
              Also set up to add a space to the end of the word
 <] End loop
 >>>>>>>[.>] Print the modified string

Previous version, 109 bytes

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

Try it online!

Jo King

Posted 2017-12-27T19:45:19.603

Reputation: 38 234

2

QuadR, 8 bytes

..\b
⌽⍵M

Try it online!

Uriel

Posted 2017-12-27T19:45:19.603

Reputation: 11 708

1

05AB1E, 7 bytes

#vy`sðJ

Try it online!

-1 thanks to Magic Octopus Urn.

Prints one trailing space.

Erik the Outgolfer

Posted 2017-12-27T19:45:19.603

Reputation: 38 134

This is 11 bytes – Daniel W. – 2017-12-28T12:50:45.533

2

@DanFromGermany No, 05AB1E has a code page in which this can be represented as 8 bytes.

– Erik the Outgolfer – 2017-12-28T12:51:24.853

Can you run the program represented in 8 bytes? – Daniel W. – 2017-12-28T13:06:06.723

@DanFromGermany Yes, the 05AB1E interpreter can run this program from a file in the 05AB1E encoding. – Erik the Outgolfer – 2017-12-28T13:09:19.047

@ETHproductions um, what? – Erik the Outgolfer – 2017-12-29T09:18:35.557

@EriktheOutgolfer Uh, I 100% didn't mean to post that. Thought I hit cancel... – ETHproductions – 2017-12-29T20:28:36.877

Try it online (7-bytes) if trailing spaces are allowed (can't use in-line code for that lol). – Magic Octopus Urn – 2018-02-02T14:44:15.143

@MagicOctopusUrn yes, one trailing space is allowed – Erik the Outgolfer – 2018-02-02T14:48:47.913

I didn't know s worked like that on lists, weird. – Magic Octopus Urn – 2018-02-02T14:55:29.740

1@MagicOctopusUrn It's not a list though, it's after ```. – Erik the Outgolfer – 2018-02-02T14:58:41.857

@EriktheOutgolfer is flatten to stack? Wow, I've only ever used~` cause I thought they were one-and-the-same. – Magic Octopus Urn – 2018-02-02T15:24:26.557

1

PHP, 119 107 bytes

Edit: thanks to totallyhuman

<?php foreach(explode(" ",trim(fgets(STDIN)))as$w)echo substr($w,0,strlen($w)-2).strrev(substr($w,-2))," ";

Try it online!

Zerquix18

Posted 2017-12-27T19:45:19.603

Reputation: 131

1Can't you make $word a single character variable name? – totallyhuman – 2017-12-28T00:33:47.460

@totallyhuman Yup! I wrote the full version and then compressed it, but didn't notice that. Thanks you. – Zerquix18 – 2017-12-28T03:33:16.057

PHP open tags can be omitted in the answer saving you 6 bytes. – Daniel W. – 2017-12-28T12:26:17.243

I wonder if fgets(STDIN) can be omitted or replaced by $x too, like not all answers do count the input to their answers – Daniel W. – 2017-12-28T12:32:02.733

trim() should be unnecessary. – Titus – 2017-12-29T08:55:28.637

1

sed, 20 17+1 (-r) = 18 bytes

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

Try it online!

Noskcaj

Posted 2017-12-27T19:45:19.603

Reputation: 421

The TIO link does not match your posted code. The TIO link is a few bytes longer. – Xcali – 2017-12-28T03:06:48.507

Whoops, fixed the link – Noskcaj – 2017-12-28T03:14:46.613

You can remove |$. It's not doing anything. (For it to do what you expect you'd need (.)(.)(\b|$), but that's not necessary because \b already matches the end of the string.) – Jordan – 2017-12-28T19:42:36.047

Whoops, meant to get rid of that. Thanks, – Noskcaj – 2017-12-28T19:58:54.190

1

Haskell, 41 bytes

foldr(%)" "
a%(b:' ':r)=b:a:' ':r
a%s=a:s

Try it online!

Outputs with a trailing space.

The repeated ' ':r looks wasteful. But a%(b:t@(' ':r))=b:a:t is the same length and a%(b:t)|' ':_<-t=b:a:t is one byte longer.


Haskell, 41 bytes

f(a:b:t)|t<"A"=b:a:f t|1>0=a:f(b:t)
f e=e

Try it online!

xnor

Posted 2017-12-27T19:45:19.603

Reputation: 115 687

1

JavaScript (Node.js), 38 36 32 bytes

s=>s.replace(/(.)(.)( |$)/g,"$2$1 ") 
s=>s.replace(/(.)(.)\b/g,"$2$1")

Try it online!

RegExp approach courtesy @Giuseppe (although I thought of this independently), assuming words separated by only one space

-2 for only considering 1 space and add trailing space

-4 Thanks @Shaggy

Shieru Asakoto

Posted 2017-12-27T19:45:19.603

Reputation: 4 445

Doesn't matter if there are more spaces, I think – l4m2 – 2017-12-28T09:48:12.217

@l4m2 But if there are more spaces then it will become a 38 for s=>s.replace(/(.)(.)( +|$)/g,"$2$1$3"). – Shieru Asakoto – 2017-12-28T09:49:16.410

@l4m2 BTW my original answer was s=>s.replace(/(.)(.)(\s|$)/g,"$2$1$3") – Shieru Asakoto – 2017-12-28T09:51:01.607

ab abc abcd abcde abcdef does ab_, bc_, cd_, de_, ___, ef_, ___ – l4m2 – 2017-12-28T09:55:11.843

@l4m2 Oh that's indeed true ;) (although I only see one space between every word) – Shieru Asakoto – 2017-12-28T10:02:27.857

1F=s=>s.replace(/(.)(.)(?!\w)/g,"$2$1") same length – l4m2 – 2017-12-28T10:08:14.367

32 bytes: s=>s.replace(/(.)(.)\b/g,"$2$1") (Or 34 bytes without grouping: s=>s.replace(/..\b/g,([x,y])=>y+x)) – Shaggy – 2018-02-01T11:08:56.083

1

PHP, 65 bytes

requires PHP 7.1 (or later)

for(;$s=$argv[++$i];$s[-1]=$s[-2],$s[-2]=$c,print"$s ")$c=$s[-1];

takes sentence as separate command line arguments. Run with -nr.


working on a single string, 77+1 bytes:

foreach(explode(" ",$argn)as$s){$c=$s[-1];$s[-1]=$s[-2];$s[-2]=$c;echo"$s ";}

Run as pipe with -nR.


... or try them online.

Titus

Posted 2017-12-27T19:45:19.603

Reputation: 13 814

1

K (oK), 23 22 bytes

" "/{x@prm[!#x]1}'" "\

Try it online!

Example:

" "/{x@prm[!#x]1}'" "\"Hello World"
"Helol Wordl"

Explanation:

Port of FrownyFrog's solution to save 1 byte.

I'll come back to this.

" "/{prm[x]1}'" "\ / the solution
              " "\ / split input on " "
    {       }'     / apply lambda to each
     prm[x]        / permute input x
           1       / and take the 2nd result
" "/               / join with " "

Previous solution:

  • " "/-2{(x_y),|x#y}'" "\ 23 bytes

streetster

Posted 2017-12-27T19:45:19.603

Reputation: 3 635

1

Google Sheets, 33 Bytes

Anonymous worksheet function that takes input from cell A1 and outputs to the calling cell

=RegExReplace(A1,"(.)(.)\b","$2$1

-2 Bytes Thanks to @KevinCruijssen for the use of (.) over (\w)

Taylor Scott

Posted 2017-12-27T19:45:19.603

Reputation: 6 709

Both (\w) can be golfed to (.) if I'm not mistaken. The \b is already an indication to look for words only. (Not entirely sure though, but it works in Java.) – Kevin Cruijssen – 2018-02-01T10:54:18.653

@KevinCruijssen - You are absolutely correct, it can be. Thank you! – Taylor Scott – 2018-02-01T17:52:38.563

1

Java 8, 35 bytes

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

Port of @TaylorScott's Google Sheets answer, after I golfed two bytes. EDIT: I see it's now a port of Neil's Retina answer after my two golfed bytes.

Explanation:

Try it online.

s->                           // Method with String as both parameter and return-type
   s.replaceAll("(.)(.)       //  Replace any two characters,
                       \\b",  //  with a word-boundary after it (space or end of String)
                "$2$1")       //  With the two characters swapped

Kevin Cruijssen

Posted 2017-12-27T19:45:19.603

Reputation: 67 575

0

Haskell, 53 45 bytes

u[a,b]=[b,a]
u(a:b)=a:u b
unwords.map u.words

Try it online!

Explanation

u is a function that swaps the last two letters of a word. To apply it to all the words we use words to split the list, map it across all of the words and then use unwords to put it back together.

Post Rock Garf Hunter

Posted 2017-12-27T19:45:19.603

Reputation: 55 382

You seem to have included the f= from TIO in your byte count, even though it's not included in your answer here. – Kritzefitz – 2017-12-27T23:55:21.183

How do you pass the input to your program? Does main=print$f"Hello World" not count to the program? – Daniel W. – 2017-12-28T12:27:56.953

@Kritzefitz Thanks! I've adjusted it. – Post Rock Garf Hunter – 2017-12-28T18:26:44.047

@DanFromGermany My program makes a point-free function unwords.map u.words. You call it like any other Haskell function. main=print$f"Hello World" does not count because my submission is a function and not a program. – Post Rock Garf Hunter – 2017-12-28T18:28:43.973

0

Jelly, 10 bytes

ḲṪ,¥\€Ḋ€UK

Try it online!

dylnan

Posted 2017-12-27T19:45:19.603

Reputation: 4 993

0

SNOBOL4 (CSNOBOL4), 136 119 bytes

	I =INPUT
B	I SPAN(&LCASE &UCASE) . Y ARBNO(' ') =:F(O)
	Y RPOS(2) REM . Z =REVERSE(Z)
	O =O Y ' '	:(B)
O	OUTPUT =O
END

Try it online!

Prints with a trailing space. You know you've done something wrong when a language is a backronym for StriNg Oriented and symBOlic Language and your code is longer than Brain-Flak :( now it's slightly better.

Line B takes I and replaces (alphabetic characters saved as Y)(some number of spaces) with the empty string.

The following line extracts the last 2 characters of Y as Z and replaces them as Z reversed, then the next line concatenates O, Y, and a single space character.

Finally, it prints when I no longer matches the required pattern in line B.

Giuseppe

Posted 2017-12-27T19:45:19.603

Reputation: 21 077

0

Perl 5, 19 + 1 (-p) = 20 bytes

s/(\w)(\w)\b/$2$1/g

Try it online!

Xcali

Posted 2017-12-27T19:45:19.603

Reputation: 7 671

0

Clean, 75 59 bytes

-16 from Laikoni

@[a,b]=[b,a]
@[a,b,' ':c]=[b,a,' ': @c]
@[a:b]=[a: @b]
@e=e

Try it online!

Οurous

Posted 2017-12-27T19:45:19.603

Reputation: 7 916

This seems to work fine without import StdEnv. – Laikoni – 2017-12-28T13:28:18.160

Also moving @[]=[] to the bottom and replacing it by @e=e saves two more bytes: Try it online!

– Laikoni – 2017-12-28T13:32:52.130

0

Standard ML (MLton), 92 77 bytes

implode o foldr(fn(a,b:: #" "::r)=>b::a:: #" "::r|(a,r)=>a::r)[#" "]o explode

Try it online! Based on xnor's Haskell solution.


Previous 92 byte version

fun f(a::b:: #" "::r)=b::a:: #" "::f r|f(x::r)=x::f r|f r=r
fun$s=implode(f(explode(s^" ")))

Try it online! Example usage: $ "Flippign Lettesr Aroudn" yields "Flipping Letters Around ".

Ungolfed

fun f (a :: b :: #" " :: r) = b :: a :: #" " :: f r
  | f              (x :: r) = x :: f r
  | f                    r  = r

fun g s = implode (f (explode (s ^ " ")))

Try it online!

Laikoni

Posted 2017-12-27T19:45:19.603

Reputation: 23 676

0

Japt, 7 bytes

A port of Jonathan's Jelly solution.

®á g1}S

Try it


Explanation

® }S splits the input on spaces, maps over the array and rejoins with spaces, á generates an array of all permutations of the current element and g1 gets the second element of that array.

Shaggy

Posted 2017-12-27T19:45:19.603

Reputation: 24 623

0

Wolfram Language (Mathematica), 72 bytes

x""<>(Characters[StringSplit@x][[;;,#]]&/@{;;-3,-1,-2})~Riffle~" "

Try it online!

Another approach using manipulation of character list and take parts instead of string regex.

The two Unicode characters are \[Function] and \[Transpose] in private use area of Mathematica, take 3 bytes each.

74 bytes

Try it online!

user202729

Posted 2017-12-27T19:45:19.603

Reputation: 14 620

0

Excel VBA, 78 Bytes

Anonymous VBE immediate window that takes input from range A1 and outputs to the VBE immediate window.

For Each s in Split([A1]):l=Len(s):?Left(s,l-2)Right(s,1)Mid(s,l-1,1)" ";:Next

Taylor Scott

Posted 2017-12-27T19:45:19.603

Reputation: 6 709

0

Ruby, 53 bytes

$*.each{|x|print x[0,x.length-2]+x[-2,2].reverse," "}

The program takes input through command line arguments (formatted as a regular sentence, without quotes).

$* is a shorthand for ARGV, therefore i can iterate over each of the words, already in an array.

Only thing that bugs me is that awful x.length-2 snippet. I would prefer to use x.last(-2), but i believe that is only in RoR.

Called like:

ruby file.rb Helol Wordl

So that each word becomes a parameter. (Not wrapped in quotes)

Håvard Nygård

Posted 2017-12-27T19:45:19.603

Reputation: 341

Doesn’t return the correct results for me. The letters aren’t swapped on all the words. – Mr. Xcoder – 2017-12-29T19:31:01.910

@Mr.Xcoder It is because TIO passes the argument in quotes :) Add a argument for each word, and it works – Håvard Nygård – 2017-12-29T19:42:08.550

This works, in practice, atleast on windows you can pass arguments without quotes, hence you can type it as if you typed a regular sentence – Håvard Nygård – 2017-12-29T19:44:52.813

0

Clojure, 122 117 bytes

-5 bytes by shortcutting the indices of the characters to swap

(fn[p](map #(let[l(count %)v(vec %)y(dec l)z(- l 2)](apply str(assoc v y(v z)z(v y))))(clojure.string/split p #" ")))

It's a shame that most of Clojure's String function are tucked away inside of Clojure.string, and that there are no good ways of manipulating the characters of Strings directly. clojure.string/split is atrociously long, and the conversion to-and-from vectors added quite a lot. I might be able to shave off a couple bytes by shortcutting the trailing indices, but this is the only decent algorithm I could think of.

(defn flip-last [phrase]
  (let [words (clojure.string/split phrase #" ")]

    ; For each word...
    (map #(let [len (count %)
                ; Need to turn the string into a vector so we can manipulate it using indices
                vec-word (vec %)]

            ; ... then turn the vector of characters back into a String.
            (apply str
               ; Associate the element at the second last index with the element at the last index,
               ;  and vice-versa...
              (assoc vec-word (dec len) (vec-word (- len 2))
                              (- len 2) (vec-word (dec len)))))

         words)))

Carcigenicate

Posted 2017-12-27T19:45:19.603

Reputation: 3 295

0

QuadR, 8 bytes

..\b
⌽⍵M

Try it online!

..\b any two characters followed by a word boundary

gets replaced with

⌽⍵M the reverse of the Match


Equivalent to the following 18-byte Dyalog APL function:

'..\b'⎕R{⌽⍵.Match}

Adám

Posted 2017-12-27T19:45:19.603

Reputation: 37 779