Знайдіть непарний символ за малюнком


20

Вхідні дані

Перший рядок буде певним рядком, повтореним у будь-якій кількості разів. Наприклад, це може бути abcabcabcabc, [];[];[];і т.д. Це може бути відрізана; наприклад: 1231231231. Завжди знаходити найкоротший рядок; наприклад, якщо рядок 22222, то рядок 2, що не 22або 22222або що - небудь ще. Рядок завжди буде повторюватися щонайменше 2 повних рази.

Усі наступні рядки будуть зразком, зміщеним на будь-яке число. Наприклад, це можуть бути:

abcabcabc
cabcabcab
bcabcabca

(зсув на 1), або це може бути:

abcdefabcdefabcdefabc
cdefabcdefabcdefabcde
efabcdefabcdefabcdefa

(зсув на 4).

Один із символів у введенні буде неправильним. (Гарантовано не бути в першому рядку.) Наприклад, у цьому введенні:

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

1на лінії 3 є непарних один з.

Вихідні дані

Ви повинні вивести (нульові, починаючи з верхнього лівого) координати непарної. Наприклад, у наведеному вище вході є відповідний вихід 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?
Денніс

@Dennis Тільки що друкується ASCII (що в основному можна припустити для будь-якого виклику, пов’язаного з рядками; інакше нам доведеться вказати, що майже для кожного виклику: P)
Doorknob

Я так здогадався. Я думаю про підхід, який потребував би невикористаного чару, тому я подумав, що запитаю.
Денніс

Чи слід перевірити такий випадок: abc/cab/abc- і вивести 0 2тут?
користувач2846289

@VadimR Ні, оскільки лише один символ буде помилятися.
Дверна ручка

Відповіді:


7

Bash Perl, 231 229 218 178 164 166 138 106 74 байт

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

Сценарій вимагає використання -nперемикача, на який припадає два байти.

Ідея додавати дві копії всіх повних повторень шаблону взята з відповіді 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

( $nмістить відповідність субпартера, доступна через зворотний зв'язок \n.)


Розумний підхоплення блоку відповіді. Його можна оптимізувати одним байтом:^((.*?)(.*?))(?=\1+\2$)
Хайко Обердік

Я перейшов на мову, якою користуються популярні діти. Можливо, може бути ще більше гольф; це мій перший сценарій Perl за понад десятиліття ...
Денніс

2
... і ти запізнився на десятиліття, якщо ти думаєш, що
перлом

ця відповідь не отримує тієї любові, яку вона заслуговує. виглядає на мене як на переможця @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,$/}}}
  • Ця версія використовує оптимізований трюк для лову відповіді, дізнався у відповіді Денніса .
  • Оптимізація за допомогою властивості, що всі лінії мають однакові довжини.
  • Кінець рядка також потрібен для останнього рядка, інакше 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
        }
    }
}

Прекрасне рішення та коментарі, мені потрібно дізнатися більше
регексу

1
перше chopнепотрібне - його слід видалити. фінал exit printможна замінити die(додати, ,$/щоб приховати зайві речі (якщо потрібно)). також length$_можна замінити наy///c
ardnew

@ardnew: Велике спасибі, я видалив перший chop, тому що $відповідає новому рядку в кінці рядка. dieМені здається необхідним приховувати зайві речі через доданий новий рядок. Також y///cнабагато коротше length$_і на один байт коротше, ніж lengthбез зайвого $_.
Хайко Обердік

1
@ardnew: Я забув про багатослівність вмирати . Він навіть включає друкує номер рядка! Я буду використовувати це у своєму наступному оновленні.
Денніс

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

Пітона, 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

Введення йде через stdin. Я поясню це, якщо є попит, але це не схоже, що я все одно виграю.


1

Перл, 157 154

Редагувати : -3 завдяки пропозиції ardnew.

<>=~/^(((.*?).*?)\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 днів ;-)), і уявлення про алгоритм спочатку було невловимим (хоча я відчував, що він є там), але нарешті (і раптом) стало все зрозуміло.

Якщо довжина рядка кратна довжині шаблону, і навіть якщо рядок не починається з початку шаблону, об'єднувальна рядок із самим собою створить візерунок замість конкатенації (уявіть нескінченне повторення слова на круговій стрічці - місце зварювання не важливо). Отже, ідея полягає в тому, щоб обрізати лінію на множину одиниці довжини і об'єднати її в оригінал. Результат, навіть для рядка, що містить неправильний символ, гарантовано збігається з малюнком хоча б один раз. Звідти легко знайти позицію ображеного персонажа.

Перший рядок безсоромно запозичений у відповіді Хайко Обердік :-)

<>=~/^(((.*?).*?)\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". Для другого рядка match[4]буде yy; це має бути справедливим y.
Денніс

Перероблений і скорочений на 14 символів.
MT0

Дуже хороша! Я спробував той самий другий регулярний вираз в якийсь момент, але я додав мінімальну схему двічі замість максимальної (і, таким чином, вийшов з ладу). Одне незначне питання: Перший регулярний вираз повідомляє ababпро модель ababaababa; потрібно використовувати ^…$.
Денніс

/^…\n/працює або/^…$/m
MT0

1
Він може не потребувати ведучого ^(принаймні, це не для жодного з 6-ти тестових випадків, які я перерахував - але, мабуть, зустрічний приклад, де це робиться, я це залишив).
MT0,
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.