From 83881031a0c341bbaf4e9a6a1652889a7a886c27 Mon Sep 17 00:00:00 2001 From: priyda <52833925+priyda@users.noreply.github.com> Date: Sat, 7 Jan 2023 09:02:48 +0530 Subject: [PATCH] LCS contraction addition in dymanic programming The contract has two functions: The lcs function takes two strings and the lengths of the strings as input and returns the length of the LCS of the strings. The view keyword specifies that this function does not modify the state of the contract, so it does not need to be executed on the blockchain. The max function is a helper function that takes two unsigned integers and returns the maximum of the two. The private keyword specifies that this function can only be called from within the contract. The lcs function first checks if the result for the input strings is already stored in the cache mapping. If it is, the function returns the cached result. If the result is not in the cache, the function calculates the result using the standard recursive definition of the LCS problem and stores the result in the cache before returning it. --- src/DynamicProgramming/LCS.sol | 43 ++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/DynamicProgramming/LCS.sol diff --git a/src/DynamicProgramming/LCS.sol b/src/DynamicProgramming/LCS.sol new file mode 100644 index 0000000..c3d10ca --- /dev/null +++ b/src/DynamicProgramming/LCS.sol @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: MIT + +pragma solidity ^0.8.0; + +/** + * @title longest common subsequence (LCS) problem + * @author [Priyda](https://github.com/priyda) + */ + +contract LCS { + // We use a mapping to store the results of each subproblem + mapping(uint => mapping(uint => uint)) public cache; + + function lcs(string memory a, string memory b, uint m, uint n) public view returns (uint) { + // Check if the result is already stored in the cache + if (cache[m][n] != 0) { + return cache[m][n]; + } + // If either string is empty, the LCS is 0 + if (m == 0 || n == 0) { + return 0; + } + // If the last characters of the strings match, add 1 to the LCS + // of the strings without the last character + if (a[m - 1] == b[n - 1]) { + uint result = 1 + lcs(a, b, m - 1, n - 1); + // Store the result in the cache + cache[m][n] = result; + return result; + } + // Otherwise, the LCS is the maximum of the LCS of the strings + // without the last character of each string + uint result = max(lcs(a, b, m, n - 1), lcs(a, b, m - 1, n)); + // Store the result in the cache + cache[m][n] = result; + return result; + } + + // Helper function to find the maximum of two unsigned integers + function max(uint a, uint b) private view returns (uint) { + return a > b ? a : b; + } +}