Last active
June 25, 2021 18:13
-
-
Save xpqz/e4467da656ae37024be917cf045ee01d to your computer and use it in GitHub Desktop.
Knuth-Morris-Pratt prefix, dfn (⎕IO←0)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pfx←{ | |
s←⍵ | |
P←0⍴⍨≢⍵ | |
j←0 | |
{ | |
0=≢⍵:P | |
i←⊃⍵ | |
P[i]←j⊢←1+{⍵<0:⍵⋄s[⍵]=s[i]:⍵⋄0≤⍵-1:∇P[⍵-1]⋄¯1} j | |
∇1↓⍵ | |
} 1+⍳¯1+≢⍵ | |
} |
@dzaima offers the following tweak:
pfx←{
s←⍵
P←0⍴⍨≢⍵
j←0
0{
⍺=≢⍵:P
i←⍺⊃⍵
P[i]←j⊢←1+{⍵<0:⍵ ⋄ s[⍵]=s[i]:⍵ ⋄ 0≤⍵-1:∇ P[⍵-1] ⋄ ¯1}j
(⍺+1)∇ ⍵
}1+⍳¯1+≢⍵
}
@dzaima's version is as fast as the tradfn:
cmpx 'prefix d' 'pfx d'
┌→─────────────────────────────────────────────────────────────────┐
↓ prefix d → 2.3E¯1 | 0% ⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕│
│ pfx d → 2.3E¯1 | -1% ⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕⎕│
└──────────────────────────────────────────────────────────────────┘
Note to self: APL isn't Scheme.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is curiously slower than the tradfn version: