Levenshtein 16 aug
user_5999248
javascript
a year ago
2.9 kB
7
Indexable
function levenshteinDistance(s1, s2) {
const len1 = s1.length;
const len2 = s2.length;
// Create a 2D array to store the distances
const dp = Array.from({
length: len1 + 1
}, () => Array(len2 + 1).fill(0));
// Initialize the first row and column
for (let i = 0; i <= len1; i++) {
dp[i][0] = i;
}
for (let j = 0; j <= len2; j++) {
dp[0][j] = j;
}
// Compute the distances
for (let i = 1; i <= len1; i++) {
for (let j = 1; j <= len2; j++) {
const cost = s1[i - 1] === s2[j - 1] ? 0 : 1;
dp[i][j] = Math.min(
dp[i - 1][j] + 1, // Deletion
dp[i][j - 1] + 1, // Insertion
dp[i - 1][j - 1] + cost // Substitution
);
}
}
// The distance is the value in the bottom-right corner of the matrix
return dp[len1][len2];
}
var relevantQuestionIds = ["QID65", "QID84", "QID87", "QID88", "QID89", "QID90", "QID155"];
//TODO: Replace correct answers
var correctAnswers = [
"first correct",
"second correct",
"third correct",
"fourth correct",
"fifth correct",
"sixth correct"
];
var testAnswers = [
"this ös ö töxt",
"two",
NaN,
22,
"test"
];
function retrieveUserAnswers(QIDs) {
let userAnswers = []
for (let i = 0; i < QIDs.length; i++) {
let questionId = QIDs[i];
let retrievalId = "{{" + questionId + "}}"; //TODO: Replace with the correct syntax ($-sign)
let answer = Qualtrics.SurveyEngine.getEmbeddedData(retrievalId);
// let answer = testAnswers[i] // this is for testing
userAnswers.push(answer);
};
return userAnswers;
}
function getStringIndices(arr) {
let stringIndices = [];
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === 'string' && arr[i].length > 0) {
stringIndices.push(i);
}
}
return stringIndices;
}
function filterArrayByIndices(arr, indices) {
return indices.map(index => arr[index]);
}
// everything above goes to first page of task block
// everything below goes to page after last snippet
userAnswers = retrieveUserAnswers(relevantQuestionIds);
indices = getStringIndices(userAnswers);
var correctAnswersLong = filterArrayByIndices(correctAnswers, indices).join(" ");
var userAnswersLong = filterArrayByIndices(userAnswers, indices).join(" ");
var distance = levenshteinDistance(userAnswersLong, correctAnswersLong);
var similarity = 1 - distance / Math.max(userAnswersLong.length, correctAnswersLong.length);
var similarityPercent = (similarity * 100).toFixed(2);
// TODO: Might have to set these as empty strings in the survey flow first. In that case, check variable names.
Qualtrics.SurveyEngine.setEmbeddedData("distance", distance);
Qualtrics.SurveyEngine.setEmbeddedData("similarity", similarityPercent);Editor is loading...
Leave a Comment