単語のリストをバックスペースで再入力


38

ここではどのようにですバックスペース-と-がretype 1つの文字列から別のものに:

  1. 最初の文字列から始めます。
  2. 結果が2番目の文字列のプレフィックスになるまで、末尾の文字を削除します。(これには0ステップかかる場合があります。)
  3. 結果が2番目の文字列と等しくなるまで、最後に文字を追加します。(これも0ステップかかります。)

たとえば、からのパスfooabcfooxyz次のようになります。

fooabc
fooab
fooa
foo
foox
fooxy
fooxyz

仕事

単語のリストが与えられたら、空の文字列から連続してリスト内のすべての単語にバックスペースで再入力し、空の文字列に戻るプログラムを作成します。すべての中間文字列を出力します。

たとえば、入力リストを指定する["abc", "abd", "aefg", "h"]と、出力は次のようになります。

a
ab
abc
ab
abd
ab
a
ae
aef
aefg
aef
ae
a

h

ルール

文字列のリスト、または任意の区切り文字を含む単一の文字列を返すか、印刷することができます。オプションで、最初と最後の空の文字列を含めることができます。入力には少なくとも1つの単語が含まれることが保証され、各単語には小文字のASCII文字(az)のみが含まれることが保証されます。編集:入力内の連続する文字列は、互いに等しくないことが保証されます。

これはです。バイト単位の最短コードが優先されます。

Python 3のリファレンス実装:オンラインで試してみてください!


4
@ rahnema1>そのバックスペース-と-が再表示し、そのプログラムの書き込み空の文字列からの道を
KritixiのLithos

3
出力はどのようになり["abc","abc"]ますか?
クリチキシリトス

1
@Emignaおっと、これはまさにそれですが、ループ内にあります!それで、私はこれがそれの複製であると言います。
リン

4
@Lynnそれはまったく同じものではありません。共通のプレフィックスを認識することは含まれず、常に1文字になります。
マーティンエンダー

6
テストケース:a,abc,abcde,abc,a,abc,abcde
Zgarb

回答:



9

Perl、43バイト

42バイトのコード+ -nフラグ。

chop$@,say$@while!s/^$@//;s/./say$@.=$&/ge

実行するには:

perl -nE 'chop$@,say$@while!s/^$@//;s/./say$@.=$&/ge' <<< "abc
abd
aefg
h"

これは、abcを3回印刷します
izabera

@izabera abc3回印刷した後、スペースがありました(実際には、スペースなしで1回目と3回目)。削除しました。
ダダ

5

Java 8、144バイト

これはリファレンス実装に似ていますが、2つのwhileループを組み合わせています。String[]パラメーターを受け入れるラムダ式です。

a->{String c="";int l=0,i;for(String w:a)while((i=w.indexOf(c))!=0||!c.equals(w))System.out.println(c=i!=0?c.substring(0,--l):c+w.charAt(l++));}

非ゴルフ

a -> {
    String c = "";
    int l = 0, i;
    for (String w : a)
        while ((i = w.indexOf(c)) != 0 || !c.equals(w))
            System.out.println(c = i != 0 ? c.substring(0, --l) : c + w.charAt(l++));
}

謝辞

  • CAD97のラムダ提案による-38バイト

class B代わりに使用する方が安くないinterface Bですか?パッケージプライベートクラスから実行できます。また、すでにJava8を指定しているので、ラムダの使用を検討してください。
CAD97

@ CAD97 interface B{static void mainはより短いですclass B{public static void main
ケビンCruijssen

@ CAD97ラムダをこれに組み込む方法を考えることはできませんでしたが、昨日それらについて知りました。何か案は?
ヤコブ

1
あ、さびている。できるはずですa->{/*your code*/}。これにより、型の変数に割り当てられますjava.util.function.Consumer<String[]>。ただし、現時点ではテストできません。
CAD97

1
@JakobCornellデフォルトでは、PPCGは完全なプログラムまたは機能の送信を許可します。匿名関数(ラムダ)を使用する言語の場合、匿名関数自体が受け入れられる答えです(したがって、変数を格納するために変数を含める必要はありません)。(Javaの提出では、ラムダのタイプを提供することは丁寧です。)
CAD97

4

Mathematica、149バイト

Reap[Fold[n=NestWhile;s=StringMatchQ;r=StringReplace;n[k=#2;Sow@r[k,#~~a_~~___:>#<>a]&,n[Sow@r[#,a___~~_:>a]&,#,!s[k,#~~___]&],k!=#&]&,"",#]][[2,1]]&


3

ゼリー31 29 26バイト

⁷œ|;\
ÇṚðfḢṭḟ;ḟ@ḊðÇ}
⁷;ç2\

オンラインでお試しください!

使い方

⁷;ç2\           Main link. Argument: A (string array)

⁷;              Prepend a linefeed to A. 
                This is cheaper than prepending an empty string.
  ç2\           Reduce all overlapping pairs by the second helper link.


ÇṚðfḢṭḟ;ḟ@ḊðÇ}  Second helper link. Arguments: s, t (strings)

Ç               Call the first helper link with argument s.
 Ṛ              Reverse the results.
            Ç}  Call the first helper link with argument t.
  ð        ð    Combine everything in between into a dyadic chain, and call it
                with the results to both sides as arguments.
                Let's call the arguments S and T.
   f            Filter; get the common strings of S and T.
    Ḣ           Head; select the first one.
      ḟ         Filterfalse; get the strings in S that do not appear in T.
     ṭ          Tack; append the left result to the right one.
        ḟ@      Filterfalse swap; get the strings in T that do not appear in S.
       ;        Concatenate the results to both sides.
          Ḋ     Dequeue; remove the first string.


⁷œ|;\           First helper link. Argument: s (string)

⁷œ|             Linefeed multiset union; prepend a linefeed to s unless it already
                has a linefeed in it (the first string does).
   ;\           Concatenate cumulative reduce; generate all prefixes of the result.

2

Haskell102 93 91 90バイト

(?)=take.length
a!x@(b:c)|a==b=b!c|a/=a?b=a:init a!x|d<-'?':a=a:d?b!x
_!x=x
(""!).(++[""])

最後の行は、文字列のリストを取得して返す匿名関数です。 オンラインでお試しください!

説明

私の解決策は再帰的です。最初?は、ヘルパー挿入関数です:a?bの最初のlength a文字b、またはbif の全体aが長くなります。次に、中置関数を定義します!。という考えはa!x、がa文字列と文字列xのリストであるが、からa最初の文字列へのパスを生成xし、の末尾まで再帰するというものですx。最後の行で、空の文字列を追加!し、空の文字列と入力に適用する匿名関数を定義します。

説明!

a!x@(b:c)        -- a!x, where x has head b and tail c:
  |a==b          -- If a equals b,
    =b!c         -- recurse to x.
  |a/=a?b        -- If a is not a prefix of b,
    =a:          -- produce a and
    init a!x     -- continue with one shorter prefix of a.
  |              -- Otherwise a is a proper prefix of b.
   d<-'?':a      -- Let d be a with an extra dummy element,
    =a:          -- produce a and
    d?b!x        -- continue with one longer prefix of b.
_!x=x            -- If x is empty, return x.

2

Python 2、118 107 103 97 93 92バイト

s=''
for i in input()+[s]:
 while i.find(s):s=s[:-1];print s
 while i>s:s+=i[len(s)];print s

入力は['abc', 'abcdef', 'abcfed']、または[ として与えられ"abc", "abcdef", "abcfed"]ます。

改訂1:-11バイト。Pythonゴルフのヒントに関する彼の投稿は@xnorに、私のヒントを見つけてくれたのは@Lynnに、そしてスマートになったことは私に感謝します。2つの変更が行われました:の代わりにnot s.startswith(i)、を使用しs.find(i)、代わりにi!=sを使用しましたi>s

リビジョン2:-4バイト。私は本当に馬鹿げた間違いを犯したことに気付いてくれました。シングルタブとダブルタブのインデントを使用する代わりに、シングルスペースとシングルタブのインデントを使用しました。

リビジョン3:-6バイト。whileを1行にすることを提案してくれたのは@ mbomb007になります。また、に変更s.find(i)してバグを修正しましたi.find(s)

改訂4:-4バイト。入力を変数に格納する必要がなかったことを認識したことで、クレジットは@xnorに送られます。

リビジョン5:-1バイト。それが入力に追加するとき['']と同じことであることに気付いてくれたので、私に感謝し[s]ます。


入れてwhile単一の行に秒ごとに。また、の<1代わりに使用できますnot
mbomb007

いい答えだ!xnorによる回避startswith方法に関するヒントがあります。
リン

@リンああ、リンクをありがとう!本当に助かった!
ハイパーニュートリノ

@ mbomb007申し訳ありませんが、whilesを1行に入力しても意味がわかりません。どういう意味while s.find(i):s=s[:-1];print sですか?また、についての提案に<1感謝しますが、Pythonのヒントスレッドに関するxnorのヒントの1つにより、もっと短いものに変更しました。
ハイパーニュートリノ

@AlexL。はい、そのようなことをします。
mbomb007

1

GNU M4、228または232バイト¹

(¹ファイルを終了するかどうかによって異なります。dnl\n私はゴルフとM4の両方にまだ慣れていません)

define(E,`ifelse(index($2,$1),0,`T($1,$2)',`$1
E(substr($1,0,decr(len($1))),$2)')')define(T,`ifelse($1,$2,,`$1
T(substr($2,0,incr(len($1))),$2)')')define(K,`ifelse($2,,$1,`E($1,$2)K(shift($@))')')define(M,`K(substr($1,0,1),$@)')

さらに、substrfrom の2番目の引数を0空の文字列に置き換えることで3バイトを節約できますが、stderrで多くの警告が生成されます。

ゴルフをしていない:

define(erase_til_prefix, `dnl arguments: src dst; prints src and chops one char off of it until src == dst, at which point it calls type_til_complete instead
ifelse(dnl
index($2, $1), 0, `type_til_complete($1, $2)',dnl
`$1
erase_til_prefix(substr($1, 0, decr(len($1))), $2)dnl
')')dnl
define(type_til_complete, `dnl arguments: src dst; types src, does not type `dst' itself
ifelse(dnl
$1, $2, ,dnl
`$1
type_til_complete(substr($2, 0, incr(len($1))), $2)'dnl
)')dnl
define(main_, `dnl
ifelse(dnl
$2, , $1, dnl no arguments left
`erase_til_prefix($1, $2)main_(shift($@))'dnl
)')dnl
define(main, `main_(substr($1, 0, 1), $@)')dnl

使用法:

$ m4 <<<"include(\`backspace-golfed.m4')M(abc, abd, aefg, abcdefg, h)"

1

PHP、116 111 101 83バイト

注:Windows-1252エンコードを使用します。

for(;$w=$argv[++$i];)for(;$c!=$w;)echo$c=($c^$c^$w)==$c?$c.ÿ&$w:substr($c,0,-1),~õ;

次のように実行します。

php -r 'for(;$w=$argv[++$i];)for(;$c!=$w;)echo$c=($c^$c^$w)==$c?$c.ÿ&$w:substr($c,0,-1),~õ;' -- abc abd aefg h 2>/dev/null
> a
> ab
> abc
> ab
> abd
> ab
> a
> ae
> aef
> aefg
> aef
> ae
> a
>
> h

説明

for(                       # Outer loop.
  ;
  $w=$argv[++$i];          # Loops over the input words.
)
  for(                     # Second inner loop.
    ;
    $c!=$w;                # Loop until the word was output.
  )
    echo $c=
      ($c^$c^$w)==$c?      # Check if last output string is a substring
                           # match with the next word to output.
        $c.ÿ&$w:           # ... If yes, suffix the string with the next
                           # char of the word, and output the result.
        substr($c,0,-1),   # ... If not, remove a char and output.
      ~õ;                  # Output newline.

微調整

  • trim($c^$w,"\0")代わりに部分文字列の一致を確認するために使用して、5バイトを保存しました$c&&strpos($w,$c)!==0
  • ~ÿ代わりにNULバイトの文字列を生成するために使用して2バイトを節約しました"\0"
  • 次の文字で$c=$c.ÿ&$w接尾辞$cを使用して8バイトを保存しました$w
  • 1つのループで2つの内部ループのロジックを組み合わせることにより、18バイトを大幅に節約しました
  • コメントからのテストケースのバグを修正しました。バイト数に変更はありません

1

バッチ、296 291バイト

@echo off
set f=
set t=%1
:t
set f=%f%%t:~,1%
set t=%t:~1%
echo(%f%
if not "%t%"=="" goto t
shift
set t=%1
set s=%f%
set p=
:h
if %s:~,1%==%t:~,1% set p=%p%%t:~,1%&set s=%s:~1%&set t=%t:~1%&goto h
:b
set f=%f:~,-1%
echo(%f%
if not "%f%"=="%p%" goto b
if not "%1"=="" goto t

共通のプレフィックスの計算は面倒でした。


0

PHP、153バイト

非常に長い:(

for($s=$argv[$k=1];$t=$argv[++$k];){for(;$s>""&&strstr($t,$s)!=$t;$s=substr($s,0,-1))echo"$s
";for($i=strlen($s);$s<$t;$s.=$t[$i++])echo"$s
";echo"$s
";}

で実行しphp -nr '<ode>' <text1> <text2> ...ます。


0

JavaScript(ES6)、135バイト

面白いチャレンジ!使用法:g(["abc", "abd", "aefg", "h"])。これを1つの関数として記述することでバイトを節約することができなかったので、2つです。改行はバイトカウントに含まれません。

f=a=>console.log(([,...z]=[x,y]=a)[0])||
y?f(a=(x==y.slice(0,-1))?z:([y.match(x)
?x+y[x.length]:x.slice(0,-1),...z])):1;
g=a=>f(['',...a])

これをもっと減らすことができると確信しています。後でゴルフのないバージョンを追加します。


0

Javascript、98バイト

a=>{c="",l=0;for(w of a)while((i=w.indexOf(c))!=0||c!=w)alert(c=i!=0?c.substring(0,--l):c+w[l++])}

Port of JakobのJavaの答え

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.