samples/2022/03/algorithms/distance.js

99 lines
1.8 KiB
JavaScript
Raw Normal View History

'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', function(inputStdin) {
inputString += inputStdin;
});
process.stdin.on('end', function() {
inputString = inputString.split('\n');
main();
});
process.on('SIGINT', function() {
inputString = inputString.split('\n');
main();
process.exit(0);
});
function readLine() {
return inputString[currentLine++];
}
/*
* Complete the 'appendAndDelete' function below.
*
* The function is expected to return a STRING.
* The function accepts following parameters:
* 1. STRING s
* 2. STRING t
* 3. INTEGER k
*/
function appendAndDelete(s, t, k) {
s = s.trim();
t = t.trim();
let n = s.length;
let m = t.length;
// console.log(`n: ${n}, m: ${m}`);
let a = new Array(n+1);
for (let i = 0; i <= n; i++) {
a[i] = new Array(m+1);
}
for (let i = 0; i <= m; i++) {
a[0][i] = i;
}
for (let i = 0; i <= n; i++) {
a[i][0] = i;
}
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
// console.log(`I: ${i}, J: ${j}, Sc: ${s[i-1]}, Tc: ${t[j-1]}`);
if (s[i-1] === t[j-1]) {
a[i][j] = a[i-1][j-1];
} else {
a[i][j] = Math.min(a[i-1][j]+1, a[i][j-1]+1);
}
}
}
// console.log('Array', a);
console.log(`Min operations: ${a[n][m]}`);
let res = a[n][m] <= k ? 'Yes': 'No';
// console.log(`Res: ${res}`);
return res;
}
function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);
const s = readLine();
const t = readLine();
const k = parseInt(readLine().trim(), 10);
const result = appendAndDelete(s, t, k);
ws.write(result + '\n');
ws.end();
}