-module(rinder). -export([naive/2, mp/2, mp/3,kmpsupply/1]). naive(X,T) -> % API entry: converts the lists/strings to tuples, computes the sizes, % and calls the real function with args X, T, size(X), size(T), I and J [loop counters]. XX=list_to_tuple(X), TT=list_to_tuple(T), M=size(XX), N=size(TT), log_to_screen("Going with ~p/~p ~p/~p~n",[XX,M,TT,N]), log_to_screen("Maximum iterations: ~p~n",[N*M-M*M+M]), naive(XX,TT,M,N,1,1). naive(X,T,M,N,I,J) when I>M -> % finished: found an occurence at pos j-m J-M; naive(X,T,M,N,I,J) when J>N -> % finished. Not found -1; naive(X,T,M,N,I,J) -> % Main loop. Cond=element(I,X), Cond2=element(J,T), case Cond2 of Cond -> naive(X,T,M,N,I+1,J+1); _ -> naive(X,T,M,N,1,J-I+2) end. mpsupply(X) -> XX=list_to_tuple(X), mp_supply(XX,size(XX)-1,1,[0]). mp_supply(X,M,J,S) when J>M -> list_to_tuple(S); mp_supply(X,M,J,S) -> I=mp__supply(X,M,J,S,element(J,list_to_tuple(S))), mp_supply(X,M,J+1,lists:flatten([S,I+1])). mp__supply(X,M,J,S,I) -> case I of 0 -> I; _ -> Cond=element(I,X), Cond2=element(J,X), case Cond of Cond2 -> I; _ -> mp__supply(X,M,J,S,element(I,list_to_tuple(S))) end end. mp(X,T) -> % API entry: converts the lists/strings to tuples, computes the sizes, and the supply function % and calls the real function with args X, T, size(X), size(T), % I and J [loop counters], and the supply function [as a tuple]. % Of course, since the next API entry does all this, just call it with J = 1 mp(X,T,1). mp(X,T,J) -> % same API entry as above with J [start position in the source string T] preset: % aka look for the *next* occurence % rinder:mp("cab","acabacabacab"). ==> 2 % rinder:mp("cab","acabacabacab",3). ==> 6 % rinder:mp("cab","acabacabacab",7). ==> 10 % rinder:mp("cab","acabacabacab",11). ==> -1 XX=list_to_tuple(X), TT=list_to_tuple(T), M=size(XX), N=size(TT), S=mpsupply(X), mp(XX,M,TT,N,1,J,S). mp(X,M,T,N,I,J,S) when I>M -> % finished. Found an occurence of x in t at position j-m J-M; mp(X,M,T,N,I,J,S) when J>N -> % finished. Not found. -1; mp(X,M,T,N,I,J,S) -> % main loop case I of 0 -> mp(X,M,T,N,I+1,J+1,S); _ -> Cond=element(J,T), Cond2=element(I,X), case Cond of Cond2 -> mp(X,M,T,N,I+1,J+1,S); _ -> mp(X,M,T,N,element(I,S),J,S) end end. log_to_screen(A,B) -> io:format(A,B).