Odd word problem: Difference between revisions
m
→{{header|EasyLang}}
(Added Wren) |
|||
(25 intermediate revisions by 16 users not shown) | |||
Line 37:
This is a rather straightforward approach, using recursion.
<
procedure Odd_Word_Problem is
Line 91:
end if;
end if;
end Odd_Word_Problem;</
Output:
Line 105:
{{works with|ALGOL 68G|Any - tested with release 2.8.win32}}
The words and punctuation should be on a single line. Uses recursion.
<
# the character that followed it #
# "ch" should contain the first letter of the word on entry and will be #
Line 179:
main: (
reverse every other word
)</
{{out}}
<pre>
Line 187:
=={{header|AutoHotkey}}==
<
loop, parse, str
if (A_LoopField ~= "[[:punct:]]")
Line 193:
else
res := toggle ? RegExReplace(res, ".*[[:punct:]]\K", A_LoopField ) : res A_LoopField
MsgBox % res</
Outputs:<pre>what,si,the;gninaem,of:efil.</pre>
=={{header|BaCon}}==
<
FUNCTION get_odd()
Line 238:
CLOSE DEVICE in
PRINT</
This program uses recursion.
{{out}}
Line 256:
=={{header|Bracmat}}==
<
= dothis doother forward backward
. ( forward
Line 288:
& put$\n
& odd-word$"kansas.txt" { Real file, as Bracmat cannot read a single character from stdin. }
);</
Output:
<pre>what,si,the;gninaem,of:efil.
Line 294:
=={{header|C}}==
<
#include <ctype.h>
static int
owp(int odd)
{
int ch, ret;
ch = getc(stdin);
putc(ch, stdout);
if (ch == EOF || ch == '.')
return EOF;
if (ispunct(ch))
return 0;
owp(odd);
return 0;
} else {
if (ispunct(ch))
return ch;
ret = owp(odd);
putc(ch, stdout);
return ret;
}
}
int
main(int argc, char **argv)
{
if (ch)
putc(ch, stdout);
if (ch == '.')
break;
}
return 0;
}
</syntaxhighlight>
=={{header|C++}}==
Line 337 ⟶ 342:
Tested with gcc 4.5, with "-std=c++0x" option.
<
#include <cctype>
#include <functional>
Line 372 ⟶ 377:
while( e ? odd() : even() ) e = !e;
return 0;
}</
=={{header|Ceylon}}==
<
String[] meaning = ["what,", "is,", "the;", "meaning,", "of:", "life."];
String[] kansas = ["we,", "are,", "not,", "in,", "kansas;", "any,", "more."];
Line 411 ⟶ 416:
=> ",.:;".contains(char);
</syntaxhighlight>
{{out}}
Line 424 ⟶ 429:
{{trans|Common Lisp}}
<
(char (.read *in*)))
Line 449 ⟶ 454:
((backward)))
(recur (not forward?)))) )
(println))</
Examples:
<
what,si,the;gninaem,of:efil.
nil
user=> (odd-word "we,are;not,in,kansas;any,more.")
we,era;not,ni,kansas;yna,more.
nil</
=={{header|CoffeeScript}}==
<
isLastChar = (c) -> c is '.'
Line 497 ⟶ 502:
# Alternate between forward and reverse until one or the other reports that
# the end-of-input mark has been reached (causing a return of false).
continue while forwardWord() and reverseWord()</
===Same without comments===
<
isLastChar = (c) -> c is '.'
Line 523 ⟶ 528:
return not isLastChar(c)
continue while forwardWord() and reverseWord()</
===Testing code===
<
println = (z) -> console.log z
Line 553 ⟶ 558:
[testString, expectedResult, putBuffer, putBuffer is expectedResult]
println result for result in results</
Output in [[node.js]]:
Line 568 ⟶ 573:
=={{header|Common Lisp}}==
Even words are straightforward. For odd words, the final punctuation is printed by a closure passed back up the caller chain.
<
(let ((stream (make-string-input-stream s)))
(loop for forwardp = t then (not forwardp)
Line 587 ⟶ 592:
(prog1 (backward stream) (write-char ch))
#'(lambda () (write-char ch) (char/= ch #\.)))) )
</syntaxhighlight>
Examples:
<
what,si,the;gninaem,of:efil.
NIL
? (odd-word "we,are;not,in,kansas;any,more.")
we,era;not,ni,kansas;yna,more.
NIL</
=={{header|D}}==
{{trans|C}}
<
import core.stdc.stdio, std.ascii;
Line 618 ⟶ 623:
bool i = true;
while (doChar(i = !i)) {}
}</
{{out}}
<pre>what,is,the;meaning,of:life.
what,si,the;gninaem,of:efil.</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Console}}
{{libheader| System.Character}}
{{Trans|D}}
<syntaxhighlight lang="delphi">
program Odd_word_problem;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.Console,
System.Character;
function doChar(isOdd: boolean; f: TProc = nil): Boolean;
begin
var c: char := Console.ReadKey(True).KeyChar;
if not isOdd then
Write(c);
if c.IsLetter then
exit(doChar(isOdd,
procedure
begin
Write(c);
if assigned(f) then
f();
end));
if isOdd then
begin
if Assigned(f) then
f();
write(c);
end;
exit(c <> '.');
end;
begin
var i: boolean := false;
while doChar(i) do
i := not i;
readln;
end.</syntaxhighlight>
=={{header|EasyLang}}==
<syntaxhighlight>
global inpi inp$ .
func$ read .
inpi += 1
return substr inp$ inpi 1
.
func ispunct c$ .
if c$ = "." or c$ = ":" or c$ = ";" or c$ = ","
return 1
.
return 0
.
func$ handle odd .
c$ = read
if ispunct c$ = 1
return c$
.
if odd = 0
write c$
r$ = handle 0
return r$
else
r$ = handle 1
write c$
return r$
.
.
proc go . .
repeat
c$ = handle odd
write c$
until c$ = "."
odd = 1 - odd
.
print ""
.
repeat
inp$ = input
until inp$ = ""
inpi = 0
go
.
input_data
we,are;not,in,kansas;any,more.
what,is,the;meaning,of:life.
</syntaxhighlight>
=={{header|EchoLisp}}==
No character input stream in EchoLisp, which runs in a browser window. We simultate it with a character stream, with the only function '''read-char''', as specified in the task.
<
(lib 'sequences)
(define input-stream null)
Line 658 ⟶ 760:
</syntaxhighlight>
{{out}}
<
(task "what,is,the;meaning,of:life.")
→ "what,si,the;gninaem,of:efil."
Line 666 ⟶ 768:
(task "Longtemps,je me suis couché,héhé,hôhô,de bonne heure.")
→ "Longtemps,ej me sius couché,éhéh,hôhô,ed bonne erueh."
</syntaxhighlight>
=={{header|Elixir}}==
{{trans|Erlang}}
<
def handle(s, false, i, o) when ((s >= "a" and s <= "z") or (s >= "A" and s <= "Z")) do
o.(s)
Line 695 ⟶ 797:
end
Odd_word.main</
{{out}}
Line 705 ⟶ 807:
=={{header|Erlang}}==
<
handle(S, false, I, O) when (((S >= $a) and (S =< $z)) or ((S >= $A) and (S =< $Z))) ->
O(S),
Line 722 ⟶ 824:
O = fun(S) -> io:put_chars([S]) end,
handle(I(), false, I, O).
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<p>A recursive solution.</p>
<
open System.Text.RegularExpressions
Line 759 ⟶ 861:
let rec loop () = forward() |> Out; loop()
loop()
0</
{{out}}
<pre>
Line 772 ⟶ 874:
This code is difficult to follow, because it twists its control flow like spaghetti. These continuations form a [[singly-linked list]], where each continuation contains a letter and a previous continuation. The program effectively reverses this linked list.
<
IN: rosetta.odd-word
Line 833 ⟶ 935:
: odd-word ( string -- )
[ read-odd-word ] with-string-reader ;</
'''USE: rosetta.odd-word'''
Line 843 ⟶ 945:
=={{header|FALSE}}==
This solution uses recursion to read the backwards words, to output the characters after having done the rest of that word.
<
[s;!$'.=~[,^f;!]?]r: {reverse words}
[[$$$$'.=\',=|\';=|\':=|~][,^]#$'.=~[,^r;!]?]f: {forward words}
^f;!, {start}</
=={{header|Forth}}==
<
: ?quit dup [char] . = if emit quit then ;
: eatbl begin dup bl = while drop key repeat ?quit ;
: even begin word? while emit key repeat ;
: odd word? if key recurse swap emit then ;
: main cr key eatbl begin even eatbl space odd eatbl space again ;</
=={{header|Fortran}}==
By not allowing the use of arrays of characters to facilitate the reversing of texts, the obvious solution involves recursion with storage via the stack so that its last-on, first-off style will achieve the required goal. But alas, Fortran compilers were typically written for computers that did not employ a stack mechanism so recursion was not expected even after the introduction of Algol in the 1960s, and the failure of recursively-invoked routines to return correctly became accepted. The standard murmur was that "Fortran is not a recursive language" even though the language contains recursive definitions such as for arithmetic expressions. By contrast, the B6700 system ''did'' employ a hardware stack, and, without any fuss, recursion just worked.
But with F90, the language definition was augmented by the menacing word RECURSIVE, and so... <
INTEGER MSG,INF !I/O unit numbers.
LOGICAL DEFER !To stumble, or not to stumble.
Line 899 ⟶ 1,001:
WRITE (MSG,"('')") !End the line of output.
GO TO 10 !And have another go.
END !That was confusing.</
With file Confused.txt containing the obvious input, the output is
<pre>
Line 911 ⟶ 1,013:
If the ADVANCE feature is unavailable, then the file could be read as UNFORMATTED, one character at a go with a record length of one. And then would arise the annoyance of dealing with the ASCII world's usage of CR, CRLF, LFCR, or CR as markers for the ends of records.
=={{header|FreeBASIC}}==
Rosetta Code problem: https://rosettacode.org/wiki/Odd_word_problem
by Jjuanhdez, 05/2023
<syntaxhighlight lang="vb">Dim Shared As Integer n1 = 1
Function reverseString(texto As String) As String
Dim As Integer x, lt = Len(texto)
For x = 0 To lt Shr 1 - 1
Swap texto[x], texto[lt - x - 1]
Next x
Return texto
End Function
Sub process(texto As String)
Dim As Integer c = 0, n2
Dim As String tmptexto
Print "Input stream: "; texto
Print "Output stream: ";
Do
n2 = Instr(texto, Any ",;:.")
tmptexto = Mid(texto, n1, n2-1)
Print Iif(c Mod 2 = 0, tmptexto, reverseString(tmptexto)); Mid(texto, n2, 1);
If Mid(texto, n2, 1) = "." Then Exit Do
texto = Mid(texto, n2+1, Len(texto))
c += 1
Loop
Print !"\n"
End Sub
process("what,is,the;meaning,of:life.")
process("we,are;not,in,kansas;any,more.")
Sleep</syntaxhighlight>
{{out}}
<pre>Input stream: what,is,the;meaning,of:life.
Output stream: what,si,the;gninaem,of:efil.
Input stream: we,are;not,in,kansas;any,more.
Output stream: we,era;not,ni,kansas;yna,more.</pre>
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
begin globals
short ndx : bool odd : cfstringref stream
end globals
local fn recursion
cfstringref ch = mid( stream, ndx, 1 )
if fn StringContainsString( @",;:. ", ch ) == no
ndx++
if odd then fn recursion : print ch; ¬
else print ch; : fn recursion
end if
end fn
local fn oddWordTask( s as cfstringref )
ndx = 0 : odd = no : stream = s
print : print, stream : print,
while ndx < len( stream )
fn recursion : print mid( stream, ndx, 1 );
odd = yes - odd : ndx++
wend
print
end fn
window 1, @"Odd word task in FutureBasic", (0,0,310,155)
fn oddWordTask( @"what,is,the;meaning,of:life." )
fn oddWordTask( @"we,are;not,in,kansas;any,more." )
fn oddWordTask( @"This also works with normal spaces." )
HandleEvents
</syntaxhighlight>
{{output}}
[[File:FB output for Odd Word Task.png]]
=={{header|Go}}==
<
import (
Line 964 ⟶ 1,144:
}
}
}</
Output:
<pre>
Line 972 ⟶ 1,152:
===Using <code>defer</code>===
<
import (
Line 1,023 ⟶ 1,203:
}
}
}</
===Using channels and goroutines===
{{trans|Ruby}}
{{trans|Tcl}}
<
import (
Line 1,116 ⟶ 1,296:
close(f.in)
close(r.in)
}</
=={{header|Haskell}}==
While it seems like this solution would break the task's rules, Haskell is non-strict, therefore this yields the same behavior of reading and printing one character at a time, without excess storage into a "string". To prove it, run the program and manually enter the input string (Windows command prompt does not respect buffering settings, but urxvt on on Linux does).
<
(BufferMode(..), getContents, hSetBuffering, stdin, stdout)
import Data.Char (isAlpha)
split :: String -> (String, String)
split =
parse :: String -> String
parse [] = []
parse l
let (a, w) = split l
(b, x) = splitAt 1 w
(c, y) = split x
(d, z) = splitAt 1 y
in a
main :: IO ()
main =
hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >> getContents >>=
putStr . takeWhile (/= '.') . parse >>
putStrLn "."</syntaxhighlight>
If the above is not acceptable, or if Haskell was implicitly strict, then this solution would satisfy the requirements:
<
isAlpha = flip elem $ ['a'..'z'] ++ ['A'..'Z']
Line 1,171 ⟶ 1,352:
main :: IO ()
main = hSetBuffering stdin NoBuffering >> hSetBuffering stdout NoBuffering >>
parse >> putStrLn ""</
Linux urxvt output:
<pre>$ ./OddWord
Line 1,193 ⟶ 1,374:
The following recursive version is based on the non-deferred GO version. A co-expression is used to turn the parameter to the wrapper into a character at a time stream.
<
every OddWord(!["what,is,the;meaning,of:life.",
"we,are;not,in,kansas;any,more."])
Line 1,214 ⟶ 1,395:
if any(marks,s := @stream) then return s
return 1(oWord(stream,marks), writes(s))
end</
Output:<pre>Input stream: what,is,the;meaning,of:life.
Line 1,222 ⟶ 1,403:
A slightly different solution which uses real I/O from stdin is:
<
repeat (while writes((any(&letters, c := reads(&input,1)),c))) |
(writes(c) ~== "." ~== writes(rWord())) | break write()
Line 1,231 ⟶ 1,412:
writes(\c)
return c1
end</
And some sample runs:
<pre>
Line 1,248 ⟶ 1,429:
J also lacks character stream support, so this implementation uses a [[Odd_word_problem/TrivialCharacterStreamSupportForJ|stream-like implementation]].
<
outch y
return x
Line 1,273 ⟶ 1,454:
outch char=. do_char coroutine ''
end.
)</
Note that in the couroutine-like support page we defined <code>u yield v y</code> such that it produces a result which, when returned to the <code>coroutine</code> helper verb, will cause the deferred execute <code>u v y</code> in a context where both u and v are expected to be coroutine verbs (they will produce a result either wrapped with <code>yield</code> or with <code>return</code>). Likewise <code>return</code> wraps the result with instructions for the <code>coroutine</code> helper, instructing it to use the returned result "as-is". (And, if <code>return</code> is used with an empty stack in the helper, that instance would be the result of the <code>coroutine</code> helper.)
Line 1,281 ⟶ 1,462:
With this implementation:
<
what,si,the;gninaem,of:efil.
evenodd 'we,are;not,in,kansas;any,more.'
we,era;not,ni,kansas;yna,more.</
That said, note that this implementation has significant overhead when compared to a more direct implementation of the algorithm.
=={{header|Java}}==
<
interface CharHandler {
CharHandler handle(char c) throws Exception;
Line 1,345 ⟶ 1,526:
new OddWord().loop();
}
}</
Output is equivalent to that of the Python solution.
Line 1,351 ⟶ 1,532:
{{works with|Julia|0.6}}
{{trans|Python}}
<
io = "what,is,the;meaning,of:life."
i = 0
Line 1,383 ⟶ 1,564:
while evn ? odd() : even()
evn = !evn
end</
{{out}}
Line 1,390 ⟶ 1,571:
=={{header|Kotlin}}==
{{trans|C}}
<
typealias Func = () -> Unit
Line 1,420 ⟶ 1,601:
println("\n")
}
}</
{{out}}
Line 1,433 ⟶ 1,614:
=={{header|Lasso}}==
<
local(
isodd = false,
Line 1,486 ⟶ 1,667:
'new:\r'
odd_word_processor('what,is,the;meaning,of:life.')
'\rShould have:\rwhat,si,the;gninaem,of:efil.'</
{{out}}
Line 1,497 ⟶ 1,678:
=={{header|Lua}}==
<
local ch = io.read(1)
if ch:find("%w") then
Line 1,519 ⟶ 1,700:
end
while forward() do end</
{{out}}
<pre>$ echo what,is,the;meaning,of:life.|oddword.lua
Line 1,536 ⟶ 1,717:
We can pass by reference the lambda function but here we pass by reference the f factor, which for keyboard check the end, and for file work as file handler and at then end as a flag which check the end.
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
global out$
Line 1,624 ⟶ 1,805:
}
Checkit
</syntaxhighlight>
===Using Closure===
<syntaxhighlight lang="m2000 interpreter">
Module OddWord {
k$=lambda$->""
Line 1,649 ⟶ 1,830:
Keyboard "we,are;not,in,kansas;any,more."
OddWord
</syntaxhighlight>
{{out}}
Line 1,658 ⟶ 1,839:
=={{header|Nim}}==
===Using a closure===
{{trans|Python}}
<syntaxhighlight lang
var nothing: Proc = proc(): bool {.closure.} = false
proc odd(prev = nothing): bool =
Line 1,686 ⟶ 1,870:
var e = false
while (if e: odd() else: even()):
e = not e</
{{out}}
<pre>$ echo "what,is,the;meaning,of:life." | ./oddword
what,si,the;gninaem,of:efil.
echo "we,are;not,in,kansas;any,more." | ./oddword
we,era;not,ni,kansas;yna,more.</pre>
===Using recursion===
{{trans|ALGOL 68}}
<syntaxhighlight lang="nim">import strutils
proc reverseWord(ch: var char) =
var nextch = stdin.readChar()
if nextch.isAlphaAscii():
reverseWord(nextch)
stdout.write(ch)
ch = nextch
proc normalWord(ch: var char) =
stdout.write(ch)
ch = stdin.readChar()
if ch.isAlphaAscii():
normalWord(ch)
var ch = stdin.readChar()
while ch != '.':
normalWord(ch)
if ch != '.':
stdout.write(ch)
ch = stdin.readChar()
reverseWord(ch)
stdout.write(ch)</syntaxhighlight>
{{out}}
Same as with the closure version.
=={{header|OCaml}}==
<
c >= 'a' && c <= 'z' ||
c >= 'A' && c <= 'Z'
Line 1,719 ⟶ 1,934:
let () =
try rev_odd_words ()
with End_of_file -> ()</
Executing:
Line 1,728 ⟶ 1,943:
=={{header|Ol}}==
Use string iterators.
<
(define (odd_word_problem words)
(letrec ((odd (lambda (s out)
Line 1,760 ⟶ 1,975:
(odd_word_problem "what,is,the;meaning,of:life.")
(odd_word_problem "we,are;not,in,kansas;any,more.")
</syntaxhighlight>
Output:
Line 1,777 ⟶ 1,992:
===Closure version===
<
{
my ($f, $c) = @_;
Line 1,796 ⟶ 2,011:
}
}
$r->();</
===Recursion version===
<
{
my $c;
Line 1,823 ⟶ 2,038:
$n = 0; $l = 0;
}
}</
===Threads (processes) version===
Perl still has weak threads support. Far more safe yet portable is to use processes (fork).
Here, fork is used instead of threads and pipe is used instead of conditional variable.
<
while (read STDIN, $_, 1) {
Line 1,851 ⟶ 2,066:
close R;
}
}</
=={{header|Phix}}==
Line 1,857 ⟶ 2,072:
To test direct console input, comment out string s .. getchar(), and uncomment getc(0) and the prompt.<br>
Likewise use integer fn = open("somefile","r"), and getc(fn) should you want to test file i/o.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"what,is,the;meaning,of:life."</span>
<span style="color: #000080;font-style:italic;">--string s = "we,are;not,in,kansas;any,more."</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">getchar</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">i</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">wrod</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">rev</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">getchar</span><span style="color: #0000FF;">(),</span> <span style="color: #000000;">nch</span>
<span style="color: #000080;font-style:italic;">-- integer ch = getc(0), nch</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" .,:;!?"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">rev</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">nch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">wrod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rev</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #008080;">not</span> <span style="color: #000000;">rev</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">nch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">wrod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rev</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">nch</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">ch</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #000080;font-style:italic;">--puts(1,"Enter words separated by a single punctuation mark (i.e. !?,.;:) and ending with .\n")</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">rev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">wrod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rev</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">=</span><span style="color: #008000;">'.'</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #000000;">rev</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">rev</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,898 ⟶ 2,116:
=={{header|PHP}}==
{{trans|Python}}
<
$a = fgetc(STDIN);
if (!ctype_alpha($a)) {
Line 1,924 ⟶ 2,142:
while ($e ? $odd($prev) : $even()) {
$e = !$e;
}</
=={{header|PicoLisp}}==
<
(use C
(loop
Line 1,940 ⟶ 2,158:
C
(prog1 (recurse (char)) (prin C)) ) ) ) ) ) )
(prinl) ) )</
Test:
<
(in "txt2" (oddWords))</
Output:
<pre>what,si,the;gninaem,of:efil.
Line 1,950 ⟶ 2,168:
=={{header|PL/I}}==
<
declare (ch, ech) character (1);
declare odd file;
Line 1,974 ⟶ 2,192:
if ech = '.' then leave;
end;
end test;</
file:
<pre>
Line 1,994 ⟶ 2,212:
=={{header|Prolog}}==
Works with SWI-Prolog.
<
read_line_to_codes(user_input, L),
even_word(L, Out, []),
Line 2,021 ⟶ 2,239:
[H],
even_word(T).
</syntaxhighlight>
Output :
<pre>?- odd_word_problem.
Line 2,036 ⟶ 2,254:
=={{header|PureBasic}}==
This example uses recursion.
<
#True = 1
Line 2,093 ⟶ 2,311:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
Sample output:
<pre>Enter a series of words consisting only of English letters (i.e. a-z, A-Z)
Line 2,106 ⟶ 2,324:
=={{header|Python}}==
<
def char_in(): return stdin.read(1)
Line 2,133 ⟶ 2,351:
e = False
while odd() if e else even():
e = not e</
Running:<syntaxhighlight lang="text">$ echo "what,is,the;meaning,of:life." | python odd.py
what,si,the;gninaem,of:efil.
$ echo "we,are;not,in,kansas;any,more." | python odd.py
we,era;not,ni,kansas;yna,more.</
{{trans|Scheme}}
In this version, the action of printing the terminating punctuation is put in a closure and returned by <code>odd()</code>.
<
def char_in(): return stdin.read(1)
Line 2,168 ⟶ 2,386:
e = False
while odd()() if e else even():
e = not e</
===Using coroutines and recursion===
Line 2,174 ⟶ 2,392:
{{trans|Tcl}}
{{works with|Python|3.3+}}
<
def fwd(c):
Line 2,206 ⟶ 2,424:
if not c:
break
coro = coro.send(c)</
=={{header|Quackery}}==
It is not possible to comply with the requirements of this task ''to the letter'' as the task presumes the existence of an ''implicit'' stack, e.g. a stack frame storing state information during subroutine calls, including recursive calls. In Quackery such information is stored on a second stack (usually referred to as ''the stack'') which is ''explicit''.
Also, there is no character-at-a-time input stream mechanism implemented in Quackery. Instead, the code uses the word <code>behead</code> which equivalently returns successive characters from a string, one at a time.
Therefore this solution is in the spirit of the requirements, if not the letter.
<syntaxhighlight lang="quackery">[ upper dup lower != ] is letter ( c --> b )
forward is backwords ( $ --> $ )
[ [ behead
dup letter while
emit again ]
dup emit
char . !=
if backwords ] is forwords ( $ --> $ )
[ [ behead
dup letter while
swap recurse
rot emit ]
dup emit
char . !=
if forwords ] resolves backwords ( $ --> $ )
[ forwords drop cr ] is oddwords ( $ --> )
$ "we,are;not,in,kansas;any,more." oddwords
$ "what,is,the;meaning,of:life." oddwords</syntaxhighlight>
{{out}}
<pre>we,era;not,ni,kansas;yna,more.
what,si,the;gninaem,of:efil.</pre>
=={{header|Racket}}==
Simple solution, using a continuation thunk for the reverse parts.
<
#!/bin/sh
#|
Line 2,237 ⟶ 2,492:
;; (with-input-from-string "we,are;not,in,kansas;any,more." main)
;; ;; -> we,era;not,ni,kansas;yna,more.
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
A recursive solution, with the added feature that it treats each line separately.
<syntaxhighlight lang="raku"
loop {
Line 2,253 ⟶ 2,508:
multi ow ($_ where /\w/) { ow(in) x .print; }
multi ow ($_) { $_; }</
{{out}}
<pre>$ ./oddword
Line 2,272 ⟶ 2,527:
No recursion or the stack is used. The program could've been written without subroutines.
<
iFID_ = 'ODDWORD.IN' /*Note: numeric suffix is added later.*/
oFID_ = 'ODDWORD.' /* " " " " " " */
Line 2,302 ⟶ 2,557:
/*──────────────────────────────────────────────────────────────────────────────────────*/
rChar: if arg()==0 then do; x= charin(iFID); #= #+1; end /*read next char*/
else x= charin(iFID, arg(1) ); /* " specific " */ return</
{{out|output|text= when using the two (default) input files which contain:}}
:* input file '''ODDWORD.IN1''' ───► <tt> what,is,the;meaning,of:life. </tt>
Line 2,319 ⟶ 2,574:
=={{header|Ring}}==
<
# Project : Odd word problem
Line 2,363 ⟶ 2,618:
next
return cStr2
</syntaxhighlight>
Output:
<pre>
Line 2,375 ⟶ 2,630:
{{trans|Tcl}}
{{works with|Ruby|1.9}}
<
fwd = proc {|c|
c =~ /[[:alpha:]]/ ? [(print c), fwd[Fiber.yield f]][1] : c }
Line 2,387 ⟶ 2,642:
until $stdin.eof?
coro = coro.resume($stdin.getc)
end</
===Using continuations===
{{trans|Factor}}
{{libheader|continuation}}
<
require 'stringio'
Line 2,462 ⟶ 2,717:
odd_word "what,is,the;meaning,of:life."
odd_word "we,are;not,in,kansas;any,more."</
=={{header|Run BASIC}}==
{{incorrect|Run BASIC|Restriction #1 violated - only single character I/O allowed. Restriction #2 violated - explicit storage in string for later reversal not allowed.}}
<
while not(eof(#f))
line input #f, a$
Line 2,496 ⟶ 2,751:
next ii
wend
close #f</
<pre>what,is,the;meaning,of:life. -> what,si,the;gninaem,of:efil.
we,are;not,in,kansas;any,more. -> we,era;not,ni,kansas;yna,more.</pre>
=={{header|Scala}}==
<
import java.io.PrintStream
Line 2,517 ⟶ 2,772:
process(Source.fromString("what,is,the;meaning,of:life."), System.out); println
process(Source.fromString("we,are;not,in,kansas;any,more."), System.out); println</
{{out}}
<pre>what,si,the;gninaem,of:efil.
Line 2,524 ⟶ 2,779:
=={{header|Scheme}}==
Output is identical to python.
<
(let ((c (read-char)))
(if (char-alphabetic? c)
Line 2,542 ⟶ 2,797:
(if (if i ((odd)) (even))
(exit)
(loop (not i))))</
=={{header|Seed7}}==
<
include "chartype.s7i";
Line 2,579 ⟶ 2,834:
until delimiter = '.';
writeln;
end func;</
{{out}}
Line 2,592 ⟶ 2,847:
Recursive solution:
{{trans|Perl}}
<
(var c = STDIN.getc) \\ return()
if (c ~~ /^[a-z]\z/i) {
Line 2,615 ⟶ 2,870:
l = false
}
}</
{{out}}
<pre>
Line 2,628 ⟶ 2,883:
Although the input is handled as strings, they're all as single-character strings.
{{works with|Tcl|8.6}}
<
proc fwd c {
Line 2,640 ⟶ 2,895:
for {set coro f} {![eof stdin]} {} {
set coro [$coro [read stdin 1]]
}</
Output is identical to Python and Scheme versions.
Line 2,648 ⟶ 2,903:
{{incorrect|Run BASIC|You are supposed to read characters one by one and not store them in arrays.}}
<
$$ MODE TUSCRIPT
inputstring=*
Line 2,667 ⟶ 2,922:
PRINT outputstring
ENDLOOP
</syntaxhighlight>
Output:
<pre>
Line 2,676 ⟶ 2,931:
=={{header|VBA}}==
First way :
<
Dim i As Integer, count As Integer, l As Integer, flag As Boolean, temp As String
count = 1
Line 2,710 ⟶ 2,965:
ReverseWord = StrReverse(temp) & sep
c = c + Len(ReverseWord)
End Function</
Second way :
<
Dim i&, count&, t$, cpt&, j&, l&, d&, f As Boolean
Const PUNCT As String = ",;:"
Line 2,750 ⟶ 3,005:
Next
OddWordSecond = t
End Function</
To call Functions :
<
Sub Main()
Line 2,762 ⟶ 3,017:
Debug.Print "First way : " & OddWordFirst("what,is,the;meaning,of:life.")
Debug.Print "Second way : " & OddWordSecond("what,is,the;meaning,of:life.")
End Sub</
{{out}}
<pre>Input : we,are;not,in,kansas;any,more.
Line 2,771 ⟶ 3,026:
First way : what,si,the;gninaem,of:efil.
Second way : what,si,the;gninaem,of:efil.</pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
const str = 'what,is,the;meaning,of:life.'
fn main() {
mut temp, mut new_str := '', ''
mut switch := true
for field in str {
temp += field.ascii_str()
if field.is_alnum() == false {
if switch == true {
new_str += temp
temp =''
switch = false
continue
}
else {
new_str += temp.all_before_last(field.ascii_str()).reverse() + field.ascii_str()
temp =''
switch = true
continue
}
}
}
println(new_str)
}
</syntaxhighlight>
{{out}}
<pre>
what,si,the;gninaem,of:efil.
</pre>
=={{header|Wren}}==
{{trans|Kotlin}}
{{libheader|Wren-str}}
<
import "./str" for Char
var fwrite = Fn.new { |ch|
Line 2,808 ⟶ 3,096:
Stdin.readByte() // remove \n from buffer
System.print("\n")
}</
{{out}}
Line 2,818 ⟶ 3,106:
we,era;not,ni,kansas;yna,more.
</pre>
=={{header|XPL0}}==
{{trans|Go}}
<syntaxhighlight lang "XPL0">proc OWP;
int B;
func Odd;
int S, B;
[S:= ChIn(8);
if S < ^A then \punct\ return S;
B:= Odd;
ChOut(0, S);
return B;
];
[OpenI(8);
loop [loop [B:= ChIn(8);
ChOut(0, B);
if B = ^. then return;
if B < ^A \punct\ then quit;
];
B:= Odd;
ChOut(0, B);
if B = ^. then return;
];
];
[OpenO(8);
Text(8, "what,is,the;meaning,of:life. ");
OWP;
CrLf(0);
OpenO(8);
Text(8, "we,are;not,in,kansas;any,more. ");
OWP;
CrLf(0);
]</syntaxhighlight>
{{out}}
<pre>
what,si,the;gninaem,of:efil.
we,era;not,ni,kansas;yna,more.
</pre>
=={{header|zkl}}==
{{trans|D}}
<
fcn oddly(inStream){
inStream=inStream.walker(3); // character iterator: string, file, etc
Line 2,836 ⟶ 3,165:
while(doWord(inStream, tf.next(), Void)) {}
println();
}</
Showing two different input streams:
<
oddly(Data(0,String,"we,are;not,in,kansas;any,more."));</
{{out}}
<pre>
|