forked from factor/factor
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
z-algorithm: slightly faster by allocating and using an array.
- Loading branch information
Showing
1 changed file
with
12 additions
and
11 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,38 +1,39 @@ | ||
! Copyright (C) 2010 Dmitry Shubin. | ||
! See http://factorcode.org/license.txt for BSD license. | ||
USING: arrays combinators.smart kernel locals math math.ranges | ||
sequences sequences.private ; | ||
USING: arrays kernel locals math math.ranges sequences | ||
sequences.private ; | ||
IN: z-algorithm | ||
|
||
: lcp ( seq1 seq2 -- n ) | ||
[ min-length ] 2keep mismatch [ nip ] when* ; | ||
[ min-length dup ] 2keep mismatch-unsafe [ nip ] when* ; | ||
|
||
<PRIVATE | ||
|
||
:: out-of-zbox ( seq Z l r k -- seq Z l r ) | ||
seq k tail-slice seq lcp :> Zk | ||
Zk Z push seq Z | ||
Zk k Z set-nth seq Z | ||
Zk 0 > [ k Zk k + 1 - ] [ l r ] if ; inline | ||
|
||
:: inside-zbox ( seq Z l r k -- seq Z l r ) | ||
k l - Z nth :> Zk' | ||
r k - 1 + :> b | ||
seq Z Zk' b < | ||
[ Zk' Z push l r ] ! still inside | ||
[ Zk' k Z set-nth l r ] ! still inside | ||
[ | ||
seq r 1 + seq b [ tail-slice ] 2bi@ lcp :> q | ||
q b + Z push k q r + | ||
q b + k Z set-nth k q r + | ||
] if ; inline | ||
|
||
: (z-value) ( seq Z l r k -- seq Z l r ) | ||
: z-value ( seq Z l r k -- seq Z l r ) | ||
2dup < [ out-of-zbox ] [ inside-zbox ] if ; inline | ||
|
||
:: (z-values) ( seq -- Z ) | ||
V{ } clone 0 0 seq length :> ( Z l r len ) | ||
len Z push [ seq Z l r 1 len [a,b) [ (z-value) ] each ] | ||
drop-outputs Z ; inline | ||
seq length dup 0 <array> :> ( len Z ) | ||
len 0 Z set-nth | ||
seq Z 0 0 len [1,b) [ z-value ] each 4drop | ||
Z ; inline | ||
|
||
PRIVATE> | ||
|
||
: z-values ( seq -- Z ) | ||
dup length 0 > [ (z-values) ] when >array ; | ||
[ { } ] [ (z-values) ] if-empty ; |