Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
editdistance.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
4#include "editdistance.h"
5
7
8int editDistance(const QString &s, const QString &t)
9{
10#define D(i, j) d[(i)*n + (j)]
11 int i;
12 int j;
13 qsizetype m = s.size() + 1;
14 qsizetype n = t.size() + 1;
15 int *d = new int[m * n];
16 int result;
17
18 for (i = 0; i < m; ++i)
19 D(i, 0) = i;
20 for (j = 0; j < n; ++j)
21 D(0, j) = j;
22 for (i = 1; i < m; ++i) {
23 for (j = 1; j < n; ++j) {
24 if (s[i - 1] == t[j - 1]) {
25 D(i, j) = D(i - 1, j - 1);
26 } else {
27 int x = D(i - 1, j);
28 int y = D(i - 1, j - 1);
29 int z = D(i, j - 1);
30 D(i, j) = 1 + qMin(qMin(x, y), z);
31 }
32 }
33 }
34 result = D(m - 1, n - 1);
35 delete[] d;
36 return result;
37#undef D
38}
39
40QString nearestName(const QString &actual, const QSet<QString> &candidates)
41{
42 if (actual.isEmpty())
43 return QString();
44
45 int deltaBest = 10000;
46 int numBest = 0;
47 QString best;
48
49 for (const auto &candidate : candidates) {
50 if (candidate[0] == actual[0]) {
51 int delta = editDistance(actual, candidate);
52 if (delta < deltaBest) {
53 deltaBest = delta;
54 numBest = 1;
55 best = candidate;
56 } else if (delta == deltaBest) {
57 ++numBest;
58 }
59 }
60 }
61
62 if (numBest == 1 && deltaBest <= 2 && actual.size() + best.size() >= 5)
63 return best;
64
65 return QString();
66}
67
68/*!
69 Returns a suggestion for the closest match to \a str in the given
70 \a commandSet. If no closest match is found, or if it is in the supplied
71 \a excludeSet containing matches to avoid, returns an empty string.
72*/
73QString suggestName(const QString &str, const QSet<QString> &commandSet,
74 const QSet<QString> &excludeSet)
75{
76 QString best = nearestName(str, commandSet);
77 if (best.isEmpty() || excludeSet.contains(best))
78 return QString();
79 return best;
80}
81
82QT_END_NAMESPACE
QString suggestName(const QString &str, const QSet< QString > &commandSet, const QSet< QString > &excludeSet)
Returns a suggestion for the closest match to str in the given commandSet.
QT_BEGIN_NAMESPACE int editDistance(const QString &s, const QString &t)
#define D(i, j)
QString nearestName(const QString &actual, const QSet< QString > &candidates)
Combined button and popup list for selecting options.