using System Collections Generic using System Linq namespace PocketGoo

 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
using System.Collections.Generic;
using System.Linq;
namespace PocketGoogle
{
public class Indexer : IIndexer
{
public static readonly char[] Seporators =
new char[] { ' ', '.', ',', '!', '?', ':', '-', '\r', '\n' };
private Dictionary<int, List<string>> documents = new Dictionary<int, List<string>>();
private Dictionary<string, List<int>> documentsList = new Dictionary<string, List<int>>();
public void Add(int id, string documentText)
{
var words = documentText.Split(Seporators).ToList();
documents.Add(id, words);
foreach (var item in words.Where(x => !string.IsNullOrEmpty(x)))
{
if (documentsList.ContainsKey(item))
{
if (!documentsList[item].Contains(id))
documentsList[item].Add(id);
}
else
documentsList.Add(item, new List<int> { id });
}
}
public List<int> GetIds(string word)
{
if (documentsList.ContainsKey(word))
return documentsList[word];
return new List<int>();
}
public List<int> GetPositions(int id, string word)
{
var result = new List<int>();
var startIndex = 0;
foreach (var item in documents[id].Where(x => x == word))
{
startIndex = documents[id].IndexOf(item, startIndex);
var length = documents[id].Take(startIndex)
.Aggregate(0, (count, nextWord) => count += nextWord.Length) + startIndex;
startIndex += 1;
result.Add(length);
}
return result;
}
public void Remove(int id)
{
if (documents.ContainsKey(id))
{
foreach (var item in documents[id].Where(x => documentsList.ContainsKey(x)))
documentsList[item].Remove(id);
documents.Remove(id);
}
}
}
}