パターンで奇妙な文字を見つける


20

入力

最初の行は、特定の文字列が何回も繰り返されます。例えば、それができるabcabcabcabc[];[];[];等これは、切断されてもよいです。例:1231231231。常に最も短い文字列を見つけます。たとえば、行がの場合、22222文字列は2、ではない2222222またはその他のものです。文字列は常に少なくとも2回は繰り返されます。

後続のすべての行は、任意の数だけオフセットされたパターンになります。たとえば、次のようになります。

abcabcabc
cabcabcab
bcabcabca

(1オフセット)、または次のようになります。

abcdefabcdefabcdefabc
cdefabcdefabcdefabcde
efabcdefabcdefabcdefa

(4オフセット)。

入力の文字の1つが間違っています。(最初の行にないことが保証されています。)たとえば、次の入力では:

a=1a=1a=1
=1a=1a=1a
1a=11=1a=
a=1a=1a=1
=1a=1a=1a

13行目は奇数1つのアウトです。

出力

奇数の座標の出力(左上から開始するゼロベース)を出力する必要があります。たとえば、上記の入力では、対応する出力は4,2です。また、出力をしてもよい4 2、または"4""2"、あるいは[[4],[2]]、または任意の他の形式は、限り、あなたは出力が可能になっているものを言うことができるように。

テストケース

入力:

codegolfcodegolfco
egolfcodegolfcodeg
lfcodegolfcodegoff
odegolfcodegolfcod
golfcodegolfcodego
fcodegolfcodegolfc

出力: 16,2

入力:

][[][][[][][[][][[][][[
[][][[][][[][][[][][[][
[][[][][[][][[][][[][][
[[][][[]]][[][][[][][[]

出力: 8,3

入力:

...
. .
...

出力: 1,1

入力:

ababa
babab
ababb
babab

出力: 4,2

行け!


文字列にはどの文字を含めることができますか?印刷可能なASCII?ASCII?Unicode?
デニス14年

@Dennisだけで印刷可能なASCII(基本的に文字列を含む任意の挑戦のために仮定することができ、そうでない場合は、我々は、ほとんどすべての挑戦のためにそれを指定する必要があります:P)
ドアノブ

そう思いました。私は未使用のcharを必要とするアプローチを考えているので、尋ねたいと思いました。
デニス14年

このようなケースをチェックする必要がabc/cab/abcあります:-そして、0 2ここに出力しますか?
user2846289 14年

@VadimRいいえ、1文字だけが間違っているためです。
ドアノブ

回答:


7

バッシュのPerl、231 229 218 178 164 166 138 106 74のバイト

/^(((.*).*)\2+)\3$/;$_.=$1x2;$.--,die$+[1]if/^(.*)(.)(.*)
.*\1(?!\2).\3/

スクリプトでは、-nスイッチを使用する必要がありますが、これは2バイトを占めています。

パターンのすべての完全な繰り返しの2つのコピーを追加するというアイデアは、MT0の回答から取られました。

他のすべての答えとは対照的に、このアプローチは各反復で現在の入力行のパターンを抽出しようとします。奇数文字を含む行で失敗します(代わりに前の行のパターンを使用します)。これは、ループにパターン抽出を含めるために行われ、数バイトを節約することができます。

ゴルフされていないバージョン

#!/usr/bin/perl -n

# The `-n' switch makes Perl execute the entire script once for each input line, just like
# wrapping `while(<>){…}' around the script would do.

/^(((.*).*)\2+)\3$/;

# This regular expression matches if `((.*).*)' - accessible via the backreference `\2' -
# is repeated at least once, followed by a single repetition of `\3" - zero or more of the
# leftmost characters of `\2' - followed by the end of line. This means `\1' will contain
# all full repetitions of the pattern. Even in the next loop, the contents of `\1' will be
# available in the variable `$1'.

$_.=$1x2;

# Append two copies of `$1' to the current line. For the line, containing the odd
# character, the regular expression will not have matched and the pattern of the previous
# line will get appended.
#
# Since the pattern is repeated at least two full times, the partial pattern repetition at
# the end of the previous line will be shorter than the string before it. This means that
# the entire line will the shorter than 1.5 times the full repetitions of the pattern, 
# making the two copies of the full repetitions of the pattern at least three times as 
# long as the input lines.

$.-- , die $+[1] if

# If the regular expression below matches, do the following:
#
#   1. Decrement the variable `$.', which contains the input line number.
#
#      This is done to obtain zero-based coordinates.
#
#   2. Print `$+[1]' - the position of the last character of the first subpattern of the
#      regular expression - plus some additional information to STDERR and exit.
#
#      Notably, `die' prints the (decremented) current line number.

/^(.*)(.)(.*)
.*\1(?!\2).\3/;

# `(.*)(.)(.*)', enclosed by `^' and a newline, divides the current input line into three
# parts, which will be accesible via the backreferences `\1' to `\3'. Note that `\2'
# contains a single character.
#
# `.*\1(?!\2).\3' matches the current input line, except for the single character between
# `\1' and `\3' which has to be different from that in `\2', at any position of the line
# containing the pattern repetitions. Since this line is at least thrice as long as
# `\1(?!\2).\3', it will be matched regardless of by how many characters the line has been
# rotated.

テストケース用

codegolfcodegolfco
egolfcodegolfcodeg
lfcodegolfcodegoff
odegolfcodegolfcod
golfcodegolfcodego
fcodegolfcodegolfc

ゴルフバージョンの出力は

16 at script.pl line 1, <> line 2.

奇妙なキャラクターが座標を持っていることを意味し16,2ます。

この露骨な乱用は、リベラルな出力形式を利用しています。

終了する直前、Perlのいくつかの特殊変数の内容は次のとおりです。

$_  = lfcodegolfcodegoff\ncodegolfcodegolfcodegolfcodegolf
$1  = lfcodegolfcodego
$2  = f
$3  = f

$nbackreferenceを介してアクセス可能なサブパターンの一致が含まれています\n。)


返信ユニットの巧妙なキャッチ。:それは1つのバイトによって最適化することができます^((.*?)(.*?))(?=\1+\2$)
ハイコOberdiek

人気のある子供たちが使用している言語に切り替えました。おそらくさらにゴルフダウンできます。これは...十年以上に私の最初のPerlスクリプトです
デニス・

2
...そしてあなたはperlが人気の子供たちが使用しているものだと思います下旬場合十年だ
ardnew

この答えは、それに値する愛を得ていません。勝者のように見える@Doorknob
ardnew

8

Perl、212 191 181 168バイト

$_=<>;/^(((.*?)(.*?))\2+)\3$/;$x=$1x4;while(<>){chop;$x=~/\Q$_\E/&&next;for$i(0..y///c-1){for$r(split//,$x){$b=$_;$b=~s/(.{$i})./$1$r/;$x=~/\Q$b\E/&&die$i,$",$.-1,$/}}}
  • このバージョンでは、デニスのanswerで学習した応答ユニットをキャッチするための最適化されたトリックを使用しています
  • すべての行の長さが等しいというプロパティを使用した最適化。
  • 最後の行には行末も必要です。それ以外の場合は、chomp代わりにchop使用する必要があります。
  • ardnewのコメントの最適化が追加されました。

古いバージョン、212バイト:

$_=<>;chop;/^(.+?)\1+(??{".{0,".(-1+length$1).'}'})$/;$;=$1;while(<>){$x=$;x length;chop;$x=~/\Q$_\E/&&next;for$i(0..-1+length$_){for$r(split//,$;){$b=$_;$b=~s/(.{$i})./$1$r/;$x=~/\Q$b\E/&&exit print$i,$",$.-1}}}

ゴルフされていないバージョン:

$_ = <>;  # read first line
/^(((.*?)(.*?))\2+)\3$/;
# The repeat unit \2 consists of \3 and \4,
# and the start part \2 can be added at the end (as partial or even full unit).
$x = $1 x 4; # $x is long enough to cover each following line

# Old version:
# /^(.+?)\1+(??{ ".{0," . (-1 + length $1) . '}' })$/;
# $a = $1; # $a is the repeat unit.
# The unit is caught by a non-greedy pattern (.+?) that is
# repeated at least once: \1+
# The remaining characters must be less than the unit length.
# The unit length is known at run-time, therefore a "postponed"
# regular expression is used for the remainder.

# process the following lines until the error is found
while (<>) {
    # old version:
    # $x = $a x length;
    # $x contains the repeated string unit, by at least one unit longer
    # than the string in the current line
    chop; # remove line end of current line
    $x =~ /\Q$_\E/ && next;
          # go to next line, if current string is a substring of the repeated units;
          # \Q...\E prevents the interpretation of special characters
    # now each string position $x is checked, if it contains the wrong character:
    for $i (0 .. y///c - 1) {  # y///c yields the length of $_
        for $r (split //, $x) { #/ (old version uses $a)
            # replace the character at position $i with a
            # character from the repeat unit
            $b = $_;
            $b =~ s/(.{$i})./$1$r/;
            $x =~ /\Q$b\E/
               && die $i, $", $. - 1, $/;
               # $" sets a space and the newline is added by $/;
               # the newline prevents "die" from outputting line numbers
        }
    }
}

素晴らしい解決策とコメント、より多くの正規表現を学ぶ必要があります;)
Newbrict 14年

1
最初のものchopは不要です。削除する必要があります。最終版exit printは(必要に応じて追加のものを隠すためにdie追加,$/する)に置き換えることができます。また、length$_に置き換えることができますy///c
ardnew

@ardnew:文字列の最後の改行の前に一致するchopため、最初のを削除しました$die追加された改行を介して余分なものを隠すことは私にとって必要なようです。また、不必要なものy///cよりもはるかに短くlength$_、1バイト短くlengthなり$_ます。
ヘイコOberdiek 14年

1
@ardnew:dieの冗長性を忘れていました。行番号の印刷も含まれています!次の更新でそれを使用します。
デニス14年

3

C、187バイト

制限。

  • 98文字より長い入力文字列を使用しないでください:)

ゴルフバージョン

char s[99],z[99],*k,p,i,I,o,a;c(){for(i=0;k[i]==s[(i+o)%p];i++);return k[i];}main(){for(gets(k=s);c(p++););for(;!(o=o>p&&printf("%d,%d\n",I,a))&&gets(k=z);a++)while(o++<p&&c())I=I<i?i:I;}

ゴルフされていないバージョン

char s[99],z[99],*k,p,i,I,o,a;

c()
{
    for(i=0
       ;k[i]==s[(i+o)%p]
       ;i++)
       ;
    return k[i];
}

main()
{
    for(gets(k=s);c(p++);)
         ;
    for(;!(o=o>p&&printf("%d,%d\n",I,a)) && gets(k=z);a++)
           while(o++ < p && c())
            I=I<i?i:I;
}

2

Python、303 292

r=raw_input
R=range
s=r()
l=len(s)
m=1
g=s[:[all((lambda x:x[1:]==x[:-1])(s[n::k])for n in R(k))for k in R(1,l)].index(True)+1]*l*2
while 1:
 t=r()
 z=[map(lambda p:p[0]==p[1],zip(t,g[n:l+n]))for n in R(l)]
 any(all(y)for y in z)or exit("%d,%d"%(max(map(lambda b:b.index(False),z)),m))
 m+=1

入力は標準入力を通過します。需要があれば説明しますが、とにかく勝つつもりはないようです。


1

Perl、157 154

編集:ardnewの提案のおかげで-3。

<>=~/^(((.*?).*?)\2+)\3$/;$p=$2;$n=$+[1];while(<>){s/.{$n}/$&$&/;/(\Q$p\E)+/g;$s=$p;1while/./g*$s=~/\G\Q$&/g;print$n>--($m=pos)?$m:$m-$n,$",$.-1,$/if pos}

しばらく時間がかかりました(もちろん、5日ではなくオンとオフです;-))、アルゴリズムについての考えは最初はとらえどころのないものでした(そこにあると感じましたが)が、最終的に(そして突然)すべてが明らかになりました。

文字列の長さがパターンの長さの倍数であり、文字列がパターンの先頭で始まっていなくても、文字列をそれ自体と連結すると、連結の代わりにパターンが生成されます(円形リボン上の単語の無限の繰り返しを想像してください-溶接は重要ではありません)。したがって、アイデアは、ラインを複数のユニット長にトリミングし、元のラインを連結することです。結果は、間違った文字を含む文字列であっても、少なくとも1回はパターンと一致することが保証されています。そこから、問題のキャラクターの位置を見つけるのは簡単です。

最初の行は、Heiko Oberdiekの答えから恥知らずに借用されています:-)

<>=~/^(((.*?).*?)\2+)\3$/;      # Read first line, find the repeating unit
$p=$2;                          # and length of whole number of units.
$n=$+[1];                       # Store as $p and $n.
while(<>){                      # Repeat for each line.
    s/.{$n}/$&$&/;              # Extract first $n chars and
                                # append original line to them.
    /(\Q$p\E)+/g;               # Match until failure (not necessarily from the
                                # beginning - doesn't matter).
    $s=$p;                      # This is just to reset global match position
                                # for $s (which is $p) - we could do without $s,
                                # $p.=''; but it's one char longer.
                                # From here, whole pattern doesn't match -
    1while/./g*$s=~/\G\Q$&/g;   # check by single char.
                                # Extract next char (if possible), match to 
                                # appropriate position in a pattern (position 
                                # maintained by \G assertion and g modifier).
                                # We either exhaust the string (then pos is 
                                # undefined and this was not the string we're
                                # looking for) or find offending char position.

    print$n>--($m=pos)?$m:$m-$n,$",$.-1,$/if pos
}

1
よくやった。私はあなたが交換することができると思う/.{$n}/;$_=$&.$_;s/.{$n}/$&$&/;
ardnew

1

JavaScript(ES6)-147 133 136文字

s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

テスト対象の文字列が変数内にあることを期待しs、結果をコンソールに出力します。

var repetitionRE = /^(((.*).*)\2+)\3\n/;
                                        // Regular expression to find repeating sequence
                                        // without any trailing sub-string of the sequence.
var sequence = repetitionRE.exec(s)[1]; // Find the sequence string.
s.split('\n')                           // Split the input into an array.
 .map(
   ( row, index ) =>                    // Anonymous function using ES6 arrow syntax
   {
     var testStr = row + '᛫'+ sequence + sequence;
                                        // Concatenate the current row, a character which won't
                                        // appear in the input and two copies of the repetitions
                                        // of the sequence from the first line.
     var match = /^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(testStr);
                                        // Left of the ᛫ finds sub-matches for a single
                                        // character and the sub-strings before and after.
                                        // Right of the ᛫ looks for any number of characters
                                        // then the before and after sub-matches with a
                                        // different character between.
      if ( match )
       console.log( match[1].length, index );
                                        // Output the index of the non-matching character
                                        // and the row.
   }         
 );

テストケース1

s="codegolfcodegolfco\negolfcodegolfcodeg\nlfcodegolfcodegoff\nodegolfcodegolfcod\ngolfcodegolfcodego\nfcodegolfcodegolfc"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

出力

16 2

テストケース2

s="][[][][[][][[][][[][][[\n[][][[][][[][][[][][[][\n[][[][][[][][[][][[][][\n[[][][[]]][[][][[][][[]"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

出力

8 3

テストケース3

s="...\n. .\n..."
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

出力

1 1

テストケース4

s="ababa\nbabab\nababb\nbabab"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

出力

4 2

テストケース5

s="xyxy\nyyxy"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

出力

0 1

テストケース6

s="ababaababa\nababaaaaba"
s.split('\n').map((x,i)=>(v=/^(.*)(.)(.*)᛫.*\1(?!\2).\3/.exec(x+'᛫'+(a=/^(((.*).*)\2+)\3\n/.exec(s)[1])+a))&&console.log(v[1].length,i))

出力

6 1

悲しいことに、このアプローチは、例えば、次の場合に失敗しs="xyxy\nyyxy"。2行目match[4]yy; になります。それだけである必要がありyます。
デニス14年

再加工され、14文字短縮されました。
MT0 14年

非常に素晴らしい!ある時点でまったく同じ2番目の正規表現を試しましたが、最大パターンの代わりに最小パターンを2回追加しました(したがって、惨めな失敗に終わりました)。1つの小さな問題:最初の正規表現はababababaababa; のパターンを報告します。を使用する必要があります^…$
デニス14年

/^…\n/作品や/^…$/m
MT0

1
先行する必要はないかもしれません^(少なくとも、私がリストした6つのテストケースのいずれにも必要ありません。しかし、おそらくそれを残した反例があります)。
MT0 14年
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.