Greedy LCS Java Code Implementation - java

I'm trying to make java code from this journal:
Journal Greedy LCS
This code is about a greedy approach for computing longest common subsequences by afroza begum.
And here is my [EDITED] code:
public class LCS_Greedy {
public static void main(String[] args) {
// String X_awal = "ABCBDABE";
// String Y = "BDCABA";
// String X_awal = "XMJYAUZ";
// String Y = "MZJAWXU";
// String X_awal ="AGGTAB";
// String Y="GXTXAYB";
// String X_awal = "ABCDGH";
// String Y = "AEDFHR";
// String X_awal = "AHBCDG";
// String Y = "AEDFHR";
//greedy not always optimum
String X_awal = "bcaaaade";
String Y = "deaaaabc";
String X = match(X_awal, Y);
int[] Penanda_Y = new int[Y.length()];
int y_length = Y.length();
for (int k = 0; k < y_length; k++) {
Penanda_Y[k] = 0;
}
int m = X.length();
int n = Y.length();
String L = "";
String LSym = "";
int R = 0;
int i = 1;
int[] P = new int[100];
P[i] = posisi(X, Y, i, Penanda_Y, R);
i = 1;
while (i <= m) {
if (i != m) {
P[i + 1] = posisi(X, Y, (i + 1), Penanda_Y, R);
}
if (P[i + 1] == 0) {
if (P[i] > R) {
L = L + " " + Integer.toString(P[i]);
LSym = LSym + " " + X.charAt(i - 1);
}
break;
}
if (P[i + 1] < R || P[i] < R) {
R = 0;
}
if (P[i] > P[i + 1]) {
if (R == 0 && i > 1) {
L = L + " " + Integer.toString(P[i]);
LSym = LSym + " " + X.charAt(i - 1);
Penanda_Y[P[i] - 1] = 1;
R = P[i];
i = i + 1;
if (R == Y.length() || i > X.length()) {
break;
}
P[i] = posisi(X, Y, i, Penanda_Y, R);
} else {
L = L + " " + Integer.toString(P[i + 1]);
LSym = LSym + " " + X.charAt(i + 1 - 1);
Penanda_Y[P[i + 1] - 1] = 1;
R = P[i + 1];
i = (i + 1) + 1;
if (R == Y.length() || i > X.length()) {
break;
}
P[i] = posisi(X, Y, i, Penanda_Y, R);
}
} else {
if (R == 0 && i > 1) {
L = L + " " + Integer.toString(P[i + 1]);
LSym = LSym + " " + X.charAt(i + 1 - 1);
Penanda_Y[P[i + 1] - 1] = 1;
R = P[i + 1];
i = (i + 1) + 1;
if (R == Y.length() || i > X.length()) {
break;
}
P[i] = posisi(X, Y, i, Penanda_Y, R);
} else {
L = L + " " + Integer.toString(P[i]);
LSym = LSym + " " + X.charAt(i - 1);
Penanda_Y[P[i] - 1] = 1;
R = P[i];
i = i + 1;
if (R == Y.length() || i > X.length()) {
break;
}
P[i] = posisi(X, Y, i, Penanda_Y, R);
}
}
}
System.out.println("X = " + X_awal);
System.out.println("X = " + Y);
System.out.println("L = " + L);
System.out.println("LSym = " + LSym);
System.out.println("Length = " + LSym.length() / 2);
}
public static String match(String X, String Y) {
String hasil = "";
for (int i = 0; i < X.length(); i++) {
for (int j = 0; j < Y.length(); j++) {
if (X.charAt(i) == Y.charAt(j)) {
hasil = hasil + X.charAt(i);
break;
}
}
}
return hasil;
}
public static int posisi(String X, String Y, int i, int[] Penanda_Y, int R) {
int n = Y.length();
int k;
int kr = 0;
i = i - 1;
for (k = 0; k < n; k++) {
if ((X.charAt(i) == Y.charAt(k)) && Penanda_Y[k] == 0) {
kr = k + 1;
break;
}
}
for (k = R; k < n; k++) {
if ((X.charAt(i) == Y.charAt(k)) && Penanda_Y[k] == 0) {
kr = k + 1;
break;
}
}
return kr;
}
}
But when I run that program, in some case it has true output, but in another case it false. What is wrong with that code? Can anybody explain to me? Thanks
Edit:
My code now can run perfectly, but it seem far away from pseudo code in that journal. Can anybody explain this? Why I cannot make code exactly from the journal? It always error when I make from pseudo code given in that journal. Thanks.

The algorithm will not lead to LCS. The greedy guess was wrong. It assumes the early match will guaranty to form LCS. Even though, the pseudocode takes the earlier matching of first two in X, which may skip a lot of common substring at the beginning of Y. The other simple test is change last 'E' to 'A' in X, the algorithm won't be able to find last matching 'A' for sure. The truth is an early match may lock down the position to forbidden longer match. In other word, we may need to skip some early match, so that we can found a longer match. Dynamic programming way is proved to be true mathematically, however, this algorithm didn't.

Related

Get sum of integers with old numbers 1 + (1 + 2) + (1 + 2 + 3) + ... + (1 + 2 + 3 + ... + n)

I'm trying to reach this :
1 + (1 + 2) + (1 + 2 + 3) + ... + (1 + 2 + 3 + ... + n)
I'm already getting this result:-
(1 + 2) + (2 + 3)
with this code :
int n = 8;
for (int i = 1; i < n; i++){
int j = i + 1;
System.out.print("(" + i + " + " + j + ")");
}
How can I achieve the top result ?
You need two loops like this :
int n = 8;
String del;
String del2 = "";
for (int i = 1; i <= n; i++) {
System.out.print(del2 + "(");
del = "";
for (int j = 1; j <= i; j++) {
System.out.print(del + j);
del = " + ";
}
System.out.print(")");
del2 = " + ";
}
code demo
Move the declaration of j before the loop and initialize it with 0, then just add the current i to j.
That would solve what? – AKSW
This would calculate the sum of the equation.
To print the equation you also need one loop only:
int n = 8;
StringBuilder equation = new StringBuilder("1");
StringBuilder equationGroup = new StringBuilder("1");
for (int i = 2; i < n; i++) {
equationGroup.append(" + ");
equationGroup.append(i);
equation.append(" + (");
equation.append(equationGroup.toString());
equation.append(")");
}
System.out.println(equation.toString());
Well, thanks #YCF_L for your answer it's the correct one, but this complete one after edit, i posted it in case some one need the complete solution:
int n = 8;
String del;
String delPlus = "";
String rightPract = "", leftPract = "";
for (int i = 2; i < n; i++) {
System.out.print(delPlus + rightPract);
del = "";
for (int j = 1; j < i; j++) {
System.out.print(del + j);
del = " + ";
}
System.out.print(leftPract);
delPlus = " + ";
rightPract = "(";
leftPract = ")";
}
Now the result is :-
1 + (1 + 2) + (1 + 2 + 3) + (1 + 2 + 3 + 4) + (1 + 2 + 3 + 4 + 5) + (1 + 2 + 3 + 4 + 5 + 6)
If you take the recursion approach you have to think of it as a recursion inside another recursion. add(i,n) generates 1 and (1+2) and (1+2+3) up to (1+2+3...n). then the sum(i,n) recursively sum them together
public static int add(int i, int n){
if(i == n){
return n;
}
return i + add(i+1,n);
}
public static int sum(int i, int n){
if(i == n){
return add(0,n);
}
return add(0, i) + sum(i+1,n);
}
public static void main(String[] args){
int n = 8;
System.out.print(sum(0, n));
}

Crossword algorithm for Android using Java [duplicate]

This question already has answers here:
Algorithm to generate a crossword [closed]
(13 answers)
Closed 6 years ago.
I am working on cross word algorithm to develop a word app. After doing a lot of googling or search on StackOverflow, I was able to reach this point. But yet I am not able to understand the right implementation for algorithm in Java. Below is the class I used.
public class Crosswords {
char[][] cross;
int rows;
int cols;
char[][] numberGrid;
boolean startword;
final char DEFAULT = ' ';
public Crosswords() {
rows = 50;
cols = 50;
cross = new char[rows][cols];
numberGrid = new char [rows][cols];
for (int i = 0; i < cross.length;i++){
for (int j = 0; j < cross[i].length;j++){
cross[i][j] = DEFAULT;
}
}
}
public Crosswords(int ros, int colls) {
rows = ros;
cols = colls;
cross = new char[rows][cols];
numberGrid = new char [rows][cols];
for (int i = 0;i < cross.length; i++){
for (int j = 0; j < cross[i].length; j++){
cross[i][j] = DEFAULT;
}
}
}
public String toString() {
String s = new String();
//String d = new String();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++){
s = s + cross[i][j] + " ";
}
s = s + "\n";
}
return s;
}
public void addWordh(String s, int r, int c) {
int i = 0;
int j = 0;
boolean b = true;
boolean intersectsWord = true;
if (s.length() > cols) {
System.out.println(s + " is longer than the grid. Please try another word.");
return;
}
if (c + s.length() > cols) {
System.out.println(s + " is too long. Please try another word.");
return;
}
if ((r - 2) >= 0) {
if ((cross[r - 1][c - 1 + s.length()] == DEFAULT) || (cross[r - 1][c - 1 + s.length()] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the beginning of another word!");
return;
}
}
for (i = 0; i < s.length(); i++) {
if ((cross[r - 1][c - 1 + i] == DEFAULT) || (cross[r - 1][c - 1 + i] == s.charAt(i))) {
b = true;
}
else {
b = false;
System.out.println("Unable to add " + s + ". Please try another word.");
return;}
}
if (b == true) {
if ((s.length() <= cols) && (c + s.length() <= cols) &&
(cross[r - 1][c - 1] == s.charAt(0)) || (cross[r - 1][c - 1] == DEFAULT)) {
while (j < s.length()) {
cross[r - 1][c - 1 + j] = s.charAt(j);
if (j==0){
startword = true;
}
cross[rows - 1 - (r - 1)][cols - 1 - (c - 1 + j)] = '*';
j++;
}
}
}
}
public void addWordv(String s, int r, int c) {
int i = 0;
int j = 0;
boolean b = true;
boolean intersectsWord = true;
if (s.length() > rows) {
System.out.println(s + " is longer than the grid. Please try another word.");
}
if (r + s.length() > rows) {
System.out.println(s + " is too long. Please try another word.");
}
else {
if ((r - 2) >= 0) {
if ((cross[r - 2][c - 1] == DEFAULT) || (cross[r - 2][c - 1] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the end of another word!");
return;
}
}
if ((cross[r - 1 + s.length()][c - 1] == DEFAULT) || (cross[r - 1 + s.length()][c - 1] == '*')) {
intersectsWord = false;
}
else { intersectsWord = true;}
if (intersectsWord == true) {
System.out.println("The word " + s + " intersects the end of another word!");
return;
}
for (i = 0; i < s.length(); i++) {
if ((cross[r - 1 + i][c - 1] == DEFAULT) || (cross[r - 1 + i][c - 1] == s.charAt(i))) {
b = true;
}
else {
b = false;
System.out.println("Unable to add " + s + ". Please try another word.");
return;}
}
if (b == true) {
if ((s.length() <= rows) && (r + s.length() <= cols) &&
(cross[r - 1][c - 1] == s.charAt(0)) || (cross[r - 1][c - 1] == DEFAULT)) {
while (j < s.length()) {
cross[r - 1 + j][c - 1] = s.charAt(j);
if (j==0){
startword = true;
}
cross[rows - 1 - (r - 1 + j)][cols - 1 - (c - 1)] = '*';
j++;
}
}
}
}
}
public void setNumberGrid(){
numberGrid = new char [rows][cols];
for (int i = 0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (cross[i][j] == DEFAULT){
numberGrid[i][j] = (char) 0;
}
else if (startword == true){
numberGrid[i][j] = (char) -2;
}
else {
numberGrid[i][j] = (char) -1;
}
}
int count = 1;
for (i=0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (numberGrid[i][j] == -2){
numberGrid[i][j] = (char)count;
count++;
}
}
}
}
}
public String printNumberGrid() {
for (int i=0; i < cross.length; i++){
for (int j=0; j < cross[rows].length; j++){
if (numberGrid[i][j] == (char)-1){
numberGrid[i][j] = ' ';
}
else if (numberGrid[i][j] == (char)0){
numberGrid[i][j] = '#';
}
}
}
String d = new String();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++){
d = d + numberGrid[i][j] + " ";
}
d = d + "\n";
}
return d;
}
public static void main(String[] args) {
Crosswords g = new Crosswords();
g.addWordv("rawr", 4, 5);
g.addWordh("bot", 5, 4);
g.addWordv("raw", 7, 5);
g.addWordh("cat", 4, 5);
g.addWordh("bass", 6, 10);
System.out.println(g);
Crosswords c = new Crosswords(20, 20);
c.addWordh("HELLO", 1, 1);
c.addWordv("HAPLOID", 1, 1);
c.addWordh("COMPUTER", 3, 12);
c.addWordv("CAT", 2, 11);
c.addWordv("WOAH", 2, 20);
c.addWordh("PARKING", 20, 5);
c.addWordv("ARK", 17, 6);
c.addWordh("AHOY", 6, 18);
c.addWordv("AHOY", 18, 10);
c.addWordv("ADVANTAGE", 2, 12);
c.addWordv("INTERNAL", 2, 18);
c.addWordh("BANTER", 7, 11);
c.addWordv("BEAGLE", 5, 12);
c.addWordh("BASE", 8, 3);
c.addWordv("BALL", 8, 3);
c.addWordh("LEFT", 10, 3);
c.addWordv("SAFE", 8, 5);
System.out.print(c);
}
}
As you can see in Main method that i am adding the words but also giving the row and column number to place the words like c.addWordv("Safe",8,5); where 8 and 5 is column number.
Now Question is how can i implement cross word algorithm which just take words and place them on board randomly without taking the row and column numbers.
Thanks in advance
EDIT:
I want to modify this class algo the way that i dont have to give away the rows and columns number..
//Pseudo Code
If the crossword size is maxSize and any word's length is stored in wordLength ,then you can use random method as below
int maxSize=20;
int wordLength=4;
Random random =new Random();
int r,c;
//for horizontal
r=random.nextInt(maxSize-wordLength);
c=random.nextInt(maxSize);
//for vertical
r=random.nextInt(maxSize);
c=random.nextInt(maxSize-wordLength);
You can store the row and column and generate the new one if its already present.

string multiplication using a big integer class

I'm trying to write a code that multiplies two strings of integers. I'm not too sure where it's going wrong... It works for some numbers, but is horribly wrong for others. I'm not asking for a full solution, but just a hint (I seriously appreciate any help possible) as to where I'm making the obviously silly mistake. Thanks in advance.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Please enter a big integer. ");
String t = scan.nextLine();
System.out.print("And another. ");
String s = scan.nextLine();
BigInt a = new BigInt(t);
BigInt b = new BigInt(s);
System.out.println(a + " + " + b + " = " + a.add(b));
System.out.println(a + " - " + b + " = " + a.sub(b));
System.out.println(a + " * " + b + " = " + a.mul(b));
System.out.println(a + " / " + b + " = " + a.div(b));
}
}
class BigInt {
public BigInt() {
n = new int[1];
}
public BigInt(String s) {
n = new int[s.length()];
for (int i = 0; i < n.length; ++i) {
n[n.length - i - 1] = s.charAt(i) - '0' ;
}
}
private BigInt(int[] n) {
this.n = new int[n.length];
for (int i = 0; i < n.length; ++i) {
this.n[i] = n[i];
}
}
public String toString() {
String s = "";
for (int i : n) {
s = i + s;
}
return s;
}
public BigInt mul(BigInt o) {
int carry = 0;
int s = 0;
int digit;
int subtotal = 0;
int total = 0;
int max = n.length > o.n.length ? n.length : o.n.length;
int[] result = new int[n.length + o.n.length];
for (int i = 0; i < o.n.length; ++i) {
int bottom = i <= o.n.length ? o.n[i] : 0;
for (s = 0; s <= n.length; ++s){
int top = s < n.length ? n[s] : 0;
int prod = (top * bottom + carry);
if (s == (max-1)) {
total = Integer.valueOf((String.valueOf(prod) + String.valueOf(subtotal)));
carry = 0;
digit = 0;
subtotal = 0;
break;
}
if (prod < 10) {
digit = prod;
subtotal += digit;
carry = 0;
}
if (prod >= 10); {
digit = prod % 10;
carry = prod / 10;
subtotal += digit;
}
}
result[i] = total;
}
return new BigInt(trim(result));
}
private int[] trim(int[] nums) {
int size = nums.length;
for (int i = nums.length - 1; i > 0; --i) {
if (nums[i] != 0) {
break;
}
--size;
}
int[] res = new int[size];
for (int i = 0; i < size; ++i) {
res[i] = nums[i];
}
return res;
}
private int[] n;
}
A quick test using:
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
System.out.println(x + " * " + y + " = " + new BigInt(Integer.toString(x)).mul(new BigInt(Integer.toString(y))));
}
}
demonstrates that somehow your multiply of x * y is actually multiplying by 10x * y. That should give you a clear hint to the problem.

Generating Pythagorean Triples using Fibonacci Sequence

I'm using the Fibonacci sequence to generate some pythagorean triples (3, 4, 5, etc) based off this page: http://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples starting at "Generalized Fibonacci Sequence".
public static int fib(int n) {
if(n == 0) return 0;
if(n <= 2) return 1;
int i = 1;
int temp = 0;
while(n != 1) {
i += temp;
temp = i - temp;
n--;
}
return i;
}
public static void main(String[] args) {
int a = 4; //a(3)
int b = 3; //b(3)
int c = 5; //c(3)
for(int n = 4; n < 10; n++) {
System.out.println(a + "^2 + " + b + "^2 = " + c + "^2");
a = a + b + c;
b = fib((2 * n) - 1) - b;
c = fib(2 * n);
}
}
However, the output my program is giving me is not accurate:
4^2 + 3^2 = 5^2
12^2 + 10^2 = 21^2
43^2 + 24^2 = 55^2
122^2 + 65^2 = 144^2
331^2 + 168^2 = 377^2
876^2 + 442^2 = 987^2
What could be causing this problem? Have I been duped by Wikipedia?
#MarkDickinson pointed out that the formula required F(1) = 0 and F(2) = 1, which is different from what is widely used, where F(1) = 1 and F(2) = 1. That fixed my problem!

How put values from cycle to multi array

I have such a cycle (it is piece of my other code):
for (int i = 2; i < 257; i = i * 2) {
V -= i + 0;
System.out.println("Suma: " +V+ " atemus: "+i);
///////////////////
int X [][] = new int [8][16]; //multi array where i need to put "i" values
}
and how you see in code have i muti array:
int X [][] = new int [8][16];
How put values of i in array and print it into a screen?
ok i put my whole code:
import java.util.Scanner;
public class IV_darbas {
public static void main(String[] arguments) {
int r, H, R, V, x, k, z;
Scanner ivestis = new Scanner(System.in);
boolean pabaiga = false;
while (!pabaiga) {
System.out.println("");
System.out.println("Si programa leis skaiciuoti turi");
System.out.println("Jei noresi testi spausk bet kuri klavisa");
System.out.println("Kai noresi baigti ivesk zodi: pabaiga ");
String first = "testi";
// Ivedi "R" reiksme
Scanner one = new Scanner(System.in);
System.out.println("Ivesk reiksme: R");
R = one.nextInt();
// Ivedi "H" reiksme
Scanner two = new Scanner(System.in);
System.out.println("Ivesk reiksme: H");
H = two.nextInt();
// Ivedi "R" reiksme
Scanner three = new Scanner(System.in);
System.out.println("Ivesk reiksme: r");
r = three.nextInt();
V = (int) ((Math.PI * Math.pow(H, 4) * (Math.pow(R, 2)
+ Math.pow(r, 2) + Math.pow(r, 5) * Math.pow(r, 3))) / 3);
System.out.println("Tavo gautas turis: " + V);
z = V * (-1);
System.out.println("Tavo gautas turis(su priesingu zenklu):" + z);
// Ivedamas papildomas skaicius
Scanner four = new Scanner(System.in);
System.out.println("Ivesk dar viena skaiciu: ");
x = four.nextInt();
k = x * z;
// salygos if sakinys
System.out.println("Pakeisto ir papildomo skaciaus sandauga: " + k);
if (k > 0) {
System.out.println("gautas skaicius " + k + " yra teigiamas");
} else if (k < 0) {
System.out.println("gautas skaicius " + k + " yra neigiamas");
} else if (k == 0) {
System.out.println("gautas skaicius " + k + " yra neutralus");
}
System.out.println("");
System.out.println("Sumavimas. Prie gauto rezultato: " + V);
for (int i=2; i<257; i=i*2 ){
V += i+0;
System.out.println("Suma: " +V+ " pridejus: "+i);
}
V = (int) ((Math.PI * Math.pow(H, 4) * (Math.pow(R, 2)
+ Math.pow(r, 2) + Math.pow(r, 5) * Math.pow(r, 3))) / 3);
System.out.println("");
System.out.println("Atimtis. Prie gauto rezultato: " + V);
for (int i=2; i<257; i=i*2 ){
V -= i+0;
System.out.println("Suma: " +V+ " atemus: "+i);
///////////////////
int X [][] = new int [8][16];
}
System.out.println("");
System.out.println("Ar testi? (n/y)");
first = ivestis.next();
if (first.equalsIgnoreCase("Pabaiga")) {
System.out.println("Darbas baigtas!");
break;
}
}
}
}
It is very unclear what you are trying to do and here is an example of what you might want to do.
// declared before any loop so it is in scope after the loop
int[][] values = new int[8][16];
int i = 1;
for(int x = 0; x < values.length; x++) {
for(int y = 0; y < values[x].length; y++) {
values[x][y] = i;
i += 2;
}
}
// to print the values
for(int x = 0; x < values.length; x++) {
for(int y = 0; y < values[x].length; y++) {
System.out.print(values[x][y] + " ");
}
System.out.println();
}
If you're asking just how to add something to an array it goes like this:
X[n] = i;
where n is an index in the array. But as someone already said you need to declare your array outside of the loop, otherwise it won't be accessible.

Categories

Resources