Question: I NEED HELP I've been on this problem for ages and I keep getting answers to questions I never asked! I'm trying to write a
I NEED HELP
I've been on this problem for ages and I keep getting answers to questions I never asked!
I'm trying to write a java code on dynamic programming algorithm. Where the user enters numbers and the compiler will find the longest consecutive subsequence.
For example:
The user should enter numbers in array X and Y of the same size. (The choice of numbers depend on the user.)
X={2, 4, 6, 8, 10, 12, 14, 16, 18, 20}
Y={13, 15, 18, 1, 3, 5, 8, 10, 12, 20}
The output should look like this: (These numbers differ depending on what the user chooses as numbers.)
Longest common subsequence is S={8, 10, 12} with length 3. n = 3 i = 4 j = 7
This is the code I wrote:
(I just need my code to be edited to the correct answer please, I don't want a code that's completely different.)
import java.util.*; import java.io.*; import java.util.Scanner; // create LCSExample1 class to find the Longest Common Subsequence class Seq { // create findLengthOfLCS() method that returns the longest common sequences public static String findLengthOfLCS(String str1, String str2, int[] X, int[] Y) { int m = X.length; int n = Y.length; int[][] dp = new int[m + 1][n + 1]; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (X[i - 1] == Y[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } // return dp[m][n]; }
int index = dp[m][n]; int temp = index; char[] longestCommonSubsequence = new char[index + 1]; longestCommonSubsequence[index] = '\0'; for (int k = 0; k <= temp; k++) lcs = lcs + longestCommonSubsequence[k]; return lcs; } public static void main(String[] args) { String str1, str2, LCS; Scanner sc= new Scanner(System.in); //System.in is a standard input stream. System.out.print("Enter first sequence: "); str1 = sc.nextLine(); //reads string. System.out.print("Enter second sequence: "); str2 = sc.nextLine(); //reads string. int m = str1.length(); int n = str2.length(); LCS = findLengthOfLCS(str1, str2, m, n); System.out.print("Sequence1: " + str1 + " Sequence2: " + str2); System.out.println(" LCS: "+LCS); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
