Untitled

 avatar
user_5999248
javascript
a month ago
2.6 kB
2
Indexable
Never
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 = [
    "correct answer 1",
    "correct answer 2",
    "correct answer 3",
    "correct answer 4",
    "correct answer 5",
    "correct answer 6",
    "correct answer 7"
];

var testAnswers = [
    "one",
    "two",
]

function retrieveAnswers(QIDs) {
    let userAnswers = []

    for (let i = 0; i < relevantQuestionIds.length; i++) {
        let questionId = relevantQuestionIds[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
        if (typeof answer == "string" && answer.length > 0) {
            userAnswers.push(answer)
        }
    };
    return userAnswers
}

// everything above goes to first page of task block
// everything below goes to page after last snippet

var userAnswers = retrieveAnswers(relevantQuestionIds)

correctAnswers.length = userAnswers.length;
console.log(correctAnswers)
var userAnswersLong = userAnswers.join(" ");
var correctAnswersLong = correctAnswers.join(" ");

var distance = levenshteinDistance(userAnswersLong, correctAnswersLong);
var similarity = 1 - distance / Math.max(userAnswersLong.length, correctAnswersLong.length);
var similarityPercent = similarity.toFixed(4) * 100;

// 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);
Leave a Comment