How put values from cycle to multi array - java

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.

Related

How to write a number as sum of some other numbers' power

Okay firstly I'm sorry I know that I'm not intelligent enough. I'm bad at Math.
I couldn't write an algorithm to this question.
System gives us int x, int y, int boundary and wants us to find which numbers up to boundary satisfy the rule as
some_number = x^i + y^j
Boundary <= 10^6
i and j > = 0
x and y < 100
for example x = 2, y = 3 and boundary= 5,
2 = 2^0 + 3^0
3 = 2^1 + 3^0
4 = 2^0 + 3^1
5 = 2^1 + 3^1
output : 2,3,4,5
import java.util.ArrayList;
public class Main {
public static ArrayList<Integer> find_numbers(int x, int y, int boundary) {
ArrayList<Integer> res = new ArrayList<Integer>();
int num = 0;
int remain_x = 0, remain_y = 0;
int count_x = 0, count_y = 0;
if (boundary >= 2) {
res.add(2);
}
for (int i = 3; i <= boundary; ++i) {
if(i == x+y)
res.add(i);
count_x = 0;
count_y = 0;
num = i;
while (num > 0) {
remain_x = num % x;
if (remain_x == 0) {
count_x++;
} else {
while (num > 0) {
remain_y = num % y;
if (remain_y == 0) {
count_y++;
}
num = num / y;
}
}
num = num / x;
}
System.out.println("i =>" +i);
System.out.println("x=>" + count_x);
System.out.println("y =>" + count_y);
}
return res;
}
public static void main(String[] args) {
ArrayList<Integer> res = new ArrayList<Integer>();
int x = 1 + (int) (Math.random() * 100);
int y = 1 + (int) (Math.random() * 100);
int boundary = 1 + (int) (Math.random() * 1000000);
res = find_numbers(x, y, boundary );
System.out.println(res);
}
}
Edit:
I wrote something after reading Shark's comment thank you so much. it's working.
import java.util.ArrayList;
public class Main {
public static ArrayList<Integer> find_numbers(int x, int y, int boundary) {
ArrayList<Integer> res = new ArrayList<Integer>();
int x_k = 0;
int y_k= 0;
while(Math.pow(x,x_k)< boundary){
x_k++;
}
while(Math.pow(y,y_k)< boundary){
y_k++;
}
for(int k = 2 ; k<= boundary;++k) {
for (int i = 0; i < x_k; ++i) {
for (int j = 0; j < y_k; ++j) {
if(k == (int)Math.pow(x,i)+(int)Math.pow(y,j) && !res.contains(k)){
System.out.println("----------------------------------------");
System.out.println(k +" =>" +x + "^" +i +"+"+y+ "^" +j);
res.add(k);
}
}
}
}
return res;
}
public static void main(String[] args) {
ArrayList<Integer> res = new ArrayList<Integer>();
int x = 1 + (int) (Math.random() * 100);
int y = 1 + (int) (Math.random() * 100);
int boundary = 1 + (int) (Math.random() * 1000000);
res = find_numbers(x, y,boundary);
System.out.println("x:" + x);
System.out.println("y:" + y);
System.out.println("boundary:" + boundary);
System.out.println("Result:" + res);
}
}
I am not sure if this is the most efficient method. Basically, I increment j until x^i + y^j > boundary then increment i.
public static ArrayList<Integer> findNumbers(int x, int y, int boundary) {
Set<Integer> result = new HashSet<>(); // make sure result is unique
int powerX = 0, powerY = 0, total = 0, tempX = 0;
while (true) {
// calculate x^i
tempX = (int) Math.pow(x, powerX);
while (true) {
// calculate x^i + y^j and compare against boundary
if ((total = tempX + (int) Math.pow(y, powerY)) <= boundary) {
// add result to set and increment y
result.add(total);
powerY++;
// break if y <= 1
if (y <= 1)
break;
} else
break;
}
// break if x <= 1 || x^i > boundary
if (tempX > boundary || x <= 1)
break;
// reset j and increment i
powerY = 0;
powerX++;
}
// return sorted result
ArrayList<Integer> arr = new ArrayList<>();
arr.addAll(result);
arr.sort(null);
return arr;
}
You might be able refactor the code for better efficiency.
public class Main {
public static ArrayList<Integer> find_numbers(int x, int y, int boundary) {
ArrayList<Integer> res = new ArrayList<Integer>();
int x_k = 0;
int y_k= 0;
while(Math.pow(x,x_k)< boundary){
x_k++;
}
while(Math.pow(y,y_k)< boundary){
y_k++;
}
for(int k = 2 ; k<= boundary;++k) {
for (int i = 0; i < x_k; ++i) {
for (int j = 0; j < y_k; ++j) {
if(k == (int)Math.pow(x,i)+(int)Math.pow(y,j) && !res.contains(k)){
System.out.println("----------------------------------------");
System.out.println(k +" =>" +x + "^" +i +"+"+y+ "^" +j);
res.add(k);
}
}
}
}
return res;
}
public static void main(String[] args) {
ArrayList<Integer> res = new ArrayList<Integer>();
int x = 1 + (int) (Math.random() * 100);
int y = 1 + (int) (Math.random() * 100);
int boundary = 1 + (int) (Math.random() * 1000000);
res = find_numbers(x, y,boundary);
System.out.println("x:" + x);
System.out.println("y:" + y);
System.out.println("boundary:" + boundary);
System.out.println("Result:" + res);
}
}

Bruteforce and Conquer and Divide not giving same distance answer for Closest Pair of Points

I created a program that generates a user inputted number of pairs of points. It then goes through a bruteforce and divide and conquer methods to find the closest pair of points. The bruteforce method works perfectly. The divide and conquer method on the other hand gives me an output but it is different than the brute force distance almost 90% of the time. I can't seem to figure out why it is like this in my code. NOTE: Some of the comments in the functions are from my teacher. Also, the closest_pair function along with rec_cl_pair have been given to me by my teacher where I must use them but had to adjust to my code (they were pseudo code for most part).
My code is:
import java.util.*;
import static java.lang.Math.min;
public class ClosestPair{
private Double x;
private Double y;
private static Double minDist = Double.POSITIVE_INFINITY;
private static ClosestPair closestPair1 = new ClosestPair(0.0,0.0);
private static ClosestPair closestPair2 = new ClosestPair(0.0,0.0);
public ClosestPair(Double x, Double y){
this.x = x;
this.y = y;
}
public static void main(String[] args) {
Double rangeMin = 0.0;
Double rangeMax = 1000.0;
Random r = new Random();
Scanner scan = new Scanner(System.in);
System.out.print("\nEnter the number of two dimensional arrays: ");
int dim = scan.nextInt();
ClosestPair[] pair = new ClosestPair[dim];
ClosestPair[] pairCopy = new ClosestPair[dim];
for(int i = 0; i < dim; i++){
Double xVal = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
Double yVal = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
pair[i] = new ClosestPair(xVal,yVal);
//System.out.print(pair[i].x + ", " + pair[i].y + "\n");
}
/*
for(int j = 0; j < pair.length; j++){
System.out.print(pair[j].x + ", " + pair[j].y + "\n");
}
*/
pairCopy = pair;
pair = mergeSort(pair);
/*
System.out.print("\n\n\n");
for(int j = 0; j < pair.length; j++){
System.out.print(pair[j].x + ", " + pair[j].y + "\n");
}
*/
//BRUTE FORCE PRINT STATEMENTS
long startTime = System.nanoTime();
bruteForce(pair);
long endTime = System.nanoTime();
long timeSpent = endTime - startTime;
System.out.print("\nMin Distance = " + minDist);
System.out.print("\n(x1,y1) = " + closestPair1.x + ", " + closestPair1.y);
System.out.print("\n(x2,y2) = " + closestPair2.x + ", " + closestPair2.y);
System.out.print("\nTime: " + timeSpent + "\n\n");
minDist = 0.0;
//CONQUER DIVIDE PRINT STATEMENTS
startTime = System.nanoTime();
minDist = closest_pair(pairCopy);
endTime = System.nanoTime();
timeSpent = endTime - startTime;
System.out.print("Min Distance = " + minDist);
System.out.print("\nTime: " + timeSpent);
scan.close();
}
private static void bruteForce(ClosestPair[] pair) {
for(int i = 1; i < pair.length - 1; i++){
for(int j = i + 1; j < pair.length; j++){
ClosestPair p = new ClosestPair(pair[i].x,pair[i].y);
//System.out.print("\np:" + pair[i].x + ", " + pair[i].y);
ClosestPair q = new ClosestPair(pair[j].x,pair[j].y);
//System.out.print("\nq: " + pair[j].x + ", " + pair[j].y);
if(getDistance(p, q) < minDist){
minDist = getDistance(p, q);
closestPair1.x = p.x;
closestPair1.y = p.y;
closestPair2.x = q.x;
closestPair2.y = q.y;
}
}
}
}
private static Double getDistance(ClosestPair p1, ClosestPair p2) {
double xdist = p2.x - p1.x;
double ydist = p2.y - p1.y;
return Math.hypot(xdist, ydist);
}
static ClosestPair[] mergeSort(ClosestPair[] a) {
if (a.length > 1) {
int q = a.length/2;
ClosestPair[] leftArray = Arrays.copyOfRange(a, 0, q);
ClosestPair[] rightArray = Arrays.copyOfRange(a,q,a.length);
mergeSort(leftArray);
mergeSort(rightArray);
a = merge(a,leftArray,rightArray);
}
return a;
}
static ClosestPair[] merge(ClosestPair[] a, ClosestPair[] l, ClosestPair[] r) {
int totElem = l.length + r.length;
//int[] a = new int[totElem];
int i,li,ri;
i = li = ri = 0;
while ( i < totElem) {
if ((li < l.length) && (ri<r.length)) {
if (l[li].x < r[ri].x) {
a[i] = l[li];
i++;
li++;
}
else {
a[i] = r[ri];
i++;
ri++;
}
}
else {
if (li >= l.length) {
while (ri < r.length) {
a[i] = r[ri];
i++;
ri++;
}
}
if (ri >= r.length) {
while (li < l.length) {
a[i] = l[li];
li++;
i++;
}
}
}
}
return a;
}
//START OF CONQUER DIVIDE SECTOIN
static double closest_pair(ClosestPair[] p){
int n = p.length - 1;
p = mergeSortDC(p, 0, n); // sort all n points by x-coordinate
return rec_cl_pair(p, 0, n);
}
static double rec_cl_pair(ClosestPair[] p, int i, int j){ // finds closest pair between points in p[i..j]
// assumes input is sorted by x-coordinate
// at termination, input is sorted by y-coordinate
// i is the left index of the subarray, j is the right index
if (j - i < 3){ // at most 3 points in p[i..j]
p = mergeSortDC (p, i, j); // sort p[i..j] by y-coordinate
double delta = getDistance(p[i], p[i+1]);
if (j - i == 1) { // two points
minDist = delta;
return delta;
}
else{
double min1 = min(getDistance(p[i+1], p[i+2]), getDistance(p[i], p[i+2]));
minDist = min(delta,min1);
return minDist;
}
}
int m = (i + j)/2;
double line = p[m].x;
double deltaL = rec_cl_pair(p, i, m); // p[i..m] is sorted by y-coordinate
double deltaR = rec_cl_pair(p, m+1, j); // p[m+1..j] is sorted by y-coordinate
double delta = min(deltaL, deltaR);
p = mergeDC(p, i, m, j); // p[i..j] is now sorted by y-coordinate
// Of points in p[i..j], find points in vertical strip of width 2*delta,
// centered at line (middle of x-values), and store in array v
int t = 0;
ClosestPair[] v = new ClosestPair[j+1];
for(int k = i; k < j; k++){
if ((p[k].x > line - delta) && (p[k].x < line + delta)){
t = t + 1;
v[t] = p[k];
}
}
// Find closest pairs among points in array v. NOTE: Cool math shows
// there are at most 8 points in the strip at distance < delta. Thus,
// in the loops below, each point is compared to at most 7 other points.
for(int k = 1;k < t-1; k++){
for(int s = k+1; k < min(t,k+7); s++){ // inner loop iterates <= 7 times
delta = min(delta, getDistance(v[k],v[s]));
minDist = delta;
return delta;
}
}
return minDist;
}
private static ClosestPair[] mergeSortDC(ClosestPair[] p, int low, int high) {
// check if low is smaller then high, if not then the array is sorted
if (low < high) {
// Get the index of the element which is in the middle
int middle = low + (high - low) / 2;
// Sort the left side of the array
mergeSortDC(p, low, middle);
// Sort the right side of the array
mergeSortDC(p, middle + 1, high);
// Combine them both
p = mergeDC(p, low, middle, high);
}
return p;
}
private static ClosestPair[] mergeDC(ClosestPair[] p, int low, int middle, int high) {
ClosestPair[] helper = new ClosestPair[p.length];
// Copy both parts into the helper array
for (int i = low; i <= high; i++) {
helper[i] = p[i];
}
int i = low;
int j = middle + 1;
int k = low;
// Copy the smallest values from either the left or the right side back
// to the original array
while (i <= middle && j <= high) {
if (helper[i].x <= helper[j].x) {
p[k] = helper[i];
i++;
} else {
p[k] = helper[j];
j++;
}
k++;
}
// Copy the rest of the left side of the array into the target array
while (i <= middle) {
p[k] = helper[i];
k++;
i++;
}
return p;
}
}
An example of output is:
Enter the number of two dimensional arrays: 50
Min Distance = 19.014027210555614
(x1,y1) = 76.99595098629398, 600.1657767818473
(x2,y2) = 87.04091889578226, 616.3098732403395
Time: 3852815
Min Distance = 29.457199999686082
Time: 414081
The first min distance is the bruteforce result. The second is the divide and conquer result

Issues when taking Dice one and Dice two with the same value and adding it to an integer

I am currently trying to get the number of times the two dice have identical values. This is what I have so far.
public static void main(String [] args)
{
System.out.print("Enter the amount of rolls you want to do: ");
Scanner scan = new Scanner(System.in);
int r = scan.nextInt();
final int FACES = 6, ROLLS = r;
int [] rollCount = new int [FACES];
int [] rolCount = new int [FACES];
Die d1 = new Die();
Die d2 = new Die();
int myRoll = 0;
int myRollTwo = 0;
int Ident = 0;
int i = 0;
while (i <= 1)
{
int ii = 0;
int iii = 0;
for (ii = 1; ii <= ROLLS; ii++)
{
myRoll = d1.roll();
rollCount[myRoll - 1]++;
}
for (ii = 1; ii <= ROLLS; ii++)
{
myRollTwo = d2.roll();
rolCount[myRollTwo - 1]++;
iii++;
}
if (myRoll == myRollTwo)
{
Ident++;
}
if (iii == ROLLS)
{
i++;
}
}
System.out.println("Die Number\tDie One\tDie Two\tTotal\t Amount of Identical Rolls");
for (i = 0; i < rollCount.length; i++)
{
System.out.println((i + 1) + "\t\t\t" + rollCount[i] + "\t\t" + rolCount[i] + "\t\t" + ((rollCount[i] + rolCount[i])*(i + 1)) + "\t\t" + Ident);
}
}
I know that the if statement near the end of the while loop wouldn't work because it would only do it once, so how exactly would I go about getting the number of times the two dice were the same?

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.

Greedy LCS Java Code Implementation

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.

Categories

Resources