Reverse words in a string: Difference between revisions
Added EchoLisp |
Added EchoLisp |
||
Line 586: | Line 586: | ||
=={{header|EchoLisp}}== |
=={{header|EchoLisp}}== |
||
Using a here-string input : |
|||
<lang scheme> |
<lang scheme> |
||
(define S #<< |
(define S #<< |
||
Line 603: | Line 604: | ||
(for/list ((line (string-split S "\n"))) |
(for/list ((line (string-split S "\n"))) |
||
(string-join (reverse (string-split line " ")) " "))) |
(string-join (reverse (string-split line " ")) " "))) |
||
</lang> |
|||
{{out}} |
|||
<pre> |
|||
------------ Fire and Ice ---------- |
------------ Fire and Ice ---------- |
||
Line 614: | Line 617: | ||
----------------------- Robert Frost |
----------------------- Robert Frost |
||
</ |
</pre> |
||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
Revision as of 15:06, 21 September 2015
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
The task is to reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.
- Example: “Hey you, Bub!” would be shown reversed as: “Bub! you, Hey”
Tokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation forms part of the word within which it is located and should not be modified. You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space. Some strings have no tokens, so an empty string (or one just containing spaces) would be the result. Display the strings in order (1st, 2nd, 3rd, ···), and one string per line. (You can consider the ten strings as ten lines, and the tokens as words.)
- Input data
(ten lines within the box) line ╔════════════════════════════════════════╗ 1 ║ ---------- Ice and Fire ------------ ║ 2 ║ ║ ◄─── a blank line here. 3 ║ fire, in end will world the say Some ║ 4 ║ ice. in say Some ║ 5 ║ desire of tasted I've what From ║ 6 ║ fire. favor who those with hold I ║ 7 ║ ║ ◄─── a blank line here. 8 ║ ... elided paragraph last ... ║ 9 ║ ║ ◄─── a blank line here. 10 ║ Frost Robert ----------------------- ║ ╚════════════════════════════════════════╝
Ada
Simple_Parse
To Split a string into words, we define a Package "Simple_Parse". This package is also used for the Phrase Reversal Task [[1]].
<lang Ada>package Simple_Parse is
-- a very simplistic parser, useful to split a string into words function Next_Word(S: String; Point: in out Positive)
return String;
-- a "word" is a sequence of non-space characters -- if S(Point .. S'Last) holds at least one word W -- then Next_Word increments Point by len(W) and returns W. -- else Next_Word sets Point to S'Last+1 and returns ""
end Simple_Parse;</lang>
The implementation of "Simple_Parse":
<lang Ada>package body Simple_Parse is
function Next_Word(S: String; Point: in out Positive) return String is Start: Positive := Point; Stop: Natural; begin while Start <= S'Last and then S(Start) = ' ' loop
Start := Start + 1;
end loop; -- now S(Start) is the first non-space,
-- or Start = S'Last+1 if S is empty or space-only
Stop := Start-1; -- now S(Start .. Stop) = "" while Stop < S'Last and then S(Stop+1) /= ' ' loop
Stop := Stop + 1;
end loop; -- now S(Stop+1) is the first sopace after Start
-- or Stop = S'Last if there is no such space
Point := Stop+1; return S(Start .. Stop); end Next_Word;
end Simple_Parse;</lang>
Main Program
<lang Ada>with Ada.Text_IO, Simple_Parse;
procedure Reverse_Words is
function Reverse_Words(S: String) return String is Cursor: Positive := S'First; Word: String := Simple_Parse.Next_Word(S, Cursor); begin if Word = "" then return ""; else return Reverse_Words(S(Cursor .. S'Last)) & " " & Word; end if; end Reverse_Words; use Ada.Text_IO;
begin
while not End_Of_File loop Put_Line(Reverse_Words(Get_Line)); -- poem is read from standard input end loop;
end Reverse_Words;</lang>
Aime
<lang aime>integer i, j, s; list l, x; data b; file f;
l_bill(l, 0,
"---------- Ice and Fire ------------", "", "fire, in end will world the say Some", "ice. in say Some", "desire of tasted I've what From", "fire. favor who those with hold I", "", "... elided paragraph last ...", "", "Frost Robert -----------------------");
i = -l_length(l); while (i) {
b_cast(b, l[i]); f_b_affix(f, b); f_list(f, x, 0); j = l_length(x); s = 0; while (j) { o_space(s); s = 1; o_text(x[j -= 1]); } o_newline(); i += 1;
}</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Applesoft BASIC
<lang ApplesoftBasic>100 DATA"---------- ICE AND FIRE ------------" 110 DATA" " 120 DATA"FIRE, IN END WILL WORLD THE SAY SOME" 130 DATA"ICE. IN SAY SOME " 140 DATA"DESIRE OF TASTED I'VE WHAT FROM " 150 DATA"FIRE. FAVOR WHO THOSE WITH HOLD I " 160 DATA" " 170 DATA"... ELIDED PARAGRAPH LAST ... " 180 DATA" " 190 DATA"FROST ROBERT -----------------------"
200 FOR L = 1 TO 10 210 READ T$ 220 I = LEN(T$) 240 IF I THEN GOSUB 300 : PRINT W$; : IF I THEN PRINT " "; : GOTO 240 250 PRINT 260 NEXT L 270 END
300 W$ = "" 310 FOR I = I TO 1 STEP -1 320 IF MID$(T$, I, 1) = " " THEN NEXT I : RETURN 330 FOR I = I TO 1 STEP -1 340 C$ = MID$(T$, I, 1) 350 IF C$ <> " " THEN W$ = C$ + W$ : NEXT I 360 RETURN </lang>
AutoHotkey
<lang AutoHotkey>Data := " (Join`r`n
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ----------------------- )"
Loop, Parse, Data, `n, `r { Loop, Parse, A_LoopField, % A_Space Line := A_LoopField " " Line Output .= Line "`n", Line := "" } MsgBox, % RTrim(Output, "`n")</lang>
AWK
<lang AWK>
- syntax: GAWK -f REVERSE_WORDS_IN_A_STRING.AWK
BEGIN {
text[++i] = "---------- Ice and Fire ------------" text[++i] = "" text[++i] = "fire, in end will world the say Some" text[++i] = "ice. in say Some" text[++i] = "desire of tasted I've what From" text[++i] = "fire. favor who those with hold I" text[++i] = "" text[++i] = "... elided paragraph last ..." text[++i] = "" text[++i] = "Frost Robert -----------------------" leng = i for (i=1; i<=leng; i++) { n = split(text[i],arr," ") for (j=n; j>0; j--) { printf("%s ",arr[j]) } printf("\n") } exit(0)
} </lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Batch File
<lang dos>@echo off
- The Main Thing...
cls echo. call :reverse "---------- Ice and Fire ------------" call :reverse call :reverse "fire, in end will world the say Some" call :reverse "ice. in say Some" call :reverse "desire of tasted I've what From" call :reverse "fire. favor who those with hold I" call :reverse call :reverse "... elided paragraph last ..." call :reverse call :reverse "Frost Robert -----------------------" echo. pause>nul exit
- /The Main Thing...
- The Function...
- reverse
set reversed=&set word=&set str=%1
- process
for /f "tokens=1,*" %%A in (%str%) do ( set str=%%B set word=%%A ) set reversed=%word% %reversed% set str="%str%" if not %str%=="" goto process
echo.%reversed% goto :EOF
- /The Function...</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
BBC BASIC
<lang bbcbasic> PRINT FNreverse("---------- Ice and Fire ------------")\
\ 'FNreverse("")\ \ 'FNreverse("fire, in end will world the say Some")\ \ 'FNreverse("ice. in say Some")\ \ 'FNreverse("desire of tasted I've what From")\ \ 'FNreverse("fire. favor who those with hold I")\ \ 'FNreverse("")\ \ 'FNreverse("... elided paragraph last ...")\ \ 'FNreverse("")\ \ 'FNreverse("Frost Robert -----------------------") END
DEF FNreverse(s$) LOCAL sp% sp%=INSTR(s$," ") IF sp% THEN =FNreverse(MID$(s$,sp%+1))+" "+LEFT$(s$,sp%-1) ELSE =s$</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Bracmat
<lang bracmat>("---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------"
: ?text
& ( reverse
= token tokens reversed . :?tokens & whl ' ( @( !arg : ?token (" "|\t|\r) ?arg ) & !tokens !token:?tokens ) & !tokens !arg:?tokens & :?reversed & whl ' ( !tokens:%?token %?tokens & " " !token !reversed:?reversed ) & !tokens !reversed:?reversed & str$!reversed )
& :?output & whl
' ( @(!text:?line \n ?text) & !output reverse$!line \n:?output )
& !output reverse$!text:?output & out$str$!output );</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Burlesque
<lang blsq> blsq ) "It is not raining"wd<-wd "raining not is It" blsq ) "ice. in say some"wd<-wd "some say in ice." </lang>
C
<lang c>#include <stdio.h>
- include <ctype.h>
void rev_print(char *s, int n) {
for (; *s && isspace(*s); s++); if (*s) { char *e; for (e = s; *e && !isspace(*e); e++); rev_print(e, 0); printf("%.*s%s", (int)(e - s), s, " " + n); } if (n) putchar('\n');
}
int main(void) {
char *s[] = { "---------- Ice and Fire ------------", " ", "fire, in end will world the say Some", "ice. in say Some ", "desire of tasted I've what From ", "fire. favor who those with hold I ", " ", "... elided paragraph last ... ", " ", "Frost Robert -----------------------", 0 }; int i; for (i = 0; s[i]; i++) rev_print(s[i], 1);
return 0;
}</lang> Output is the same as everyone else's.
C++
<lang cpp>
- include <algorithm>
- include <functional>
- include <string>
- include <iostream>
- include <vector>
//code for a C++11 compliant compiler template <class BidirectionalIterator, class T> void block_reverse_cpp11(BidirectionalIterator first, BidirectionalIterator last, T const& separator) {
std::reverse(first, last); auto block_last = first; do { using std::placeholders::_1; auto block_first = std::find_if_not(block_last, last, std::bind(std::equal_to<T>(),_1, separator)); block_last = std::find(block_first, last, separator); std::reverse(block_first, block_last); } while(block_last != last);
}
//code for a C++03 compliant compiler template <class BidirectionalIterator, class T> void block_reverse_cpp03(BidirectionalIterator first, BidirectionalIterator last, T const& separator) {
std::reverse(first, last); BidirectionalIterator block_last = first; do { BidirectionalIterator block_first = std::find_if(block_last, last, std::bind2nd(std::not_equal_to<T>(), separator)); block_last = std::find(block_first, last, separator); std::reverse(block_first, block_last); } while(block_last != last);
}
int main() {
std::string str1[] = { "---------- Ice and Fire ------------", "", "fire, in end will world the say Some", "ice. in say Some", "desire of tasted I've what From", "fire. favor who those with hold I", "", "... elided paragraph last ...", "", "Frost Robert -----------------------" };
std::for_each(begin(str1), end(str1), [](std::string& s){ block_reverse_cpp11(begin(s), end(s), ' '); std::cout << s << std::endl; }); std::for_each(begin(str1), end(str1), [](std::string& s){ block_reverse_cpp03(begin(s), end(s), ' '); std::cout << s << std::endl; });
return 0;
} </lang>
Alternate version
<lang cpp>
- include <string>
- include <iostream>
using namespace std;
string invertString( string s ) {
string st, tmp; for( string::iterator it = s.begin(); it != s.end(); it++ ) { if( *it != 32 ) tmp += *it; else { st = " " + tmp + st; tmp.clear(); } } return tmp + st;
}
int main( int argc, char* argv[] ) {
string str[] = { "---------- Ice and Fire ------------", "", "fire, in end will world the say Some", "ice. in say Some", "desire of tasted I've what From", "fire. favor who those with hold I", "", "... elided paragraph last ...", "", "Frost Robert -----------------------" }; for( int i = 0; i < 10; i++ ) cout << invertString( str[i] ) << "\n"; cout << "\n"; return system( "pause" );
} </lang>
Clojure
<lang clojure> (def poem
"---------- Ice and Fire ------------ fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... Frost Robert -----------------------")
(doall
(map println (map #(apply str (interpose " " (reverse (re-seq #"[^\s]+" %)))) (clojure.string/split poem #"\n"))))
</lang> Output is the same as everyone else's.
Common Lisp
<lang lisp>(defun split-and-reverse (str)
(labels ((iter (s lst) (let ((s2 (string-trim '(#\space) s))) (if s2 (let ((word-end (position #\space s2))) (if (and word-end (< (1+ word-end) (length s2))) (iter (subseq s2 (1+ word-end)) (cons (subseq s2 0 word-end) lst)) (cons s2 lst))) lst)))) (iter str NIL)))
(defparameter *poem*
"---------- Ice and Fire ------------ fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... Frost Robert -----------------------")
(with-input-from-string (s *poem*)
(loop for line = (read-line s NIL) while line do (format t "~{~a~#[~:; ~]~}~%" (split-and-reverse line))))</lang>
Output is the same as everyone else's.
D
<lang d>void main() {
import std.stdio, std.string, std.range, std.algorithm;
immutable text =
"---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------";
writefln("%(%-(%s %)\n%)", text.splitLines.map!(r => r.split.retro));
}</lang> The output is the same as the Python entry.
EchoLisp
Using a here-string input : <lang scheme> (define S #<<
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ----------------------- >>#)
(for-each writeln
(for/list ((line (string-split S "\n"))) (string-join (reverse (string-split line " ")) " ")))
</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Elixir
<lang elixir>defmodule RC do
def reverse_words(txt) do txt |> String.split("\n") # split lines |> Enum.map(&( # in each line &1 |> String.split # split words |> Enum.reverse # reverse words |> Enum.join(" "))) # rejoin words |> Enum.join("\n") # rejoin lines end
end</lang> Usage: <lang elixir>txt = """
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ----------------------- """
IO.puts RC.reverse_words(txt)</lang>
Emacs Lisp
<lang Emacs Lisp> (defun reverse-words (line)
(insert (format "%s\n" (mapconcat 'identity (reverse (split-string line)) " "))))
(defun reverse-lines (lines)
(mapcar 'reverse-words lines))
(reverse-lines
'("---------- Ice and Fire ------------" "" "fire, in end will world the say Some" "ice. in say Some" "desire of tasted I've what From" "fire. favor who those with hold I" "" "... elided paragraph last ..." "" "Frost Robert ----------------------- "))
</lang> Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Gema
<lang gema>\L<G> =@{$2} $1</lang>
Go
<lang go>package main
import (
"fmt" "strings"
)
// a number of strings var n = []string{
"---------- Ice and Fire ------------", " ", "fire, in end will world the say Some", "ice. in say Some ", "desire of tasted I've what From ", "fire. favor who those with hold I ", " ", "... elided paragraph last ... ", " ", "Frost Robert -----------------------",
}
func main() {
for i, s := range n { t := strings.Fields(s) // tokenize // reverse last := len(t) - 1 for j, k := range t[:len(t)/2] { t[j], t[last-j] = t[last-j], k } n[i] = strings.Join(t, " ") } // display result for _, t := range n { fmt.Println(t) }
}</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Groovy
<lang groovy>def text = new StringBuilder()
.append('---------- Ice and Fire ------------\n') .append(' \n') .append('fire, in end will world the say Some\n') .append('ice. in say Some \n') .append('desire of tasted I\'ve what From \n') .append('fire. favor who those with hold I \n') .append(' \n') .append('... elided paragraph last ... \n') .append(' \n') .append('Frost Robert -----------------------\n').toString()
text.eachLine { line ->
println "$line --> ${line.split(' ').reverse().join(' ')}"
}</lang>
- Output:
---------- Ice and Fire ------------ --> ------------ Fire and Ice ---------- --> fire, in end will world the say Some --> Some say the world will end in fire, ice. in say Some --> Some say in ice. desire of tasted I've what From --> From what I've tasted of desire fire. favor who those with hold I --> I hold with those who favor fire. --> ... elided paragraph last ... --> ... last paragraph elided ... --> Frost Robert ----------------------- --> ----------------------- Robert Frost
Haskell
<lang Haskell> revstr :: String -> String revstr = unwords . reverse . words -- point-free style --equivalent: --revstr s = unwords (reverse (words s))
revtext :: String -> String revtext = unlines . map revstr . lines -- applies revstr to each line independently
test = revtext "---------- Ice and Fire ------------\n\
\\n\ \fire, in end will world the say Some\n\ \ice. in say Some\n\ \desire of tasted I've what From\n\ \fire. favor who those with hold I\n\ \\n\ \... elided paragraph last ...\n\ \\n\ \Frost Robert -----------------------\n" --multiline string notation requires \ at end and start of lines, and \n to be manually input
</lang> unwords, reverse, words, unlines, map and lines are built-in functions, all available at GHC's Prelude. For better visualization, use "putStr test"
Icon and Unicon
Works in both languages: <lang unicon>procedure main()
every write(rWords(&input))
end
procedure rWords(f)
every !f ? { every (s := "") := genWords() || s suspend s }
end
procedure genWords()
while w := 1(tab(upto(" \t")),tab(many(" \t"))) || " " do suspend w
end</lang>
- Output:
for test file
->rw <rw.in ------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost ->
J
Treated interactively:
<lang J> ([:;@|.[:<;.1 ' ',]);._2]0 :0
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
)
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
</lang>
Java
<lang java>public class ReverseWords {
static final String[] lines = { " ----------- Ice and Fire ----------- ", " ", " fire, in end will world the say Some ", " ice. in say Some ", " desire of tasted I've what From ", " fire. favor who those with hold I ", " ", " ... elided paragraph last ... ", " Frost Robert ----------------------- "};
public static void main(String[] args) { for (String line : lines) { String[] words = line.split("\\s"); for (int i = words.length - 1; i >= 0; i--) System.out.printf("%s ", words[i]); System.out.println(); } }
}</lang>
<lang java>package string;
import static java.util.Arrays.stream;
public interface ReverseWords {
public static final String[] LINES = { " ----------- Ice and Fire ----------- ", " ", " fire, in end will world the say Some ", " ice. in say Some ", " desire of tasted I've what From ", " fire. favor who those with hold I ", " ", " ... elided paragraph last ... ", " Frost Robert ----------------------- " };
public static String[] reverseWords(String[] lines) { return stream(lines) .parallel() .map(l -> l.split("\\s")) .map(ws -> stream(ws) .parallel() .map(w -> " " + w) .reduce( "", (w1, w2) -> w2 + w1 ) ) .toArray(String[]::new) ; } public static void main(String... arguments) { stream(reverseWords(LINES)) .forEach(System.out::println) ; }
}</lang>
- Output:
----------- Fire and Ice ----------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
JavaScript
<lang javascript> function reverseString(s) {
return s.split('\n').map(function(line) { return line.split(/\s/).reverse().join(' '); }).join('\n');
} </lang>
jq
<lang jq>split("[ \t\n\r]+") | reverse | join(" ")</lang> This solution requires a version of jq with regex support for split.
The following example assumes the above line is in a file named reverse_words.jq and that the input text is in a file named IceAndFire.txt. The -r option instructs jq to read the input file as strings, line by line.<lang sh>$ jq -R -r -M -f reverse_words.jq IceAndFire.txt
Fire and Ice ----------
Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire.
... last paragraph elided ...
Robert Frost</lang>
Julia
<lang Julia>revstring (str) = join(reverse(split(str, " ")), " ")</lang>
- Output:
julia> revstring("Hey you, Bub!") "Bub! you, Hey" julia> s = IOBuffer( "---------- Ice and Fire ------------ fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... Frost Robert -----------------------") julia> for line in eachline(s) println(revstring(chomp(line))) end ------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Liberty BASIC
<lang lb> for i = 1 to 10
read string$ print reverse$(string$)
next end
function reverse$(string$)
token$="*" while token$<>"" i=i+1 token$ = word$(string$, i) output$=token$+" "+output$ wend reverse$ = trim$(output$)
end function
data "---------- Ice and Fire ------------" data "" data "fire, in end will world the say Some" data "ice. in say Some" data "desire of tasted I've what From" data "fire. favor who those with hold I" data "" data "... elided paragraph last ..." data "" data "Frost Robert -----------------------" </lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
LiveScript
<lang livescript> poem =
""" ---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ----------------------- """
reverse-words = (.split ' ') >> (.reverse!) >> (.join ' ') reverse-string = (.split '\n') >> (.map reverse-words) >> (.join '\n') reverse-string poem </lang>
Lua
(Note: The Wiki's syntax highlighting for Lua does not highlight the following valid string literal correctly, so the listing is split in two parts.)
s = [[---------- Ice and Fire ------------ fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... Frost Robert ----------------------- ]]
<lang lua>function table.reverse(a)
local res = {} for i = #a, 1, -1 do res[#res+1] = a[i] end return res
end
function splittokens(s)
local res = {} for w in s:gmatch("%S+") do res[#res+1] = w end return res
end
for line, nl in s:gmatch("([^\n]-)(\n)") do
print(table.concat(table.reverse(splittokens(line)), ' '))
end</lang>
Note: With the technique used here for splitting s
into lines (not part of the task) the last line will be gobbled up if it does not end with a newline.
Mathematica
<lang Mathematica>poem = "---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I ... elided paragraph last ... Frost Robert -----------------------";
lines = StringSplit[poem, "\n"]; wordArray = StringSplit[#] & @ lines ; reversedWordArray = Reverse[#] & /@ wordArray ; linesWithReversedWords =
StringJoin[Riffle[#, " "]] & /@ reversedWordArray;
finaloutput = StringJoin[Riffle[#, "\n"]] & @ linesWithReversedWords</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
MATLAB
<lang MATLAB>function testReverseWords
testStr = {'---------- Ice and Fire ------------' ; ... ; ... 'fire, in end will world the say Some' ; ... 'ice. in say Some' ; ... 'desire of tasted Ive what From' ; ... 'fire. favor who those with hold I' ; ... ; ... '... elided paragraph last ...' ; ... ; ... 'Frost Robert -----------------------' }; for k = 1:length(testStr) fprintf('%s\n', reverseWords(testStr{k})) end
end
function strOut = reverseWords(strIn)
strOut = strtrim(strIn); if ~isempty(strOut) % Could use strsplit() instead of textscan() in R2013a or later words = textscan(strOut, '%s'); words = words{1}; strOut = strtrim(sprintf('%s ', words{end:-1:1})); end
end</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Nim
<lang nim>import strutils
let text = """---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------"""
proc reversed*[T](a: openArray[T], first, last: int): seq[T] =
result = newSeq[T](last - first + 1) var x = first var y = last while x <= last: result[x] = a[y] dec(y) inc(x)
proc reversed*[T](a: openArray[T]): seq[T] =
reversed(a, 0, a.high)
for line in text.splitLines():
echo line.split(' ').reversed().join(" ")</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Objeck
<lang objeck>use Collection;
class Reverselines {
function : Main(args : String[]) ~ Nil { lines := List->New(); lines->AddBack("---------- Ice and Fire ------------"); lines->AddBack(""); lines->AddBack("fire, in end will world the say Some"); lines->AddBack("ice. in say Some"); lines->AddBack("desire of tasted I've what From"); lines->AddBack("fire. favor who those with hold I"); lines->AddBack(""); lines->AddBack("... elided paragraph last ..."); lines->AddBack(""); lines->AddBack("Frost Robert -----------------------"); lines->Rewind(); each(i : lines) { words := lines->Get()->As(String)->Split(" "); if(words <> Nil) { for(j := words->Size() - 1; j > -1; j-=1;) { IO.Console->Print(words[j])->Print(" "); }; }; IO.Console->PrintLine(); lines->Next(); }; }
}</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
OCaml
<lang ocaml>#load "str.cma" let input = ["---------- Ice and Fire ------------";
""; "fire, in end will world the say Some"; "ice. in say Some"; "desire of tasted I've what From"; "fire. favor who those with hold I"; ""; "... elided paragraph last ..."; ""; "Frost Robert -----------------------"];;
let splitted = List.map (Str.split (Str.regexp " ")) input in let reversed = List.map List.rev splitted in let final = List.map (String.concat " ") reversed in List.iter print_endline final;;</lang> Sample usage
$ ocaml reverse.ml ------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Oforth
<lang Oforth>func: revWords(s) {
s words reverse reduce(#[ " " swap + + ]) dup ifNull: [ drop "" ]
}
func: reverseWords {
revWords("---------- Ice and Fire ------------") println revWords(" ") println revWords("fire, in end will world the say Some") println revWords("ice. in say Some ") println revWords("desire of tasted I've what From ") println revWords("fire. favor who those with hold I ") println revWords(" ") println revWords("... elided paragraph last ... ") println revWords(" ") println revWords("Frost Robert -----------------------") println
}</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Perl
<lang perl>print join(" ", reverse split), "\n" for ; __DATA__
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ----------------------- </lang>
Perl 6
We'll read input from stdin <lang perl6>say .words.reverse for lines</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
PicoLisp
<lang PicoLisp> (in "FireIce.txt"
(until (eof) (prinl (glue " " (flip (split (line) " "))))))
</lang>
- Output:
Same as anybody else.
PL/I
<lang PL/I>rev: procedure options (main); /* 5 May 2014 */
declare (s, reverse) character (50) varying; declare (i, j) fixed binary; declare in file;
open file (in) title ('/REV-WRD.DAT,type(text),recsize(5> Nil) { for(j := words->Size() - 1; j > -1; j-=1;) { IO.Console->Print(words[j])->Print(" "); }; }; IO.Console->PrintLine(); lines->Next(); }; }
}0)');
do j = 1 to 10; get file (in) edit (s) (L); put skip list (trim(s));
reverse = ;
do while (length(s) > 0); s = trim(s); i = index(s, ' '); if i = 0 then if s ^= then i = length(s)+1; if i > 0 then reverse = substr(s, 1, i-1) || ' ' || reverse; if length(s) = i then s = ; else s = substr(s, i); end; put edit ('---> ', reverse) (col(40), 2 A); end;
end rev;</lang>
- Output:
---------- Ice and Fire ------------ ---> ------------ Fire and Ice ---------- ---> fire, in end will world the say Some ---> Some say the world will end in fire, ice. in say Some ---> Some say in ice. desire of tasted I've what From ---> From what I've tasted of desire fire. favor who those with hold I ---> I hold with those who favor fire. ---> ... elided paragraph last ... ---> ... last paragraph elided ... ---> Frost Robert ----------------------- ---> ----------------------- Robert Frost
PowerShell
<lang PowerShell> Function Reverse-Words($lines) {
$lines | foreach { $array = $PSItem.Split(' ') $array[($array.Count-1)..0] -join ' ' }
}
$lines = "---------- Ice and Fire ------------", "", "fire, in end will world the say Some", "ice. in say Some", "desire of tasted I've what From", "fire. favor who those with hold I", "", "... elided paragraph last ...", "", "Frost Robert -----------------------"
Reverse-Words($lines) </lang>
output :
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
PureBasic
<lang purebasic>a$ = "---------- Ice and Fire ------------" +#CRLF$+
" " +#CRLF$+ "fire, in end will world the say Some" +#CRLF$+ "ice. in say Some " +#CRLF$+ "desire of tasted I've what From " +#CRLF$+ "fire. favor who those with hold I " +#CRLF$+ " " +#CRLF$+ "... elided paragraph last ... " +#CRLF$+ " " +#CRLF$+ "Frost Robert -----------------------" +#CRLF$
a$ = "Hey you, Bub! " +#CRLF$+#CRLF$+ a$
OpenConsole() For p1=1 To CountString(a$,#CRLF$)
b$=StringField(a$,p1,#CRLF$) : c$="" For p2=1 To CountString(b$,Chr(32))+1 c$=StringField(b$,p2,Chr(32))+Space(1)+c$ Next PrintN(LSet(b$,36,Chr(32))+" ---> "+Trim(c$))
Next Input() </lang>
Python
<lang python> text = \
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------
for line in text.split('\n'): print(' '.join(line.split()[::-1]))</lang>
Output:
<lang Shell>------------ Fire and Ice ----------
Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire.
... last paragraph elided ...
Robert Frost</lang>
Racket
<lang racket>#lang racket/base
(require racket/string)
(define (split-reverse str)
(string-join (reverse (string-split str))))
(define poem
"---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------")
(let ([poem-port (open-input-string poem)])
(let loop ([l (read-line poem-port)]) (unless (eof-object? l) (begin (displayln (split-reverse l)) (loop (read-line poem-port))))))
</lang>
REXX
<lang rexx>/*REXX pgm reverses the order of tokens in a string, but not the letters*/ @. = @.1 = "---------- Ice and Fire ------------" @.2 = ' ' @.3 = "fire, in end will world the say Some" @.4 = "ice. in say Some" @.5 = "desire of tasted I've what From" @.6 = "fire. favor who those with hold I" @.7 = ' ' @.8 = "... elided paragraph last ..." @.9 = ' ' @.10 = "Frost Robert -----------------------"
do j=1 while @.j\==; $= /*process each "line"; nullify $.*/ do k=1 for words(@.j) /*process each word in the string*/ $=word(@.j,k) $ /*prepend the word to a new line.*/ end /*k*/ /* [↑] could do this another way*/ say $ /*display newly constructed line.*/ end /*j*/ /*stick a fork in it, we're done.*/</lang>
output when using the ten lines of input:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Ruby
<lang ruby>puts <<EOS
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ----------------------- EOS
.each_line.map {|line| line.split.reverse.join(' ')}</lang>
Output the same as everyone else's.
Rust
<lang rust>fn rev_words(line: &str) -> String {
line.split_whitespace().rev().collect::<Vec<&str>>().join(" ")
}
fn rev_words_on_lines(text: &str) -> String {
text.lines().map(rev_words).collect::<Vec<String>>().join("\n")
}
fn main() {
let text = "---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------";
println!("{}", rev_words_on_lines(text));
}</lang>
Scala
<lang Scala>object ReverseWords extends App {
"""| ---------- Ice and Fire ------------ | | fire, in end will world the say Some | ice. in say Some | desire of tasted I've what From | fire. favor who those with hold I | | ... elided paragraph last ... | | Frost Robert ----------------------- """ .stripMargin.lines.toList.map{_.split(" ")}.map{_.reverse} .map(_.mkString(" ")) .foreach{println}
}</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Scheme
<lang Scheme> (for-each
(lambda (s) (print (string-join (reverse (string-split s #/ +/))))) (string-split "---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------" #/[ \r]*\n[ \r]*/))
</lang> Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Seed7
<lang seed7>$ include "seed7_05.s7i";
const array string: lines is [] (
"---------- Ice and Fire ------------", "", "fire, in end will world the say Some", "ice. in say Some", "desire of tasted I've what From", "fire. favor who those with hold I", "", "... elided paragraph last ...", "", "Frost Robert -----------------------");
const proc: main is func
local var string: line is ""; var array string: words is 0 times ""; var integer: index is 0; begin for line range lines do words := split(line, ' '); for index range length(words) downto 1 do write(words[index] <& " "); end for; writeln; end for; end func;</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Sidef
<lang ruby>DATA.each{|line| line.words.reverse.join(" ").say};
__DATA__
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------</lang>
Smalltalk
<lang smalltalk> poem := '---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted Ive what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------'.
(poem lines collect: [ :line | ((line splitOn: ' ') reverse) joinUsing: ' ' ]) joinUsing: (String cr). </lang>
- Output:
'------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I''ve tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost'
Sparkling
This only considers space as the word separator, not tabs, form feeds or any other sort of whitespace. (This, however, turns out not to be an issue with the example input.)
<lang sparkling>let lines = split("---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------", "\n");
foreach(lines, function(idx, line) { let words = split(line, " "); let reverseWords = map(words, function(idx) { return words[sizeof words - idx - 1]; }); foreach(reverseWords, function(idx, word) { printf("%s ", word); });
print(); });</lang>
Tcl
<lang tcl>set lines {
"---------- Ice and Fire ------------" "" "fire, in end will world the say Some" "ice. in say Some" "desire of tasted I've what From" "fire. favor who those with hold I" "" "... elided paragraph last ..." "" "Frost Robert -----------------------"
} foreach line $lines {
puts [join [lreverse [regexp -all -inline {\S+} $line]]] # This would also work for data this simple: ### puts [lreverse $line]
}</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
Alternatively…
<lang tcl>puts [join [lmap line $lines {lreverse $line}] "\n"]</lang>
TXR
Run from command line: <lang bash>txr reverse.txr verse.txt</lang> Solution: <lang txr>@(collect) @ (some) @(coll)@{words /[^ ]+/}@(end) @ (or) @(bind words nil) @ (end) @(end) @(set words @(mapcar (fun nreverse) words)) @(output) @ (repeat) @(rep)@words @(last)@words@(end) @ (end) @(end) </lang> New line should be present after the last @(end) terminating vertical definition. i.e. <lang txr>@(end) [EOF]</lang> not <lang txr>@(end)[EOF]</lang>
UNIX Shell
<lang bash>while read -a words; do
for ((i=${#words[@]}-1; i>=0; i--)); do printf "%s " "${words[i]}" done echo
done << END
Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert ----------------------- END</lang>
Same as above, except change <lang bash>read -a</lang> to <lang bash>read -A</lang>
zkl
<lang zkl>text:=Data(0,String,
- <<<
"---------- Ice and Fire ------------
fire, in end will world the say Some ice. in say Some desire of tasted I've what From fire. favor who those with hold I
... elided paragraph last ...
Frost Robert -----------------------");
- <<<
text.pump(11,Data,fcn(s){ // process stripped lines
s.split(" ").reverse().concat(" ") + "\n" }) .text.print();</lang>
- Output:
------------ Fire and Ice ---------- Some say the world will end in fire, Some say in ice. From what I've tasted of desire I hold with those who favor fire. ... last paragraph elided ... ----------------------- Robert Frost
- Programming Tasks
- Solutions by Programming Task
- Ada
- Aime
- Applesoft BASIC
- AutoHotkey
- AWK
- Batch File
- BBC BASIC
- Bracmat
- Burlesque
- C
- C++
- Clojure
- Common Lisp
- D
- EchoLisp
- Elixir
- Emacs Lisp
- Gema
- Go
- Groovy
- Haskell
- Icon
- Unicon
- J
- Java
- JavaScript
- Jq
- Julia
- Liberty BASIC
- LiveScript
- Lua
- Mathematica
- MATLAB
- Nim
- Objeck
- OCaml
- Oforth
- Perl
- Perl 6
- PicoLisp
- PL/I
- PowerShell
- PureBasic
- Python
- Racket
- REXX
- Ruby
- Rust
- Scala
- Scheme
- Seed7
- Sidef
- Smalltalk
- Sparkling
- Tcl
- TXR
- UNIX Shell
- Zkl