Created
September 10, 2015 12:26
-
-
Save LarsVonQualen/f66da3cc5f0798488347 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace dk.odense.EnPlan.Utils | |
{ | |
public class WeightedSearch<TValue> | |
{ | |
private readonly List<TValue> _list; | |
private readonly List<Func<TValue, string, int>> _weights = new List<Func<TValue, string, int>>(); | |
public WeightedSearch(List<TValue> list) | |
{ | |
_list = list; | |
} | |
public WeightedSearch<TValue> AddWeight(Func<TValue, string, int> weight) | |
{ | |
_weights.Add(weight); | |
return this; | |
} | |
public IEnumerable<TValue> Search(string[] tokens) | |
{ | |
// Apply weights | |
var weighted = _list.Select(value => new | |
{ | |
Value = value, | |
Weight = | |
tokens.Aggregate(0, (tokenTotal, token) => tokenTotal + _weights.Aggregate(0, (weightTotal, weight) => weightTotal + weight(value, token))) | |
}); | |
// Order by weight | |
var ordered = weighted.OrderByDescending(arg => arg.Weight); | |
// Return the actual values | |
return ordered.Select(arg => arg.Value).ToList(); | |
} | |
public IEnumerable<TValue> SearchOptimized(List<string> tokens) | |
{ | |
var weigthed = new List<WeightedValue<TValue>>(); | |
foreach (var element in _list) | |
{ | |
var weigthedValue = new WeightedValue<TValue>() | |
{ | |
Value = element, | |
Weight = 0 | |
}; | |
foreach (var token in tokens) | |
{ | |
foreach (Func<TValue, string, int> t in _weights) | |
{ | |
weigthedValue.Weight += t(element, token); | |
} | |
} | |
weigthed.Add(weigthedValue); | |
} | |
return weigthed.Select(value => value.Value).ToList(); | |
} | |
} | |
class WeightedValue<TValue> | |
{ | |
public TValue Value { get; set; } | |
public int Weight { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment