Пример #1
0
        public int LevenshteinDistance <T>(T[] strOld,
                                           T[] strNew,
                                           IEqualityComparer <T> comparer = null,
                                           Func <Choice <T>, int> weight  = null,
                                           bool allowTransposition        = false)
        {
            var m1 = strOld.Length + 1;
            var m2 = strNew.Length + 1;

            if (comparer == null)
            {
                comparer = EqualityComparer <T> .Default;
            }

            if (weight == null)
            {
                weight = c => 1;
            }

            _ResizeArray(m1, m2);

            _num[0, 0] = 0;

            for (var i = 1; i < m1; i++)
            {
                _num[i, 0] = _num[i - 1, 0] + weight(Choice <T> .Remove(strOld[i - 1]));
            }
            for (var j = 1; j < m2; j++)
            {
                _num[0, j] = _num[0, j - 1] + weight(Choice <T> .Add(strNew[j - 1]));
            }

            for (var i = 1; i < m1; i++)
            {
                for (var j = 1; j < m2; j++)
                {
                    if (comparer.Equals(strOld[i - 1], strNew[j - 1]))
                    {
                        _num[i, j] = _num[i - 1, j - 1];
                    }
                    else
                    {
                        _num[i, j] = Math.Min(Math
                                              .Min(
                                                  _num[i - 1, j] + weight(Choice <T> .Remove(strOld[i - 1])),
                                                  _num[i, j - 1] + weight(Choice <T> .Add(strNew[j - 1]))
                                                  ),
                                              _num[i - 1, j - 1] + weight(Choice <T> .Substitute(strOld[i - 1], strNew[j - 1]))
                                              );

                        if (allowTransposition && i > 1 &&
                            j > 1 &&
                            comparer.Equals(strOld[i - 1], strNew[j - 2]) &&
                            comparer.Equals(strOld[i - 2], strNew[j - 1]))
                        {
                            _num[i, j] = Math.Min(_num[i, j],
                                                  _num[i - 2, j - 2] + weight(Choice <T> .Transpose(strOld[i - 1], strOld[i - 2])));
                        }
                    }
                }
            }

            return(_num[m1 - 1, m2 - 1]);
        }