32
\$\begingroup\$

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.

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Related. \$\endgroup\$ May 17, 2017 at 15:02
  • 1
    \$\begingroup\$ Can we take the input as a list of words? (i.e. ['man', 'bites', 'dog']) \$\endgroup\$
    – Riker
    May 17, 2017 at 15:18
  • 3
    \$\begingroup\$ Can the output have trailing whitespace? \$\endgroup\$ May 17, 2017 at 16:13
  • \$\begingroup\$ misleading title, we're actually reversing a sentence, not the words... \$\endgroup\$
    – roblogic
    Aug 14, 2023 at 17:34

52 Answers 52

11
\$\begingroup\$

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 (^).

\$\endgroup\$
2
  • \$\begingroup\$ Never used Retina but why do you need the 0$? Can't you just reverse it? \$\endgroup\$ May 23, 2017 at 23:19
  • \$\begingroup\$ @RandomUser sort mode (O) is currently the only mode that has this reverse option. \$\endgroup\$ May 24, 2017 at 0:02
10
\$\begingroup\$

Haskell, 21 bytes

unwords.reverse.words

Try it online!

\$\endgroup\$
10
\$\begingroup\$

Python 3, 29 bytes

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

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ What does the * do? \$\endgroup\$
    – AAM111
    May 28, 2017 at 23:38
  • \$\begingroup\$ @OldBunny2800 unpack the list \$\endgroup\$
    – Rod
    May 29, 2017 at 2:41
  • \$\begingroup\$ Ahh. Makes sense. \$\endgroup\$
    – AAM111
    May 29, 2017 at 3:03
8
\$\begingroup\$

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.

\$\endgroup\$
2
  • 3
    \$\begingroup\$ Congrats on 50k!! Your turn today :-) \$\endgroup\$
    – Luis Mendo
    May 18, 2017 at 17:02
  • \$\begingroup\$ @LuisMendo Thanks! \$\endgroup\$ May 18, 2017 at 17:02
7
\$\begingroup\$

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>

\$\endgroup\$
3
  • 1
    \$\begingroup\$ It'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 \$\endgroup\$ May 17, 2017 at 15:59
  • \$\begingroup\$ Side note: In C# if you pass nothing to Split it splits on whitespace by default, can you do the same here? \$\endgroup\$ May 17, 2017 at 16:00
  • 1
    \$\begingroup\$ Unfortunately 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. \$\endgroup\$
    – Shaggy
    May 17, 2017 at 18:25
7
\$\begingroup\$

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

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

Jelly, 3 bytes

ḲṚK

Try it online!

Explanation:

Ḳ     Splits the input at spaces
Ṛ     Reverses the array
K     Joins the array, using spaces
\$\endgroup\$
1
6
\$\begingroup\$

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!

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

C#, 58 bytes

using System.Linq;s=>string.Join(" ",s.Split().Reverse());
\$\endgroup\$
4
\$\begingroup\$

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"); }
\$\endgroup\$
2
  • \$\begingroup\$ That's sneaky, using the shell to do the word-splitting for you! Clever abuse of the rules. \$\endgroup\$ Jul 9, 2023 at 12:34
  • \$\begingroup\$ Second one only works if your compiler puts strings into writable storage and has non-printing character immediately preceding. It segfaults here. \$\endgroup\$ Jul 9, 2023 at 13:26
3
\$\begingroup\$

05AB1E, 4 bytes

#Rðý

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

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ I see unicode, is it reallly 4 bytes? \$\endgroup\$ May 18, 2017 at 4:38
  • \$\begingroup\$ Yes, 05AB1E uses a custom codepage \$\endgroup\$
    – kalsowerus
    May 18, 2017 at 7:34
  • \$\begingroup\$ #R¸» alternate 4-byte solution :P. \$\endgroup\$ Jun 28, 2017 at 19:17
3
\$\begingroup\$

GNU Make, 62 bytes

$(if $1,$(call $0,$(wordlist 2,$(words $1),$1)) $(word 1,$1),)
\$\endgroup\$
3
\$\begingroup\$

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
]
\$\endgroup\$
3
\$\begingroup\$

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

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

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.

\$\endgroup\$
6
  • 2
    \$\begingroup\$ Thanks 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) \$\endgroup\$ May 18, 2017 at 12:36
  • \$\begingroup\$ Nice! you can save a byte if you use the -S flag. \$\endgroup\$
    – Oliver
    May 18, 2017 at 14:40
  • \$\begingroup\$ I count 2 bytes, @obarakon. Unless the flag is included in the byte count, in which case that would be 4 byes, no? \$\endgroup\$
    – Shaggy
    May 18, 2017 at 14:42
  • \$\begingroup\$ @Shaggy Each flag counts as one byte. So -S would be +1 onto your total byte count. \$\endgroup\$
    – Oliver
    May 18, 2017 at 14:43
  • \$\begingroup\$ Ah, I see. Is that a PPCG thing or a Japt thing? \$\endgroup\$
    – Shaggy
    May 18, 2017 at 14:44
2
\$\begingroup\$

Python 2, 34 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ Out-golfed. >_> Well... the other one only works in Python 3... \$\endgroup\$ May 17, 2017 at 15:47
2
\$\begingroup\$

Pyth, 4 bytes

jd_c

Try it online!

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

PHP, 47 Bytes

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

Try it online!

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

k, 9 bytes

" "/|" "\

Try it in your browser of the web variety!

     " "\ /split on spaces
    |     /reverse
" "/      /join with spaces
\$\endgroup\$
2
\$\begingroup\$

J-uby, 23 bytes

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

Explanation

:split   # split by spaces
|        # then
:reverse # reverse 
|        # then
~:*&' '  # join with spaces
\$\endgroup\$
2
\$\begingroup\$

Mathematica, 35 bytes

StringRiffle@Reverse@StringSplit@#&

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ StringSplit[#] splits on whitespace automatically, so you don't need to specify the " ". \$\endgroup\$
    – Not a tree
    May 20, 2017 at 0:34
  • 2
    \$\begingroup\$ correct! -5 bytes! \$\endgroup\$
    – ZaMoC
    May 20, 2017 at 0:39
  • \$\begingroup\$ Ooh, and I think you can save another byte using function composition: StringRiffle@*Reverse@*StringSplit (call it like StringRiffle@*Reverse@*StringSplit@"hello world") \$\endgroup\$
    – Not a tree
    May 20, 2017 at 0:56
2
\$\begingroup\$

Vim, 20 bytes

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

This is shorter than the other vim answer.

Try it online!

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

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 */
\$\endgroup\$
1
  • \$\begingroup\$ split uses space as the default separator, so split() is shorter than (_/" ")(). \$\endgroup\$
    – fergusq
    May 19, 2017 at 16:45
2
\$\begingroup\$

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.
\$\endgroup\$
2
\$\begingroup\$

Zsh, 13 bytes

echo ${(Oa)@}

Try it online!

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

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.
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

TAESGL, 7 bytes

ĴS)Ř)ĴS

Interpreter

Explanation

 ĴS)Ř)ĴS
AĴS)        implicit input "A" split at " "
    Ř)      reversed
      ĴS    joined with " "
\$\endgroup\$
1
\$\begingroup\$

J, 6 bytes

|.&.;:

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

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

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

Your Answer

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