15
\$\begingroup\$

Task

The task is to golf a real-time exact string matching algorithm of your choice.

Input

Two lines of text supplied on standard input, separated by a new line. The first line contains the "pattern" and will simply be an ASCII string drawn from the letters a-z.

The second line contains the longer "text" and will also simply be an ASCII string drawn from the letters a-z.

Output

A list of indices of where the exact matches occur. You should output the position of the start of each match that occurs.

Specification

Your algorithm can spend linear time preprocessing the pattern. It must then read the text from left to right and take constant time for every single character in the text and output any new match as soon as it occurs. Matches can of course overlap each other.

Algorithm

There are many real-time exact matching algorithms. One is mentioned on the wiki for KMP for example. You can use any one you like but you must always output the right answer.

I will keep a per language leader table so that those who prefer popular languages can also win in their own way. Please explain which algorithm you have implemented.

Real-time

It seems there has been a lot of confusion over what real-time means. It doesn't simply mean linear time. So standard KMP is not real-time. The link in the question explicitly points to a part of the wiki page for KMP about a real-time variant of KMP. Neither is Boyer-Moore-Galil real-time. This cstheory question/answer discusses the issue or one can just google "real-time exact matching" or similar terms.

\$\endgroup\$
  • \$\begingroup\$ am I correct in assuming that vectorized answers don't count? i.e., we MUST traverse the text linearly? \$\endgroup\$ – sirpercival Apr 29 '15 at 14:13
  • \$\begingroup\$ So if I had the strings abcd and acbdefg, I would output 1 4, for a and d? \$\endgroup\$ – ASCIIThenANSI Apr 29 '15 at 15:11
  • \$\begingroup\$ I don't think that's right, both a and d match. There is abcd and acbdefg, and the a and d are at identical positions. \$\endgroup\$ – ASCIIThenANSI Apr 29 '15 at 15:13
  • 1
    \$\begingroup\$ @ASCIIThenANSI YES! :) \$\endgroup\$ – user9206 Apr 29 '15 at 15:17
  • 1
    \$\begingroup\$ Why are we having 1 based indexes here ? -.- \$\endgroup\$ – Optimizer Apr 30 '15 at 19:10
3
\$\begingroup\$

Python 2, 495 bytes

This one is a real-time KMP, which is a lot shorter and only slightly slower than the BMG algorithm (which is usually sublinear). Call with K(pattern, text); output is identical to the BMG algorithm.

L,R,o=len,range,lambda x:ord(x)-97
def K(P,T):
 M,N=L(P),L(T);Z=[0]*M;Z[0]=M;r=l=0
 for k in R(1,l):
    if k>r:
     n=0
     while n+k<l<P[n]==P[n+k]:n+=1
     Z[k]=n
     if n>0:l,r=k,k+n-1
    else:
     p,_=k-l,r-k+1
     if Z[p]<_:Z[k]=Z[p]
     else:
        i=r+1
        while i<M<P[i]==P[i-k]:i+=1
        Z[k],l,r=i-k,k,i-1
 F=[[0]*26]*M
 for j in R(M-1,0,-1):z=Z[j];i,x=j+z-1,P[z+1];F[i][o(x)]=z
 s=m=0
 while s+m<N:
    c=T[s+m]
    if c==P[m]:
     m+=1
     if m==M:print s,;s+=1;m-=1
    else:
     if m==0:s+=1
     else:f=F[m][o(c)];s+=m-f;m=f
\$\endgroup\$
  • \$\begingroup\$ Which reference did you use for real-time KMP out of interest? \$\endgroup\$ – user9206 May 1 '15 at 6:36
  • \$\begingroup\$ The search algorithm was an amalgam of several, but the real-time part came primarily from this with a dash of Wikipedia. \$\endgroup\$ – sirpercival May 1 '15 at 11:10
2
\$\begingroup\$

Python 2, 937 bytes

This ain't short, by any means, but it (a) works, (b) satisfies all the requirements, and (c) is golfed as much as I can possibly make it.

L,r,t,o,e,w=len,range,26,lambda x:ord(x)-97,enumerate,max
def m(s,M,i,j,c=0):
 while i<M-c>j<s[i+c]==s[j+c]:c+=1
 return[c,M-i][i==j]
def Z(s):
 M=L(s)
 if M<2:return[[],[1]][M]
 z=[0]*M;z[0:2]=M,m(s,M,0,1)
 for i in r(2,1+z[1]):z[i]=z[1]-i+1
 l=h=0
 for i in r(2+z[1],M):
    if i<=h:k=i-l;b,a=z[k],h-i+1;exec["z[i]=b+m(s,M,a,h+1);l,h=i,i+z[i]-1","z[i]=b","z[i]=min(b,M-i);l,h=i,i+z[i]-1"][cmp(a,b)]
    else:
     z[i]=m(s,M,0,i)
     if z[i]>0:l,h=i,i+z[i]-1
 return z
def S(P,T):
 M,N=L(P),L(T)
 if not 0<M<N:return
 R,a=[[-1]]*t,[-1]*t
 for i,c in e(P):
    a[o(c)]=i
    for j in r(t):R[j]+=a[j],
 if M<=0:R=[[]]*t
 n,F,z,l=Z(P[::-1])[::-1],[0]*M,Z(P),0;G=[[-1,M-n[j]][n[j]>0]for j in r(M-1)]
 for i,v in e(z[::-1]):l=[l,w(v,l)][v==i+1];F[~i]=l
 k,p=M-1,-1
 while k<N:
    i,h=M-1,k
    while 0<=i<[]>h>p<P[i]==T[h]:i-=1;h-=1
    if i<0 or h==p:print-~k-M,;k+=[1,M-F[1]][M>1]
    else:c,q=i-R[o(T[h])][i],i+1;s=w(c,q==M or M-[G,F][G[q]<0][q]);p=[p,k][s>=q];k+=s

This is an implementation of the Boyer-Moore-Galil algorithm. Pretty straightforward - call with S(pattern,text); the other two functions are used in preprocessing. Indeed, everything but the last 5 lines is preprocessing.

An example run, which took about a second:

>>> a = 'a'*1000
>>> b = 'a'*1999 + 'b'
>>> S(a,b)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
\$\endgroup\$
  • \$\begingroup\$ I am not sure this is real-time is it? \$\endgroup\$ – user9206 May 1 '15 at 6:36
  • \$\begingroup\$ Boyer-Moore-Galil runs in a worst case of O(n+m). It's actually faster than KMP. \$\endgroup\$ – sirpercival May 1 '15 at 11:05
  • \$\begingroup\$ But real-time is the not the same as linear time. \$\endgroup\$ – user9206 May 1 '15 at 12:06
  • \$\begingroup\$ Under "specifications" it says that the algorithm must run in O(m) preprocessing and O(n) matching [=> O(n+m)], which this does (or better). \$\endgroup\$ – sirpercival May 1 '15 at 14:14
  • \$\begingroup\$ Yes but that isn't what real-time means. The whole thing could run in O(n+m) time but take n time for one of the symbols in the text, example. \$\endgroup\$ – user9206 May 1 '15 at 14:31
1
\$\begingroup\$

KMP, Python 2(213 bytes)

R=raw_input
E=enumerate
p=R()
t=R()
f=[-1]*((len(p)+1))
j=-1
for i,c in E(p):
 while j+1 and p[j]!=c:j=f[j]
 f[i+1]=j=j+1
j=-1
for i,c in E(t):
 while j+1 and p[j]!=c:j=f[j]
 j+=1
 if j==len(p):print i+1-j;j=f[j]

Ungolfed version. The first loop is to build up the KMP automata. The second loop is walking on the automata. They share nearly the same pattern but abstracting them out will cost more bytes so for a code golf I'd rather duplicate this logic. Similar implementation is actually widely used in programing contests.

pattern = raw_input()
text = raw_input()

fail = [-1] * (len(pattern) + 1)
j = -1
for i, c in enumerate(pattern):
    while j >= 0 and pattern[j] != c:
        j = fail[j]
    j += 1
    fail[i + 1] = j

j = -1
for i, c in enumerate(text):
    while j >= 0 and pattern[j] != c:
        j = fail[j]
    j += 1
    if j == len(pattern):
        print i + 1 - j
        j = fail[j]
\$\endgroup\$
  • \$\begingroup\$ This isn't real-time sadly. See the wiki link in the question. \$\endgroup\$ – user9206 May 3 '15 at 16:16
1
\$\begingroup\$

Realtime KMP, Python 2(167 bytes)

R=raw_input
E=enumerate
P=R()
T=R()
F=[{}]
for i,c in E(P):j=F[i].get(c,0);F+=[dict(F[j])];F[i][c]=i+1
j=0
for i,c in E(T):
 j=F[j].get(c,0)
 if j==len(P):print i+1-j

In normal KMP, we simulate the automaton behavior by using a fail function. In this realtime KMP, the full automaton is constructed so that in the matching phrase it can process each character in realtime(constant time).

The preprocessing time and space complexity is O(n m), where m is the alphabet size and n is the length of pattern string. However, in my tests, the actual size of transition table is always less than 2n so maybe we can prove that the time and space complexity is O(n).

Ungolfed version

pattern = raw_input()
text = raw_input()

# transitions[i][c] points to the next state walking from state i by c.
# Transition that point to staet 0 are not stored.
# So use transitions[i].get(c, 0) instead of transitions[i][c]
transitions = [{}]
for i, c in enumerate(pattern):
    j = transitions[i].get(c, 0)
    transitions.append(transitions[j].copy())
    # Before this assignment, transitions[i] served as the fail function
    transitions[i][c] = i + 1

j = 0
for i, c in enumerate(text):
    j = transitions[j].get(c, 0)
    if j == len(pattern):
        print i + 1 - j
\$\endgroup\$
  • \$\begingroup\$ Well, sadly, hash table in Python isn't realtime so the implementation here isn't realtime either. \$\endgroup\$ – Ray May 4 '15 at 3:51
1
\$\begingroup\$

Q, 146 Bytes

W:S:u:"";n:0;p:{$[n<#x;0;x~(#x)#W;#x;0]};f:{{|/p'x}'((1_)\x#W),\:/:u};F:{S::x 1;W::*x;n::#W;u::?W;T:(f'!1+n),\:0;(&n=T\[0;u?S])-n-1}

Test

F"
 ABCDABD
 ABCdABCDABgABCDABCDABDEABCDABzABCDABCDABDE"

generates 15 and 34

Notes

Not restricted to alphabet (support any ascii char, and is case-sensitive).

Not uses any of the specific operations defined by Q over strings -> works on strings as sequences (ops match, length, etc.)

Minimizes transition table joining all characters not in pattern as one unique character-class.

I can squeeze code a little. It's a first attempt to validate solution strategy

Visit any character of text exactly once, and for each input character there is a unique jump. So I assume that search fits as 'real time'

Table construction al state i and char c search for longest substring that ends at i and after appending c is a prefix of S. Construction is not optimized, so i don't know if its valid

Input format doesn't fit well with language. Passing two string arguments will save 16 Bytes

Explanation

global W represents pattern and S corresponds to text to search

x:1_"\n "\:x weird code to cope with input requirements (Q requires thtat multiline strings has non-first lines indented, so it must discard added space in front of every non-first line)

n::#W calculates W lenght and save as global n

u::?W calculates unique chars in W, and save as global u

u?S generates the characted-class for each char of S

Construct a transition table T with one row per unique character in W (plus one extra), and a column for each index in W (plus one extra). Extra row correspond to initial state, and extra column collects any char in S but not in W. This strategy minimizes table size

p:{$[n<#x;0;x~(#x)#W;#x;0]} is the function that search longest prefix

f:{{|/p'x}'((1_)\x#W),\:/:u} is the function that calculates a row x of T

T:(f'!1+n),\:0 applies f repeteadly to calculate each row, and adds value 0 to each row

Search text using transition table. T\[0;u?S] iterates over 0 (initial state) and each of the character class of S, using as a new value the value at transitition table T[state][charClass]. Final states has value n, so we look for that value in the sequence of states and returns it adjusted (to indicate initial instead of final position of each match)

\$\endgroup\$
0
\$\begingroup\$

Boyer-Moore, Perl (50)

Perl attempts to use Boyer-Moore naturally:

$s=<>;$g=<>;chomp$g;print"$-[0] "while$s=~m/($g)/g
\$\endgroup\$
  • \$\begingroup\$ This is not real time sadly. \$\endgroup\$ – user9206 May 2 '15 at 13:22
  • \$\begingroup\$ What do you mean by "real time"? \$\endgroup\$ – protist May 2 '15 at 13:28
  • \$\begingroup\$ Constant time for every symbol of the text that is read in. See the wiki link I pasted. \$\endgroup\$ – user9206 May 2 '15 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy