WIP
DirectOutput framework for virtual pinball cabinets WIP
Go to:
Overview 
DiceCoefficientExtensions.cs
Go to the documentation of this file.
1 /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2  * modified by Tyler Jensen from
3  * http://www.codeguru.com/vb/gen/vb_misc/algorithms/article.php/c13137__1/Fuzzy-Matching-Demo-in-Access.htm
4  * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
5 
6 using System;
7 using System.Collections.Generic;
8 using System.Linq;
9 using System.Text;
10 
11 namespace FuzzyStrings
12 {
13  public static class DiceCoefficientExtensions
14  {
22  public static double DiceCoefficient(this string input, string comparedTo)
23  {
24  var ngrams = input.ToBiGrams();
25  var compareToNgrams = comparedTo.ToBiGrams();
26  return ngrams.DiceCoefficient(compareToNgrams);
27  }
28 
35  private static double DiceCoefficient(this string[] nGrams, string[] compareToNGrams)
36  {
37  int matches = 0;
38  foreach (var nGram in nGrams)
39  {
40  if (compareToNGrams.Any(x => x == nGram)) matches++;
41  }
42  if (matches == 0) return 0.0d;
43  double totalBigrams = nGrams.Length + compareToNGrams.Length;
44  return (2 * matches) / totalBigrams;
45  }
46 
47  private static string[] ToBiGrams(this string input)
48  {
49  // nLength == 2
50  // from Jackson, return %j ja ac ck ks so on n#
51  // from Main, return #m ma ai in n#
52  input = SinglePercent + input + SinglePound;
53  return ToNGrams(input, 2);
54  }
55 
56  private static string[] ToTriGrams(this string input)
57  {
58  // nLength == 3
59  // from Jackson, return %%j %ja jac ack cks kso son on# n##
60  // from Main, return ##m #ma mai ain in# n##
61  input = DoublePercent + input + DoublePount;
62  return ToNGrams(input, 3);
63  }
64 
65  private static string[] ToNGrams(string input, int nLength)
66  {
67  int itemsCount = input.Length - 1;
68  string[] ngrams = new string[input.Length - 1];
69  for (int i = 0; i < itemsCount; i++) ngrams[i] = input.Substring(i, nLength);
70  return ngrams;
71  }
72 
73  private const string SinglePercent = "%";
74  private const string SinglePound = "#";
75  private const string DoublePercent = "&&";
76  private const string DoublePount = "##";
77  }
78 }