UNPKG

@technobuddha/library

Version:
58 lines (57 loc) 2.04 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.longestCommonSubsequence = void 0; var create2DArray_1 = __importDefault(require("../create2DArray")); /** * Implementation of Longest Common Subsequence problem. * http://en.wikipedia.org/wiki/Longest_common_subsequence * * Returns the longest possible array that is subarray of both of given arrays. * * @param array1 First array of objects. * @param array2 Second array of objects. * @param __namedParameters see {@link Options} * @default compare equality comparison * @default collect basic collector * @returns A list of objects that are common to both arrays * such that there is no common subsequence with size greater than the * length of the list. */ function longestCommonSubsequence(array1, array2, _a) { var _b = _a === void 0 ? {} : _a, _c = _b.compare, compare = _c === void 0 ? function (a, b) { return a === b; } : _c, _d = _b.collect, collect = _d === void 0 ? function (i1, _i2) { return array1[i1]; } : _d; var l1 = array1.length; var l2 = array2.length; var c = create2DArray_1.default(l1 + 1, l2 + 1, 0); var i; var j; for (i = 1; i <= l1; i++) { for (j = 1; j <= l2; j++) { if (compare(array1[i - 1], array2[j - 1])) c[i][j] = c[i - 1][j - 1] + 1; else c[i][j] = Math.max(c[i - 1][j], c[i][j - 1]); } } var result = []; i = l1; j = l2; while (i > 0 && j > 0) { if (compare(array1[i - 1], array2[j - 1])) { result.unshift(collect(i - 1, j - 1)); i--; j--; } else if (c[i - 1][j] > c[i][j - 1]) { i--; } else { j--; } } return result; } exports.longestCommonSubsequence = longestCommonSubsequence; exports.default = longestCommonSubsequence;