-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
NaiveStringSearch.fs
52 lines (50 loc) · 1.46 KB
/
NaiveStringSearch.fs
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
namespace Algorithms.Strings
/// <summary>
/// https://en.wikipedia.org/wiki/String-searching_algorithm#Na%C3%AFve_string_search
///
/// This algorithm tries to find the pattern from every position of
/// the mainString if pattern is found from position i it add it to
/// the answer and does the same for position i+1
/// </summary>
///
/// <remarks>
/// Complexity : O(n*m)
/// n=length of main string
/// m=length of pattern string
/// </remarks>
module NaiveStringSearch =
/// <summary>
/// </summary>
/// <example>
/// <code>
/// naive_pattern_search("ABAAABCDBBABCDDEBCABC", "ABC")
/// [4, 10, 18]
///
/// naive_pattern_search("ABC", "ABAAABCDBBABCDDEBCABC")
/// []
///
/// naive_pattern_search("", "ABC")
/// []
///
/// naive_pattern_search("TEST", "TEST")
/// [0]
///
/// naive_pattern_search("ABCDEGFTEST", "TEST")
/// [7]
/// </code>
/// </example>
/// <param name="s"></param>
/// <param name="pattern"></param>
/// <returns>List of positions</returns>
let naivePatternSearch (s: string, pattern: string): int list =
s.ToCharArray()
|> Seq.mapi
(fun i x ->
let myv = pattern.[0]
if x = pattern.[0] then
(i, s.[i..(i + (pattern.Length - 1))])
else
(i, ""))
|> Seq.where (fun (i, x) -> pattern = x)
|> Seq.map (fun (i, x) -> i)
|> List.ofSeq