Reversing of Words

30

2

Sona is in her house with her 10 year old daughter. She needs to go to school to bring back another child from school, as school is over at 2 pm. It's hot outside, so she wants to leave her younger child at home.

She gave a bunch of strings to her child to keep her busy while she is gone. She asked her to reverse the words in the string. There are lot of strings, so you need to help her daughter in solving this huge task.

So, given a string that contains words separated by single space, reverse the words in the string. You can assume that no leading or trailing spaces are there.

The string will only contain [a-zA-z ], so you don't need to handle punctuation.

You will be given a string as an input, and you should output a string.

Sample Test Cases:

Input:
Man bites dog 

Output: 
dog bites Man


Input:
The quick brown fox jumps over the lazy dog

Output:
dog lazy the over jumps fox brown quick The


Input:
Hello world

Output:
world Hello

Scoring

This is . Shortest answer in bytes wins.

user69410

Posted 2017-05-17T15:00:46.050

Reputation:

1Related. – Martin Ender – 2017-05-17T15:02:29.403

1Can we take the input as a list of words? (i.e. ['man', 'bites', 'dog']) – Rɪᴋᴇʀ – 2017-05-17T15:18:38.090

3Can the output have trailing whitespace? – Digital Trauma – 2017-05-17T16:13:08.480

Answers

11

Retina, 7 bytes

O$^`\w+

Try it online!

Match all words (\w+) sort them with sort key empty string (O$) which means they won't get sorted at all, and then reverse their order (^).

Martin Ender

Posted 2017-05-17T15:00:46.050

Reputation: 184 808

Never used Retina but why do you need the 0$? Can't you just reverse it? – caird coinheringaahing – 2017-05-23T23:19:44.790

@RandomUser sort mode (O) is currently the only mode that has this reverse option. – Martin Ender – 2017-05-24T00:02:25.020

9

Haskell, 21 bytes

unwords.reverse.words

Try it online!

nimi

Posted 2017-05-17T15:00:46.050

Reputation: 34 639

9

Python 3, 29 bytes

print(*input().split()[::-1])

Try it online!

Rod

Posted 2017-05-17T15:00:46.050

Reputation: 17 588

What does the * do? – OldBunny2800 – 2017-05-28T23:38:09.740

@OldBunny2800 unpack the list

– Rod – 2017-05-29T02:41:50.093

Ahh. Makes sense. – OldBunny2800 – 2017-05-29T03:03:36.623

7

JavaScript (ES6), 31 bytes

s=>s.split` `.reverse().join` `

Try it

f=
s=>s.split` `.reverse().join` `
o.innerText=f(i.value="Man bites dog")
oninput=_=>o.innerText=f(i.value)
<input id=i><pre id=o>

Shaggy

Posted 2017-05-17T15:00:46.050

Reputation: 24 623

1It's answers like this, that is essentially the same as my C# answer that makes me hate C# for golfing. All the extra fluff in my answer nearly doubles the byte count... +1 – TheLethalCoder – 2017-05-17T15:59:51.717

Side note: In C# if you pass nothing to Split it splits on whitespace by default, can you do the same here? – TheLethalCoder – 2017-05-17T16:00:26.597

1Unfortunately not, @TheLethalCoder, if you don't supply a string/regex to split in JS, it will either split on each individual character or create an array with a single element containing the original string, depending on the syntax used. – Shaggy – 2017-05-17T18:25:19.643

7

Bash + common Linux utilities, 21

printf "$1 "|tac -s\ 

Leaves a trailing space in the output string - not sure if that's OK or not.

Digital Trauma

Posted 2017-05-17T15:00:46.050

Reputation: 64 644

2Congrats on 50k!! Your turn today :-) – Luis Mendo – 2017-05-18T17:02:17.810

@LuisMendo Thanks! – Digital Trauma – 2017-05-18T17:02:36.337

6

Jelly, 3 bytes

ḲṚK

Try it online!

Explanation:

Ḳ     Splits the input at spaces
Ṛ     Reverses the array
K     Joins the array, using spaces

steenbergh

Posted 2017-05-17T15:00:46.050

Reputation: 7 772

5https://en.wikipedia.org/wiki/Krk – QBrute – 2017-05-18T06:29:41.797

6

R, 19 bytes

cat(rev(scan(,'')))

reads the string from stdin. By default, scan reads tokens separated by spaces/newlines, so it reads the words in as a vector. rev reverses, and cat prints the elements with spaces.

Try it online!

Giuseppe

Posted 2017-05-17T15:00:46.050

Reputation: 21 077

6

Brachylog, 6 bytes

ṇ₁↔~ṇ₁

Try it online!

Explanation

ṇ₁        Split on spaces
  ↔       Reverse
   ~ṇ₁    Join with spaces

Note that both "split on spaces" and "join wth spaces" use the same built-in, that is ṇ₁, just used in different "directions".

Fatalize

Posted 2017-05-17T15:00:46.050

Reputation: 32 976

4

C#, 58 bytes

using System.Linq;s=>string.Join(" ",s.Split().Reverse());

TheLethalCoder

Posted 2017-05-17T15:00:46.050

Reputation: 6 930

3

05AB1E, 4 bytes

#Rðý

Note: Will only work for 2 or more words. +1 byte if this is not OK.

Try it online!

Okx

Posted 2017-05-17T15:00:46.050

Reputation: 15 025

I see unicode, is it reallly 4 bytes? – val says Reinstate Monica – 2017-05-18T04:38:20.047

Yes, 05AB1E uses a custom codepage

– kalsowerus – 2017-05-18T07:34:00.460

#R¸» alternate 4-byte solution :P. – Magic Octopus Urn – 2017-06-28T19:17:55.290

3

brainfuck, 74 bytes

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

Try it online!

This code creates the number -32 in two different places, but that seems to be fewer bytes than trying to maintain a single -32.

Explanation

,[                        input first character
  >++++[<-------->-]      subtract 32 from current character (so space becomes zero)
,]                        repeat for all characters in input
<                         go to last character of last word
[                         while there are more words to display:
 >++++[->--------<]       create -32 two cells right of last letter
 +>                       increment trailing space cell (1 right of last letter) so the next loop works
 [[<]>[+>]<]              add 32 to all cells in word and trailing space cell
 <-                       subtract the previously added 1 from the trailing space
 [<]>                     move pointer to beginning of word
 [.>]<                    output word (with trailing space)
 [[-]<]                   erase word
 <                        move to last character of previous word
]

Nitrodon

Posted 2017-05-17T15:00:46.050

Reputation: 9 181

3

Japt, 11 10 7 4 bytes

My first attempt at Japt.

¸w ¸

Try it online


Explanation

    :Implicit input of string U
¸   :Split on <space>
w   :Reverse
¸   :Join with <space>

Please share your Japt tips here.

Shaggy

Posted 2017-05-17T15:00:46.050

Reputation: 24 623

2Thanks for using Japt :-) You can use ¸ in place of qS, which should save you three bytes here. (See the "Unicode shortcuts" section of the interpreter docs) – ETHproductions – 2017-05-18T12:36:44.053

Nice! you can save a byte if you use the -S flag.

– Oliver – 2017-05-18T14:40:27.687

I count 2 bytes, @obarakon. Unless the flag is included in the byte count, in which case that would be 4 byes, no? – Shaggy – 2017-05-18T14:42:21.713

@Shaggy Each flag counts as one byte. So -S would be +1 onto your total byte count. – Oliver – 2017-05-18T14:43:53.170

Ah, I see. Is that a PPCG thing or a Japt thing? – Shaggy – 2017-05-18T14:44:32.297

@Shaggy It's a PPCG thing. Source

– Oliver – 2017-05-18T14:50:21.523

3

C, 54 48 bytes

Using arguments as input, 48 bytes

main(c,v)char**v;{while(--c)printf("%s ",v[c]);}

Try Online

> ./a.out man bites dog

Using pointers, 84 bytes

f(char*s){char*t=s;while(*t)t++;while(t-s){while(*t>32)t--;*t=0;printf("%s ",t+1);}}

Use

main(){ f("man bites dog"); }

Khaled.K

Posted 2017-05-17T15:00:46.050

Reputation: 1 435

2

Python 2, 34 bytes

lambda s:' '.join(s.split()[::-1])

Try it online!

totallyhuman

Posted 2017-05-17T15:00:46.050

Reputation: 15 378

Out-golfed. >_> Well... the other one only works in Python 3... – totallyhuman – 2017-05-17T15:47:02.813

2

Pyth, 4 bytes

jd_c

Try it online!

notjagan

Posted 2017-05-17T15:00:46.050

Reputation: 4 011

2

PHP, 47 Bytes

<?=join(" ",array_reverse(explode(" ",$argn)));

Try it online!

Jörg Hülsermann

Posted 2017-05-17T15:00:46.050

Reputation: 13 026

2

GNU Make, 62 bytes

$(if $1,$(call $0,$(wordlist 2,$(words $1),$1)) $(word 1,$1),)

eush77

Posted 2017-05-17T15:00:46.050

Reputation: 1 280

2

Röda, 27 25 bytes

2 bytes saved thanks to @fergusq

{[[split()|reverse]&" "]}

Try it online!

This function takes input from the input stream.

Explanation (outdated)

{[[(_/" ")()|reverse]&" "]}           /* Anonymous function */
   (_/" ")                            /* Pull a value from the stream and split it on spaces */
          ()                          /* Push all the values in the resulting array to the stream */
            |reverse                  /* And reverse it */
  [                 ]                 /* Wrap the result into an array*/
                     &" "             /* Concatenate each of the strings in the array with a space */
 [                       ]            /* And push this result to the output stream */

user41805

Posted 2017-05-17T15:00:46.050

Reputation: 16 320

split uses space as the default separator, so split() is shorter than (_/" ")(). – fergusq – 2017-05-19T16:45:41.330

2

Mathematica, 35 bytes

StringRiffle@Reverse@StringSplit@#&

Try it online!

J42161217

Posted 2017-05-17T15:00:46.050

Reputation: 15 931

StringSplit[#] splits on whitespace automatically, so you don't need to specify the " ". – Not a tree – 2017-05-20T00:34:33.180

2correct! -5 bytes! – J42161217 – 2017-05-20T00:39:36.473

Ooh, and I think you can save another byte using function composition: StringRiffle@*Reverse@*StringSplit (call it like StringRiffle@*Reverse@*StringSplit@"hello world") – Not a tree – 2017-05-20T00:56:40.063

2

Cubix, 48 bytes

Almost gave up on this one, but finally got there.

oU_;SW;@?ABu>):tS-?;\0$q^s.$;;<$|1osU!(;;...<#(1

Try it online!

This maps onto a cube with a side length of three as follows

      o U _
      ; S W
      ; @ ?
A B u > ) : t S - ? ; \
0 $ q ^ s . $ ; ; < $ |
1 o s U ! ( ; ; . . . <
      # ( 1
      . . .
      . . .

The general steps are:

  • Get all input A and reverse B stack
  • Move the negative q to the bottom, add a counter 0 to the stack. bit of jumping around in here.
  • Find space/end loop, also puts stack in correct print order.
    • Increment counter ) and fetch the counter item from the stack t
    • Is it a space or EOI S-?
    • Repeat if not
  • Print word loop
    • Decrement counter (
    • Exit loop if counter !U is 0
    • Swap s counter with character on stack
    • Print o character and pop it from the stack ;
    • Repeat loop
  • Get the length of the stack # and decrement (
  • Check ? if 0 and exit @ if it is 0
  • Otherwise print a space So clean up ;; and go back to the first loop.

I've skipped a number of superfluous steps, but you can see it Step By Step

MickyT

Posted 2017-05-17T15:00:46.050

Reputation: 11 735

1

CJam, 7 bytes

qS/W%S*

Try it online!

Explanation

q        e# Read input
 S/      e# Split on spaces
   W%    e# Reverse
     S*  e# Join with spaces

Business Cat

Posted 2017-05-17T15:00:46.050

Reputation: 8 927

1

Ohm, 4 bytes

z]Qù

Try it online!

Explanation

z     Split the input on spaces.
 ]    Dump it onto the stack.
  Q   Reverse the stack.
   ù  Join the stack with spaces. Implicit output.

Business Cat

Posted 2017-05-17T15:00:46.050

Reputation: 8 927

1

k, 9 bytes

" "/|" "\

Try it in your browser of the web variety!

     " "\ /split on spaces
    |     /reverse
" "/      /join with spaces

zgrep

Posted 2017-05-17T15:00:46.050

Reputation: 1 291

1

J, 6 bytes

|.&.;:

Try it online! This is reverse (|.) under (&.) words (;:). That is, split sentence into words, reverse it, and join the sentence again.

Conor O'Brien

Posted 2017-05-17T15:00:46.050

Reputation: 36 228

1

Java 8, 62 bytes

s->{String r="";for(String x:s.split(" "))r=x+" "+r;return r;}

Try it here.

Java 7, 77 bytes

String c(String s){String r="";for(String x:s.split(" "))r=x+" "+r;return r;}

Try it here.

Kevin Cruijssen

Posted 2017-05-17T15:00:46.050

Reputation: 67 575

1

Gema, 29 characters

<W><s>=@set{o;$1 ${o;}}
\Z=$o

Sample run:

bash-4.4$ gema '<W><s>=@set{o;$1 ${o;}};\Z=$o' <<< 'Man bites dog'
dog bites Man 

manatwork

Posted 2017-05-17T15:00:46.050

Reputation: 17 865

1

Java 8, 53 57 bytes

Lambda + Stream API

s->Stream.of(s.split(" ")).reduce("",(a,b)->b+" "+a)

Following Selim suggestion, we just dropped 4 bytes

user902383

Posted 2017-05-17T15:00:46.050

Reputation: 1 360

1Save 4 bytes by using Stream.of instead of Arrays.stream :--) – Selim – 2017-05-19T09:03:48.910

1

Perl 6, 14 bytes

{~[R,] .words}

Try it

Expanded:

{              # lambda with implicit param $_

  ~            # stringify following (joins a list using spaces)

   [R,]        # reduce the following using the Reverse meta operator

        .words # call the words method on $_
}

Brad Gilbert b2gills

Posted 2017-05-17T15:00:46.050

Reputation: 12 713

1

Vim, 20 bytes

:s/ /\r/g|g/^/m0<cr>vGJ

This is shorter than the other vim answer.

Try it online!

James

Posted 2017-05-17T15:00:46.050

Reputation: 54 537

1

Pyth, 3 bytes

_cw

My first Pyth answer, one byte shorter than @notjagan's answer!

Explained:

 cw # Split the input by space (same as Python's string.split())
_   # Reverses the array
    # Pyth prints implicitly.

OldBunny2800

Posted 2017-05-17T15:00:46.050

Reputation: 1 379

0

TAESGL, 7 bytes

ĴS)Ř)ĴS

Interpreter

Explanation

 ĴS)Ř)ĴS
AĴS)        implicit input "A" split at " "
    Ř)      reversed
      ĴS    joined with " "

Tom

Posted 2017-05-17T15:00:46.050

Reputation: 3 078

0

Cheddar, 26 bytes

3 bytes thanks to Conor O'Brien

@.split(" ").rev.join(" ")

Try it online!

Leaky Nun

Posted 2017-05-17T15:00:46.050

Reputation: 45 011

26 bytes – Conor O'Brien – 2017-05-18T00:11:04.967

0

AWK, 30 28 bytes

{for(;++i<=NF;)s=$i" "s}$0=s

Try it online!

Thanks, manatwork, for catching my needless fluff. :)

Robert Benson

Posted 2017-05-17T15:00:46.050

Reputation: 1 339

Not specified by the challenge, but hopefully there is no need to handle empty input, so {for(;++i<=NF;)s=$i" "s}$0=s. – manatwork – 2017-05-18T08:53:58.327

Trying to remember what was going on 21 hours ago... failing. Good catch @manatwork . – Robert Benson – 2017-05-18T13:47:43.343

0

Lua, 66 42 bytes

for i=#...,1,-1 do
io.write(arg[i],' ')end

Try it online!

Felipe Nardi Batista

Posted 2017-05-17T15:00:46.050

Reputation: 2 345

0

Ruby, 23+1 = 24 bytes bytes

Uses the -p flag.

$_=$_.split.reverse*' '

Try it online!

Value Ink

Posted 2017-05-17T15:00:46.050

Reputation: 10 608

0

Stacked, 17 bytes

' 'split rev' '#`

Try it online!

#` is "join".

Conor O'Brien

Posted 2017-05-17T15:00:46.050

Reputation: 36 228

0

MATL, 5 bytes

YbPZc

Try it at MATL Online!

Explanation

    % Implicitly grab input as a string
Yb  % Split it on all of the spaces, yielding a cell array of words
P   % Flip this array
Zc  % Join these words back together with spaces
    % Implicitly display the result

Suever

Posted 2017-05-17T15:00:46.050

Reputation: 10 257

0

Scala, 37 bytes

s=>s.split(" ").reverse.mkString(" ")

Try it here.

Kevin Cruijssen

Posted 2017-05-17T15:00:46.050

Reputation: 67 575

0

jq, 27 characters

(23 characters code + 4 characters command line options)

./" "|reverse|join(" ")

Sample run:

bash-4.4$ jq -Rr './" "|reverse|join(" ")' <<< 'Man bites dog'
dog bites Man

On-line test

manatwork

Posted 2017-05-17T15:00:46.050

Reputation: 17 865

0

Vim, 49 42 bytes

:s/.*/\=join(reverse(split(submatch(0))))/

Thank you to @manatwork for feedback

Hex

Posted 2017-05-17T15:00:46.050

Reputation: 11

Does this require a specific version? Vim 8.0 gives me “E486: Pattern not found: %V.*%V.” – manatwork – 2017-05-18T11:23:10.453

BTW, it seems to work fine without those \%V things: :s/.*/\=join(reverse(split(submatch(0))))/. – manatwork – 2017-05-18T11:33:55.433

@manatwork it works for vim 8 only I did it with visual select aka %V for no practical reason.. my bad :D Thank you for the feed back I will update the answer – Hex – 2017-05-22T09:16:02.643

0

Ruby, 27 24 bytes

thanks to @manatwork

->a{a.split.reverse*" "}

marmeladze

Posted 2017-05-17T15:00:46.050

Reputation: 227

Same with shorter syntax: ->a{a.split.reverse*" "} – manatwork – 2017-05-18T11:25:40.730

0

Swift, 116 bytes

var r:(String)->String={return $0.characters.split(separator:" ").map(String.init).reversed().joined(separator:" ")}

You can try it here

Caleb Kleveter

Posted 2017-05-17T15:00:46.050

Reputation: 647

0

Clojure(script), 57 bytes

#(apply str(interpose" "(reverse(re-seq #"[a-zA-Z]+"%))))

madstap

Posted 2017-05-17T15:00:46.050

Reputation: 141

0

J-uby, 23 bytes

:split|:reverse|~:*&' '

Explanation

:split   # split by spaces
|        # then
:reverse # reverse 
|        # then
~:*&' '  # join with spaces

Cyoce

Posted 2017-05-17T15:00:46.050

Reputation: 2 690

0

tcl, 18

puts [lreverse $S]

demo

sergiol

Posted 2017-05-17T15:00:46.050

Reputation: 3 055

0

tcl, 11

lreverse ""
          ^
          |
          Put the string you want to test here between the ""

Can be tested on http://www.tutorialspoint.com/execute_tcl_online.php starting the tcl interpreter by typing tclsh. Then type

lreverse "Man bites dog"

%

lreverse "The quick brown fox jumps over the lazy dog"

%

lreverse "Hello world"

sergiol

Posted 2017-05-17T15:00:46.050

Reputation: 3 055

0

Wren, 40 bytes

Fn.new{|a|a.split(" ")[-1..0].join(" ")}

Try it online!

Explanation

Fn.new{|a|                             } // Anonymous function with the parameter a
          a.split(" ")                   // Split on spaces
                      [-1..0]            // Reverse the array
                             .join(" ")  // Join the array with spaces

user85052

Posted 2017-05-17T15:00:46.050

Reputation: