30
\$\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\$
  • 1
    \$\begingroup\$ Related. \$\endgroup\$ – Martin Ender May 17 '17 at 15:02
  • 1
    \$\begingroup\$ Can we take the input as a list of words? (i.e. ['man', 'bites', 'dog']) \$\endgroup\$ – Rɪᴋᴇʀ May 17 '17 at 15:18
  • 3
    \$\begingroup\$ Can the output have trailing whitespace? \$\endgroup\$ – Digital Trauma May 17 '17 at 16:13

46 Answers 46

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\$
  • \$\begingroup\$ Never used Retina but why do you need the 0$? Can't you just reverse it? \$\endgroup\$ – caird coinheringaahing May 23 '17 at 23:19
  • \$\begingroup\$ @RandomUser sort mode (O) is currently the only mode that has this reverse option. \$\endgroup\$ – Martin Ender May 24 '17 at 0:02
9
\$\begingroup\$

Haskell, 21 bytes

unwords.reverse.words

Try it online!

\$\endgroup\$
9
\$\begingroup\$

Python 3, 29 bytes

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

Try it online!

\$\endgroup\$
  • \$\begingroup\$ What does the * do? \$\endgroup\$ – OldBunny2800 May 28 '17 at 23:38
  • \$\begingroup\$ @OldBunny2800 unpack the list \$\endgroup\$ – Rod May 29 '17 at 2:41
  • \$\begingroup\$ Ahh. Makes sense. \$\endgroup\$ – OldBunny2800 May 29 '17 at 3:03
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\$
  • 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\$ – TheLethalCoder May 17 '17 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\$ – TheLethalCoder May 17 '17 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 '17 at 18:25
7
\$\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
    \$\begingroup\$ Congrats on 50k!! Your turn today :-) \$\endgroup\$ – Luis Mendo May 18 '17 at 17:02
  • \$\begingroup\$ @LuisMendo Thanks! \$\endgroup\$ – Digital Trauma May 18 '17 at 17:02
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\$
6
\$\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\$
5
\$\begingroup\$

Jelly, 3 bytes

ḲṚK

Try it online!

Explanation:

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

C#, 58 bytes

using System.Linq;s=>string.Join(" ",s.Split().Reverse());
\$\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\$

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\$
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\$
  • 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\$ – ETHproductions May 18 '17 at 12:36
  • \$\begingroup\$ Nice! you can save a byte if you use the -S flag. \$\endgroup\$ – Oliver May 18 '17 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 '17 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 '17 at 14:43
  • \$\begingroup\$ Ah, I see. Is that a PPCG thing or a Japt thing? \$\endgroup\$ – Shaggy May 18 '17 at 14:44
2
\$\begingroup\$

Python 2, 34 bytes

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

Try it online!

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

Pyth, 4 bytes

jd_c

Try it online!

\$\endgroup\$
2
\$\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\$
  • \$\begingroup\$ I see unicode, is it reallly 4 bytes? \$\endgroup\$ – val May 18 '17 at 4:38
  • \$\begingroup\$ Yes, 05AB1E uses a custom codepage \$\endgroup\$ – kalsowerus May 18 '17 at 7:34
  • \$\begingroup\$ #R¸» alternate 4-byte solution :P. \$\endgroup\$ – Magic Octopus Urn Jun 28 '17 at 19:17
2
\$\begingroup\$

PHP, 47 Bytes

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

Try it online!

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

GNU Make, 62 bytes

$(if $1,$(call $0,$(wordlist 2,$(words $1),$1)) $(word 1,$1),)
\$\endgroup\$
2
\$\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\$
2
\$\begingroup\$

Mathematica, 35 bytes

StringRiffle@Reverse@StringSplit@#&

Try it online!

\$\endgroup\$
  • \$\begingroup\$ StringSplit[#] splits on whitespace automatically, so you don't need to specify the " ". \$\endgroup\$ – Not a tree May 20 '17 at 0:34
  • 2
    \$\begingroup\$ correct! -5 bytes! \$\endgroup\$ – J42161217 May 20 '17 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 '17 at 0:56
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\$
  • \$\begingroup\$ split uses space as the default separator, so split() is shorter than (_/" ")(). \$\endgroup\$ – fergusq May 19 '17 at 16:45
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\$

k, 9 bytes

" "/|" "\

Try it in your browser of the web variety!

     " "\ /split on spaces
    |     /reverse
" "/      /join with spaces
\$\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\$
1
\$\begingroup\$

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.

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

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

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

\$\endgroup\$
  • 1
    \$\begingroup\$ Save 4 bytes by using Stream.of instead of Arrays.stream :--) \$\endgroup\$ – Selim May 19 '17 at 9:03
1
\$\begingroup\$

Vim, 20 bytes

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

This is shorter than the other vim answer.

Try it online!

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy