文を逆にする


15

このチャレンジの目標は、入力を受け取り、その入力を文の順序を逆にして出力することです。入力例:

Hello friend. What are you doing? I bet it is something I want to do too!

出力例:

I bet it is something I want to do too! What are you doing? Hello friend.

例からわかるように、プログラムは疑問符、感嘆符、およびピリオドを処理する必要があります。各文には句読点があり、次の文の前にスペースがあると仮定できます。末尾のスペース/改行は、読み取り可能な限り問題ありません。最短のコードが優先されます。

幸運を!

編集:文に引用符や括弧がないと仮定することができますが、コードでこれらの両方を処理できるようにすると、-5バイトの括弧/引用符の出力例が得られます:

"Hello, " she said. (I didn't know what she was talking about.) --> (I didn't know what she was talking about.) "Hello, " she said.

引用符や括弧がないと仮定できますか?そうでない場合、それらをどのように処理しますか?
BrainSteel

投稿を編集してそれをクリアしました。

引用符または括弧を含む文の期待される出力の例を教えてください。
mbomb007

6
文に引用符または括弧内の句読点がある場合、どのように対処する必要がありますか?
isaacg

2
@Scimonster「ie」などの意味ですか?ああ、とする私のテストケースの見積もりを修正してください"Hello!" she said. (I hesitated. How should I respond? This is too much!) I responded, "Hi there. How are you? What is your cat's name?" without thinking any more about it.
ないようにチャールズ

回答:


9

ジュリア、45 42バイト-5ボーナス= 37

s->join(reverse(split(s,r"[.?!]\K "))," ")

これにより、入力として文字列を受け入れ、文を逆にして文字列を返す匿名関数が作成されます。これは、特殊文字を適切に処理しますが、二重引用符とドル記号はエスケープする必要があります。そうしないと、Juliaで有効な文字列ではなくなります。

Ungolfed +説明:

function f(s)
    # Get individual sentences by splitting on the spaces that
    # separate them. Spaces are identified by matching punctuation
    # then moving the position beyond that match and matching a
    # space. This is accomplished using \K.

    sentences = split(s, r"[.?!]\K ")

    # Reverse the order of the array of sentences.

    reversed_order = reverse(sentences)

    # Join the array elements into a string, separated by a space.

    join(reversed_order, " ")
end

例:

julia> f("Hello friend. What are you doing? I bet it is something I want to do too!")
"I bet it is something I want to do too! What are you doing? Hello friend."

julia> f("\"Hello, \" she said. (I didn't know what she was talking about.)")
"(I didn't know what she was talking about.) \"Hello, \" she said."

そして、出力のエスケープされた引用符を見たくない場合:

julia> println(f("\"Hello, \" she said. (I didn't know what she was talking about.)"))
(I didn't know what she was talking about.) "Hello, " she said.

MartinBüttnerのおかげで、正規表現で3バイト節約されました!以前は、これは後読みを使用していました(?<=[.?!])


これはボーナスの対象とは思わない
オプティマイザー

@Optimizer:どうしてですか?投稿にあるように、括弧、引用符などで期待どおりに機能します。
アレックスA.

質問のボーナスセクションの例を使用して、testへのオンラインリンクを提供できますか。
オプティマイザー

@Optimizer:Juliaの最新バージョンをオンラインで実行する唯一の方法は、登録が必要であり、パーマリンクをサポートしていません。ここに投稿に単に入力と出力を含めるだけで十分でしょうか?
アレックスA.

確かに、..
オプティマイザー

7

CJam、23 22バイト

これがボーナスの対象かどうかはわかりませんが、解決策は次のとおりです。

Sq{1$".?!"-{])[}|}%]W%

コード拡張(少し古い)

Sq+                      e# Read the input and prepend with a space
   {            }%       e# For each input character
    _".?!"&              e# Copy and check if its one of ., ? and !
           {][}&         e# If it is one of the above, wrap everything till now in an array
                         e# and start a new array to be wrapped next time we get one of those
                         e# three characters. We now have an array of strings, each having
                         e# a single sentence
                  W%     e# Reverse the ordering of these sentences
                    s(   e# Convert to string and remove the first space

こちらからオンラインでお試しください


ああ、最初に編集した直後にこの投稿を作成しました。-5のボーナスが得られます(少し難しくするため)-5のボーナスをあなたに!18バイト、すごい、それがビート可能かどうかわからない:P

5

J、 35 32

単一のアポストロフィをエスケープする必要があることを除いて、ボーナス入力をほとんど処理します。したがって、カウントしないと思います。(また、ここに私の最初の提出)

f=.;@|.@(]<;.2~'.?!'e.~])@,~&' '

使用法:

f 'Hello friend. What are you doing? I bet it is something I want to do too!'

4

Perl、27/25

#!perl -n
print reverse/ |[^.!?]*./g

または、コマンドラインから:

$perl -nE'say reverse/ |[^.!?]*./g'

いいね!で-5ボーナスを獲得できperl -nE 'say reverse/ |[^.?!]*.\)?/g'ます。合計カウントは23になります
。– ThisSuitIsBlackNot

2

PHP、60

echo join(' ',array_reverse(preg_split('/(?<=[?!.])/',$s)));

[?!.]\K代わりに正規表現を使用できますか?
マーティンエンダー

また、分割するパターンにスペースを含めない限り、これは文字列にスペースを追加しませんか?
マーティンエンダー

@MartinBüttner、いいえ、データを結合するときに適切な記号を復元することはできませんので、キャラクターを消費しないものが必要です。
ロマンニンシュ

2

Bash + coreutils、40バイト

sed 's/\([?.!]\) */\1\n/g'|tac|tr \\n \ 

これはSTDINから読み取るため、入力はファイルからリダイレクトされるか、単純にパイプされます。例:

$ printf 'Hello friend. What are you doing? I bet it is something I want to do too!' | sed 's/\([?.!]\) */\1\n/g'|tac|tr \\n \ 
I bet it is something I want to do too! What are you doing? Hello friend. 
$ 

これは(foo bar.)、単位として入れ替わるという意味で、括弧に対して実際に機能しますか?
マーティンエンダー

@MartinBüttner質問が編集されたように見えるので、私はもはやボーナスを請求することはできません:
デジタルトラウマ

2

ピップ、25バイト

a.:sRV(a^@2+$ALa@*^".?!")

入力文字列にスペースを追加した後、すべてのインデックスを見つけます .?!、2を追加し、使用します^@文章(末尾のスペースでそれぞれ)に文字列を分割する分割のオペレータを。リストを逆にすると、プログラムの最後に自動的に印刷されます。ほら!

入力による主な計算の段階を示す例A! B? C. D!

              ^".?!"     ["." "?" "!"]
           a@*           [[7] [4] [1 10]]
        $AL              [7 4 1 10]
      2+                 [9 6 3 12]
   a^@                   ["A! " "B? " "C. " "D! "]
RV(                 )    ["D! " "C. " "B? " "A! "]

                         D! C. B? A! 

いいえ:)
オプティマイザー

2

網膜61 34 33 30バイト

これを24バイト削減したnutkiの功績。

^
#
+`(#.*[.!?]) (.+)
$2 $1
#
<empty>

どこ<empty>が空の行を表します。これは#入力が入力の一部ではないことを前提としていますが、それが正当でない場合は、"(ボーナスのために処理する必要がある)または印刷できない何かを含む他のキャラクターと交換することができます。を使用すると、そのようなコードを単一のファイルで実行できます-sフラグ実行できます。または、各行を個別のファイルに入れて、すべてをRetinaに渡すことができます。

単一の正規表現の置換でこれを逆にすることは可能ですが、本当に面倒です。.NETバランシンググループを使用する場合でも、約90バイトが必要だったので、代わりに複数のステップで実行しようとしました。

Retinaでは、すべてのラインペアが1つの置換ステージであり、最初のラインがパターンで、2番目のラインが置換ステージです。

^
#

この段階では、さらに処理するために文字列を準備するだけです。#aをマーカーとして追加します。このマーカーは、その前のすべてがすでに適切な場所に配置されており、それ以降はすべて処理する必要があることを示しています。

+`(#.*[.!?]) (.+)
$2 $1

この段階では、前の最後の文を繰り返し移動することにより、文を交換します#(プロセス内の文字列を前方に移動します)。+`出力が変化しなくなるまで、この段階を繰り返すように網膜に指示します。例として、入力のfoo. bar! blah?処理方法を次に示します。

#foo. bar! blah?
blah? #foo. bar!
blah? bar! #foo.

最後に、マーカーを単に削除します。

#
<empty>

なぜ.+=> $0 #と繰り返される(.*?[.!?] )(.*#)=>では$2$1ないのですか?
-nutki

@nutkiああ、それはずっといいです、ありがとう。:)
マーティンエンダー

1

Java、113

s->{String t[]=s.split("(?<=[\\.?!]) "),u="";for(int i=t.length;i-->0;)u+=t[i]+" ";return u.replaceAll(".$","");}

1

JavaScript(ES6)47 45

述べられているように、これは単純な正規表現の練習です。javascriptの場合:

// ES6 - FireFox only
F=t=>t.match(/\S[^.!?]+./g).reverse().join(' ')

// ES5 - so much longer
function G(t){return t.match(/\S[^.!?]+./g).reverse().join(' ')}

// TEST

alert(G("Hello friend. What are you doing? I bet it is something I want to do too!"))
 


私はjavascriptをやろうとしていましたが、あなたはそれに私を打ち負かしました。
BobTheAwesome

これにより、最後の文(最初は最初の文)を除くすべての前に余分なスペースが生成されます。タスクがあまり明確に定義されていないため、OKかどうかはわかりません。
nutki

@nutkiはい、同意します。修正
edc65

1

Python 2, 62

それはおそらくバイトコストの価値がないので、ボーナスのために改善するつもりはありません。

import re
print' '.join(re.split('(?<=[?!.]).',input())[::-1])

これはボーナスの対象外です。質問のボーナス例
オプティマイザー

@Optimizer質問履歴を見てください。ボーナスを追加するために質問を更新した時点で、出力は例に一致しました。括弧がピリオドの外にあることを示すものは何もありませんでした。
mbomb007

これは最初から意図したことだと思う。しかし、しっかりした例は後で出てきました。まだボーナスを受け取るという意味ではありません:)(私も私のものを削除しました)
オプティマイザー

1

Matlab(93バイト)

y=[32 input('','s')];y=sortrows([cumsum(ismember(y,'?!.'),'reverse');y]',1)';disp(y(4:2:end))
  • これは、入力に先頭または末尾のスペースが含まれていないことを前提としています
  • 標準入出力を使用します
  • Tested in Matlab 2014b

1

Ruby 41

The other Ruby answers don't have enough WTF.

#!ruby -apF(?<=[.!?])\s
$_=$F.reverse*" "

This at least works in Ruby 2. If the a and F switch works in 1.8.7, I guess you could drop $_= to save three characters.

Reverses every line on stdin and print to stdout:

$ ruby foo.rb <<< "Hello. Hi. How are you? Good, you? fine, thanks."
fine, thanks. Good, you? How are you? Hi. Hello.

Could you please explain the answer.
Mhmd

1

Ruby, 48(42 without the puts) bytes

reverse_sentence.rb

puts $*[0].scan(/\S[^.!?]+./).reverse.join(" ")

Usage:

ruby reverse_sentence.rb 'Hello friend. What are you doing? I bet it is something I want to do too!'

Output:

I bet it is something I want to do too! What are you doing? Hello friend.

Criticism more than welcome.


2
Criticism: You spelled "sentence" incorrectly.
Alex A.

save 6 characters: .join(" ") => *" "
daniero

@AlexA. Best feedback ever!
DickieBoy

@daniero thanks, nice to know
DickieBoy

1

k, 31

{1_,/|(0,1+&x in"?!.")_x:" ",x}

.

k){1_,/|(0,1+&x in"?!.")_x:" ",x} "Hello friend. What are you doing? I bet it is something I want to do too!"
"I bet it is something I want to do too! What are you doing? Hello friend."

0

C# - LINQPAD - 93 - 5 = 88 bytes

void Main(){string.Join(" ",Regex.Split(Console.ReadLine(),"(?<=[.?!]) ").Reverse()).Dump();}

C# Console App 189 - 5 = 184 bytes

using System;using System.Linq;using System.Text.RegularExpressions;class P{static void Main(){Console.WriteLine(string.Join(" ",Regex.Split(Console.ReadLine(), "(?<=[.?!]) ").Reverse()));}}

regex shamelessly flogged from Alex A. :)


You can save 7 bytes by putting your application in namespace System then within that using Linq;usingText.RegularExpressions saving 2x system.
ldam

I don't think that this qualifies for the bonus. Look at the bonus example in the question
Optimizer

0

Clojure - 44 71 chars

(defn rs[s](reverse(re-seq #"\S.+?[.!?]"s)))

Improved and simplified RE, eliminated unnecessary whitespace.

Output is a sequence of the sentences in the original string, with the order of the sentences reversed:

Input: "Hello friend. What are you doing? I bet it is something I want to do too!" Output: ("I bet it is something I want to do too!" "What are you doing?" "Hello friend.")


0

Ruby, 47

$><<gets.strip.split(/(?<=[.?!]) /).reverse*' '

credits to Martin Büttner, for saving some characters.


1
You can read the input from STDIN with gets to save a byte, print it with $><< to save byte (no need for a space) and join the string with *'' to save two bytes.
Martin Ender

@MartinBüttner thanks for the suggestion, I wouldn't go with reading from the input from STDIN, though. Simply because there will be a trailing new line.
Mhmd

Actually, I think your code will currently result in a leading space.
Martin Ender

mmm, you're right. I'll see what should I do.
Mhmd

0

CJam, 21 bytes

1q{1?_"!.?"-}%1a/W%S*

This works by turning spaces after !s, .s and ?s into the number 1 (not the character 1 nor the character with code point 1, so the input can still contain those), splitting at 1's, reversing the order of the resulting chunks and joining by spaces.

Try it online in the CJam interpreter.

How it works

1                     e# B := 1
 q                    e# Q := input()
  {         }%        e# for each C in Q (map):
   1?                 e#   C := B ? C : 1
     _"!.?"-          e#   B := string(C).strip("!.?")
              1a/     e# Q := Q.split([1])
                 W%   e# Q := reverse(Q)
                   S* e# Q := Q.join(" ")
                      e# print(Q)
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.