Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dart Refactor Levenshtein distance calculation in code.dart #262

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 34 additions & 23 deletions levenshtein/dart/code.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,38 @@ int levenshteinDistance(String word1, String word2) {
final m = word1.length;
final n = word2.length;
// Create a matrix to store distances
var matrix = List.generate(m+1, (i) => List.generate(n+1, (j) => 0));
var matrix = List.generate(
m + 1,
(i) => List.generate(
n + 1,
(j) => 0,
growable: false,
),
growable: false);

// Initialize first row and column
// Initialize first row and column
for (int i = 1; i <= m; i++) {
matrix[i][0] = i;
matrix[i][0] = i;
}
for (int j = 1; j <= n; j++) {
matrix[0][j] = j;
matrix[0][j] = j;
}

// Compute Levenshtein distance
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
int cost = word1[i-1] == word2[j-1]? 0:1;
matrix[i][j] = min(
min(
matrix[i-1][j] + 1, // Deletion
matrix[i][j-1] + 1 // Insertion
),
matrix[i-1][j-1] + cost // Substitution
);
}
final a = matrix[i];
final b = matrix[i - 1];
final c = word1[i - 1];
for (int j = 1; j <= n; j++) {
int cost = c == word2[j - 1] ? 0 : 1;
a[j] = min(
min(
b[j] + 1, // Deletion
a[j - 1] + 1 // Insertion
),
b[j - 1] + cost // Substitution
);
}
}
return matrix[m][n];
}
Expand All @@ -40,20 +50,21 @@ void main(List<String> args) {
int times = 0;
// Compare each pair of arguments exactly once
for (int i = 0; i < args.length; i++) {
for (int j = i+1; j < args.length; j++) {
if (i != j) {
int distance = levenshteinDistance(args[i], args[j]);
if (minDistance == -1 || distance < minDistance ) {
minDistance = distance;
}
times++;
final a = args[i];
for (int j = i + 1; j < args.length; j++) {
if (i != j) {
int distance = levenshteinDistance(a, args[j]);
if (minDistance == -1 || distance < minDistance) {
minDistance = distance;
}
times++;
}
}
}

// The only output from the program should be the times (number of comparisons)
// and min distance calculated of all comparisons. Two total lines of output,
// formatted exactly like this.
print("times: " + times.toString());
print("min_distance: " + minDistance.toString());
}
}