longest common subsequence function does not work for all examples - java

EDIT: UP
The code does not work properly with the strings below.
"1 11 23 1 18 9 15 23 5"
"11 1 18 1 20 5 11 1"
EDIT: I noticed, that if I change 20 to 40 in second string, the function works properly...
For strings:
"12 4 55 11 8 43 22 90 5 88 15"
"15 66 4 36 43 22 78 88 32"
it works properly. Where is the problem?
Here is my code:
int[][] tabelka = new int[linia1.length()+1][linia2.length()+1];
for (int i = 0; i<linia1.length(); i++) {
for (j = 0; j<linia2.length(); j++) {
if ( linia1.charAt(i) == linia2.charAt(j) ) {
tabelka[i+1][j+1] = tabelka[i][j] + 1;
}
else {
tabelka[i+1][j+1] = Math.max(tabelka[i+1][j], tabelka[i][j+1]);
}
}
}
for (int i = 0; i<linia1.length(); i++) {
for (j = 0; j<linia2.length(); j++) {
System.out.println(tabelka[i][j]);
}
}
StringBuffer podciag = new StringBuffer();
for(int x = linia1.length(), y = linia2.length(); x != 0 && y != 0; ) {
if( tabelka[x][y] == tabelka[x-1][y] ) {
licznik++;
x--;
}
else if( tabelka[x][y] == tabelka[x][y-1] ) {
licznik++;
y--;
}
else {
licznik++;
assert linia1.charAt(x-1) == linia2.charAt(y-1);
podciag.append(linia1.charAt(x-1));
x--;
y--;
}
}
String buff = podciag.reverse().toString();
The output of this code (for the first two strings) is:
11 1 18 1 2 5
However, the output should be:
11 1 18 5

For a full / better explanation, please refer to:
http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/
http://www.geeksforgeeks.org/printing-longest-common-subsequence/
I think that you are constructing the array correctly. However, I am not sure about the way the table is being read in order to construct the LCS.
The idea is to start at the end of the 2D array solution[str1.length()][str2.length()] and if:
The last characters of str1 and str2 are equal then the last character is part of the LCS and decrement both indexes
If they are not equal, compare solution[i-1][j] and solution[i][j-1] and go in direction of greater value.
Repeat until either of the indexes are 0.

Related

How can I print out 1-50 even numbers only, but the it start a new line every multiples of 10. (JAVA)

I'm a newbie, but I'm willing to learn how to code.
I tried using this code:
int n = 50;
int counter = 0;
System.out.print("Even Numbers from 1 to "+n+" are: ");
for (int i = 1; i <= n; i++) {
counter++;
if (counter == 2) {
System.out.println(i + " ");
counter = 0;
%10== 0
to find all even numbers between 1 to 50 and make a new line at multiples of 10 just follow these steps -
Make one loop which will go 1 to 50
Check if the number is even by checking the remainder after diving it with 2, if YES print that number.
Check if the number is a multiple of 10 by checking the remainder after dividing it by 10, if YES make a new line
The code will look something like this -
int i = 1;
while(i<=50){
if(i%2 == 0) System.out.print(i + " ");
if(i%10 == 0) System.out.println();
i++;
}
Output -
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
It's up to you which looping method you want to use for me While loop looks cleaner.
I hope this solves all your queries.
PFB Snippet:
public class Main
{
public static void main(String[] args) {
for(int i=1;i<=50;i++){
if (i%2 == 0) //Check whether number is even
{
System.out.print(i+" ");
if (i%10 == 0) // Check if it is multiple of 10
{
System.out.print("\n");
}
}
}
}
}
Output:
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
"\n" is a Escape Sequence which means new line

Printing a snake pattern using an array

I'm having trouble with an assignment where we are required to print out this array:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
My code is somewhat correct but it is not printing 10 and 19 where it should be.
My output:
Choose a number for the rows from 0 to 16.
5
Choose a number for the columns from 0 to 16
5
1 0 10 0 19
2 9 11 18 20
3 8 12 17 21
4 7 13 16 22
5 6 14 15 23
My code:
//snake move with the number
import java.util.Scanner;
public class SnakeMove {
public static void main(String[] args) {
//create Scanner object
Scanner inScan = new Scanner(System.in);
//prompt the user to choose number for the Row from 0 to 16
System.out.println("Choose a number for the rows from 0 to 16.");
//take the input from user with nextInt() method
//use the variable int row
int row = inScan.nextInt();
//prompt the user to choose number for the Col from 0 to 16
System.out.println("Choose a number for the columns from 0 to 16");
//take the input from user with nextInt()
//use the variable int col
int col = inScan.nextInt();
if (row != col) {
System.out.println("Run the program again and choose the same number for Row and Col");
System.exit(0);
}
int[][] arr = move(row, col);
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}//main method
static int[][] move(int row, int col) {
boolean flag = true;
int count = 1;
int[][] array = new int[row][col];
for (int j = 0; j < array[0].length; j++) {
if (flag) {
for (int i = 0; i < array.length; i++) {
//assign the increment value of count
// to specific array cells
array[i][j] = count;
count++;
}
flag = false;
} else {
//row decrement going up
for (int i = array.length - 1; i > 0; i--) {
//assign the increment value of count
// to specific array cells
array[i][j] = count;
count++;
}
flag = true;
}
}//column increment
return array;
}//move method
}//end SnakeMove class
Can anyone detect what is causing the error? Any help would be appreciated.
I believe this is a good alternative and easy to understand. Do comment if you have a simplified version of the same.
Code:
import java.util.Arrays;
import java.util.Scanner;
public class SnakePatternProblem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // *INPUT*
int row = scanner.nextInt();
int col = scanner.nextInt();
int[][] array = new int[row][col];
// Initializing first row of the array with a generalized expression
for (int i = 0; i < col; i++) {
if (i % 2 != 0) array[0][i] = col * (i+1);
else array[0][i] = (col * i) + 1;
}
array[0][0] = 1; // this element is not covered in the above loop.
// Nested loop for incrementing and decrementing as per the first row of elements.
for (int i= 1; i< row; i++){
for (int j=0; j< col; j++){
if(j%2==0) array[i][j] = array[i-1][j] + 1;
else array[i][j] = array[i-1][j] - 1;
}
}
System.out.println(Arrays.deepToString(array)); // *OUTPUT
}
}
Explanation:
Consider first row of 5 x 5 matrix named "arr" with snake pattern:
1 10 11 20 21
The element in the odd column is equivalent to ((currentColumn + 1) * Total_No_Of_columns);
Example: arr[0][1] = (1 + 1)* 5 = 10
The element in the even column is equivalent to (currentColumn * Total_No_Of_columns) + 1;
Example: arra[0][2] = (2 * 5) + 1 = 11;
Important Note: element at first row, first column is Zero
arr[0][0] = 1 -> must be declared
Now, the remaining matrix is incrementing or decrementing loop from the first element in that column.
Elements with even column number gets incremented by 1 in each row from the first element of that column.
1 -> First element of column-0
2 -> (1 + 1)
3 -> (2 + 1).... so on
4
5
Elements with odd column number gets decremented by 1 in each row from the first element of that column.
10 -> First element of column - 1
9 -> (10 - 1)
8 -> (9 - 1).... so on
7
6
This will generate the "snaking" pattern you described.
It could be simplified with ternary but this makes it more readable I think
It would be interesting to find a more clever way about it though, if anyone finds a better way pls comment
public static int[][] genArray(int length) {
int[][] arr = new int[length][length];
int counter = 0;
for (int col = 0; col < arr.length; col++) {
if (col % 2 == 0) {
for (int row = 0; row < arr.length; row++) {
arr[row][col] = counter++;
}
} else {
for (int row = arr.length - 1; row >= 0; row--) {
System.out.println("row: " + row + ", col: " + col);
arr[row][col] = counter++;
}
}
}
}
return arr;
}
You can create such an array as follows:
int m = 5;
int n = 4;
int[][] snakeArr = IntStream.range(0, n)
.mapToObj(i -> IntStream.range(0, m)
// even row - straight order,
// odd row - reverse order
.map(j -> (i % 2 == 0 ? j : m - j - 1) + i * m + 1)
.toArray())
.toArray(int[][]::new);
// output
Arrays.stream(snakeArr)
.map(row -> Arrays.stream(row)
.mapToObj(e -> String.format("%2d", e))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
Transposing snake array:
int[][] transposedSA = new int[m][n];
IntStream.range(0, m).forEach(i ->
IntStream.range(0, n).forEach(j ->
transposedSA[i][j] = snakeArr[j][i]));
// output
Arrays.stream(transposedSA)
.map(row -> Arrays.stream(row)
.mapToObj(e -> String.format("%2d", e))
.collect(Collectors.joining(" ")))
.forEach(System.out::println);
1 10 11 20
2 9 12 19
3 8 13 18
4 7 14 17
5 6 15 16
An easy way to do it is to create a 2-D array as shown below and then print its transpose.
1 2 3 4 5
10 9 8 7 6
11 12 13 14 15
20 19 18 17 16
21 22 23 24 25
It is a 2-D array of the dimension, LEN x LEN, where LEN = 5.
The above pattern goes like this:
The pattern starts with a start value of 1.
When the main loop counter is an even number, the counter, which assigns a value to the array, starts with start value and increases by one, LEN times. Finally, it sets start for the next row to start with final_value_of_the_array_value_assignment_counter - 1 + LEN.
When the main loop counter is an odd number, the counter, which assigns a value to the array, starts with start value and decreases by one LEN times. Finally, it sets start for the next row to start with start + 1.
The transpose of the above matrix will look like:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
In terms of code, we can write it as:
public class Main {
public static void main(String[] args) {
final int LEN = 5;
int[][] arr = new int[LEN][LEN];
int start = 1, j, k, col;
for (int i = 0; i < LEN; i++) {
if (i % 2 == 0) {
k = 1;
for (j = start, col = 0; k <= LEN; j++, k++, col++) {
arr[i][col] = j;
}
start = j - 1 + LEN;
} else {
k = 1;
for (j = start, col = 0; k <= LEN; j--, k++, col++) {
arr[i][col] = j;
}
start++;
}
}
// Print the transpose of the matrix
for (int r = 0; r < LEN; r++) {
for (int c = 0; c < LEN; c++) {
System.out.print(arr[c][r] + "\t");
}
System.out.println();
}
}
}
Output:
1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25
Change the value of LEN to 10 and you will get the following pattern:
1 20 21 40 41 60 61 80 81 100
2 19 22 39 42 59 62 79 82 99
3 18 23 38 43 58 63 78 83 98
4 17 24 37 44 57 64 77 84 97
5 16 25 36 45 56 65 76 85 96
6 15 26 35 46 55 66 75 86 95
7 14 27 34 47 54 67 74 87 94
8 13 28 33 48 53 68 73 88 93
9 12 29 32 49 52 69 72 89 92
10 11 30 31 50 51 70 71 90 91

BlueJ - BlueJ freezes when reading in from a text file

So for my computer science class we had to create a program that will read in from a text file named "compact.txt" and have the integers inside stored into an int[]. After that we have to print the numbers to the terminal with the 0s contained in the text file and then without the 0s contained in the text file. The code compiles and runs, but when it runs it does not print anything to the terminal and it completely freezes all of BlueJ. After the freeze I can't even copy the code from inside the main and have to force close it from task manager. FileInput is what my class uses to read in files. Here is my code:
import chn.util.*;
public class compact
{
public static void main(String [] args)
{
FileInput fI = new FileInput("compact.txt");
int[] ar = new int[100];
String line = fI.readLine();
fI.close();
System.out.println(line);
int count = 0;
int x = 0;
while(x < line.length())
{
if(!line.substring(x, x+1).equals(" "))
{
if(!line.substring(x + 1, x + 2).equals(" ") && !
(line.length() - 1 == x))
{
ar[count] = Integer.parseInt(line.substring(x + 1, x+2));
}
else
{
ar[count] = Integer.parseInt(line.substring(x, x+1));
}
count++;
}
x++;
}
System.out.print("Before: " + ar[0]);
for(int i = 1; i < count; i++)
{
System.out.print(", " + ar[i]);
}
System.out.print("\n");
System.out.println("After: ");
for(int i = 0; i < count; i++)
{
if(ar[i] == 0)
{
System.out.print("");
}
else
{
if(i == count - 1)
{
System.out.print(ar[i]);
}
System.out.print(ar[i] + ", ");
}
}
}
}
And this is what is contained inside of the "compact.txt" file:
0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0
So, I get a StringIndexOutOfBoundsException because when x is equal to line.length() - 1, x + 1 or x + 2 exceeds the length of the String.
This generally means your logic is broken. While you could go back with pen a paper and nut it out, a better approach might be to use:
java.util.Scanner...
String line = "0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0";
Scanner scan = new Scanner(line);
while (scan.hasNextInt()) {
System.out.println(scan.nextInt());
}
This will allow you to get each individual int element from the original String
Or String#split...
String line = "0 6 13 0 0 75 33 0 0 0 4 29 21 0 86 0 32 66 0 0";
String[] parts = line.split(" ");
which will give you an array of Strings split by the space.
From there you can decide how best to approach separating the 0s (or, simply filter the output using a if statement)

Outputting values 1 to A, with B values per row (Java)

public static void applicationB(int A, int B) {
int number = 1;
for (int row = 0; row < A; row++) {
for (int col = 0; col < B; col++) {
int output = number + row++;
System.out.printf("% 4d", output);
}
// does it skip because of this?
System.out.println("");
}
}
It outputs with A = 20, B = 5
1 2 3 4 5
7 8 9 10 11
13 14 15 16 17
19 20 21 22 23
The correct output should be
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
I cannot figure out how to get it to stop skipping 6, 12, and 18.
Am I just doing this a horrible way? or am I on the right track?
You are incrementing row in two places. Also, it would be easier to just have one loop, and output a line break every B elements (you can use i % B to test for this).
I would suggest the following approach. Iterate over the values you want to print out, from 1 to the maximum value (A). Then, print a newline whenever the remainder of value divided by the number of columns (B) is zero.
for (int value = 1; value <= A; value++) {
System.out.printf("% 4d", value);
if (value % B == 0) {
System.out.println("");
}
}

Array Printf issue

I'm working on simple program that is supposed to list the numeric values in an array; a certain way. This is how I would like to have the output look like:
Printing Array:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22
It has to be lined as seen above and line must only contain 10 numbers.
I seem to have everything formatted correctly but my output doesn't look like that.
Here is what I am getting:
Printing Array:
1
2 3 4 5 6 7 8 9 10 11
12 13 14 15 16 17 18 19 20 21
22
I'm not sure exactly what I'm doing wrong but here's my code:
//disregard the name 'Juice', I like to give my programs weird names
public class Juice
{
public static void main(String[] args)
{
//sets up the array
int[] numbers = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22};
//title
System.out.println("Printing Array: ");
//counting the elements
for (int i = 0; i < numbers.length; i++)
{
//prints each element value with 4 spaces in between
System.out.printf("%4d", numbers[i]);
//once line reaches ten values; print new line
if (i % 10 == 0)
{
System.out.printf("\n");
}
}
}
}
if ((i+1) % 10 == 0)
{
System.out.printf("\n");
}
Your code does what you asked it to.
On first loop, i=0, but i % 10 == 0 is also true, so it prints new line.
You can use many different approaches to fix this, but probably easiest one will be to replace this condition to (i+1) % 10 == 0 or to i % 10 == 9.
you almost did it
public class Juice
{
public static void main(String[] args)
{
//sets up the array
int[] numbers = {1,2,3,4,5,6,7,8,9,10,12,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32};
//title
System.out.println("Printing Array: ");
//counting the elements
for (int i = 0; i < numbers.length; i++)
{
//prints each element value with 4 spaces in between
System.out.printf("%4d", numbers[i]);
//once line reaches ten values; print new line
if (i % 10 == 9)
{
System.out.printf("\n");
}
}
}
}
i've modified a conditions to if (i % 10 == 9)
OUTPUT
Printing Array:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32
Alternatively to avoid the confusion between the index to the array element and the element count switch to using a foreach loop.
//counting the elements
int i = 1;
for (int number : numbers) {
//prints each element value with 4 spaces in between
System.out.printf("%4d", number);
//once line reaches ten values; print new line
if (i % 10 == 0) {
System.out.println();
}
i++;
}

Categories