Above is the image of my application.i am build an application to do the alignment of two string.the two string will be compared and a 2d array will be populated.the values of the 2d array will be the values of the matrix.All works perfectly fine the only prob i ma having is that i want when it print the values of the matrix it prints it in a matrix format as it the example below instead of having an output of "0000000011011000002100013" i want it to display as this
0 0 0 0 0
0 0 1 0 0
0 0 1 0 0
0 1 0 2 1
0 1 0 1 3
When print out it has to see if the number of character printed is equal to my row size and then move to next line and continues to print until all matrix values has been displayed.Below are my pieces of my codes.thank you in advance
Code for my Compute matrix button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
match_reward = Integer.parseInt (match_tf.getText());
mismatch_penalty =Integer.parseInt (mismatch_tf.getText());
gap_cost=Integer.parseInt(gap_tf.getText());
build_matrix();
collumn_tf.setText(String.valueOf(max_col));
row_tf.setText(String.valueOf(max_row));
highest_score_tf.setText(String.valueOf(max_score));
StringBuilder sb = new StringBuilder();
for (int i =0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sb.append(String.valueOf(matrix[i][j]));
sb.append(' ');
}
}
matrix_tf.setText(sb.toString());
}
Code to build my matrix
private void build_matrix() {
String seq1 = sequence1_tf.getText();
String seq2 = sequence2_tf.getText();
int r, c, ins, sub, del;
rows = seq1.length();
cols = seq2.length();
matrix = new int [rows][cols];
// initiate first row
for (c = 0; c < cols; c++)
matrix[0][c] = 0;
// keep track of the maximum score
max_row = max_col = max_score = 0;
// calculates the similarity matrix (row-wise)
for (r = 1; r < rows; r++)
{
// initiate first column
matrix[r][0] = 0;
for (c = 1; c < cols; c++)
{
sub = matrix[r-1][c-1] + scoreSubstitution(seq1.charAt(r),seq2.charAt(c));
ins = matrix[r][c-1] + scoreInsertion(seq2.charAt(c));
del = matrix[r-1][c] + scoreDeletion(seq1.charAt(r));
// choose the greatest
matrix[r][c] = max (ins, sub, del, 0);
if (matrix[r][c] > max_score)
{
// keep track of the maximum score
max_score = matrix[r][c];
max_row = r; max_col = c;
}
}
}
}
Just append a \n newline after the inner loop:
for (int i =0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sb.append(String.valueOf(matrix[i][j]));
sb.append(' ');
}
sb.append('\n');
}
Related
I have this matrix :
So 2 line and 2 columns.
1 2
3 4
I have the reading function
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
try {// System.out.println("number is ");
a[i][j] = scanner.nextInt();
} catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
} //print the input matrix
How can I make a border to a matrix? I've seen that in java there is no index -1.
I want a border with a number. For example :
0 0 0 0
0 0 0 0
0 1 2 0
0 3 4 0
0 0 0 0
How should I make that border function?
So, you need a (m+2) x (n+2) matrix:
// initialize m and n
...
// initialize the matrix with 0s
int a[][] = new int[m+2][n+2];
Then ignore the first elements (i and j should skip 0) and the last elements (i should skip m+1, j should skip n+1):
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
try {
a[i][j] = scanner.nextInt();
} catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
}
First you need to create the matrix with extra rows and columns, for example in your case a 4x4 matrix. and them put 0 on the borders
when i==0 or i==n-1, j==0 or j==n-1,
int a[][] = new int[4][4];
int n,m;
n=4;
m=4;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==0 || j==0 || i==m-1 || j==n-1){
//a[i][j] = 0;
a[i][j] = 1;
}
System.out.print(a[i][j]+" ");
}
System.out.println();
}
then
for (int i = 1; i < m-1; i++) {
for (int j = 1; j < n-1; j++) {
try {// System.out.println("number is ");
a[i][j] = scanner.nextInt();
} catch (java.util.NoSuchElementException e) {
// e.printStackTrace();
}
}
} //print the input matrix
Elaborating on my comment:
If you first put in words what creating a border means, then translating it from English to Java is a simple task.
Let's take a look at the the two matrices that you have given:
Original one:
1 2
3 4
With border:
0 0 0 0
0 1 2 0
0 3 4 0
0 0 0 0
We see that when creating a border, we increase the width and height of the matrix by 2 respectively (to have an empty row of 0s on the top-bottom, and left-right), so instead of a 2x2 matrix we now have 4x4, and the indices of the elements are incremented by 1 (every element is pushed one step to the right, and one step downwards).
Putting this is in code:
int[][] createBorder(int[][] matrix) {
//this is our 4x4 matrix
int[][] borderedMatrix = new int[matrix.length+2][matrix[0].length+2];
//fill the 4x4 matrix with 0's
for(int i = 0; i < borderedMatrix.length; i++) {
for(int j = 0; j < borderedMatrix[0].length; j++) {
borderedMatrix[i][j] = 0;
}
}
//copy the values of the 2x2 into the 4x4 matrix, but push them one step to the right, and one step downwards
for(int k = 0; k < matrix.length; k++) {
for(int l = 0; l < matrix[0].length; l++) {
borderedMatrix[k+1][l+1] = matrix[k][k];
}
}
return borderedMatrix;
}
The simplest way would be to create a matrix of n+1xm+1, populate the border with 0 then fill in the remainder with the original nxm matrix.
So if I had your example matrix
int[][] original = {{1, 2},
{3, 4}};
int borderWidth = original[0].length + 2;
int borderHeight = original.length + 2;
int borderArray = new int[borderHeight][borderWidth];
for (int i = 0; i < borderWidth; i++) { //border
borderArray[0][i] = 0; //populate top row
borderArray[borderHeight - 1][i] = 0; //populate bottom row
if (i == 0 || i == borderWidth - 1) { //populate left and right columns
for (j = 1; j < borderHeight - 1; j++) {
borderArray[j][i] = 0;
}
}
}
for (int i = 0; i < original.length; i++) { //populate middle with original
System.arraycopy(original[i], 0, borderArray[i+1], 1, original[].length);
}
I have an int[ ][ ] a that contains both positive and negative integers. I want to copy only the positive integers into another array, int[ ][ ] result.
Here's my attempt:
for( int r = 0; r < a.length; r ++ )
{
int aC = 0;
for( int resC = 0; resC < result[r].length; resC++ )
{
while (a[r][aC] < 0)
{
aC++;
}
result[r][resC] = a[r][aC];
aC++;
}
}
When I run the program it crashes on line 6 quoting a java.lang.ArrayIndexOutOfBoundsException: 3 error. When I run the debugger I can see that it works so long as r = 0.
I feel like I'm missing something blindingly obvious but after staring at it for an hour I still can't find the problem.
Why have 3 loops? Just loop your 2 dimensions and copy positive values:
for (int r = 0; r < a.length; r++)
for (int c = 0; c < a[r].length; c++)
if (a[r][c] > 0)
result[r][c] = a[r][c];
Unless of course you want to condense the values (question didn't say, but code attempt seems to indicate). Or did you also want to truncate?
Input Copy Condensed Truncated
-1 1 2 0 1 2 1 2 0 1 2
-1 -1 3 ==> 0 0 3 ==> 3 0 0 ==> 3
4 -1 5 4 0 5 4 5 0 4 5
Here is a version with truncation:
int[][] result = new int[a.length][];
for (int r = 0; r < a.length; r++) {
int count = 0;
for (int c = 0; c < a[r].length; c++)
if (a[r][c] > 0)
count++;
result[r] = new int[count];
for (int c = 0, cRes = 0; c < a[r].length; c++)
if (a[r][c] > 0)
result[r][cRes++] = a[r][c];
}
When we reach the inner for loop,
we don't have any guarantees about result[r],
and so r may very well be out of bounds.
Instead of this:
for (int r = 0; r < a.length; r++) {
int aC = 0;
for (int resC = 0; resC < result[r].length; resC++) {
The code will be safer like this:
for (int r = 0; r < a.length; r++) {
int aC = 0;
for (int resC = 0; resC < a[r].length; resC++) {
Because, we know that a[r] will be within bounds.
But this is not nearly enough.
The innermost while loop is also likely to try to access an index out of bounds, in fact it's inevitable when you have at least one negative value.
Actually you need to invert the looping logic there,
instead of iterating over indexes in result,
it will make more sense to iterate over indexes in the source.
Like this:
for (int r = 0; r < a.length; r++) {
int resC = 0;
for (int aC = 0; aC < a[r].length; aC++) {
if (a[r][aC] < 0) {
continue;
}
result[r][resC++] = a[r][aC];
}
}
Finally, with variables renamed, it becomes a lot easier to understand what the code is trying to do:
for (int row = 0; row < source.length; row++) {
int targetCol = 0;
for (int col = 0; col < source[row].length; col++) {
if (source[row][col] < 0) {
continue;
}
target[row][targetCol++] = source[row][col];
}
}
You have no bounds checking on
a[r][aC]
so
while (a[r][aC] < 0)
will fail.
Also as you will now have uneven sized arrays, it would be better to to add to an ArrayList, and then convert to an array afterwards if necessary.
Something like
ArrayList <Integer> posValues = new ArrayList <Integer> ();
for( int r = 0; r < a.length; r ++ )
{
for( int c = 0; c < a[r].length; c++ )
{
if (a[r][c] > 0)
{
posValues.add (new Integer (a[r][c]));
}
}
}
This is what I want to do when A is a square matrix.
P - is power.
A & B are square matrices.
User will be asked to enter size of matrix A, and elements of matrix A and to what power they want to raise the matrix to.
Once they input what power, and what elements my program is supposed to calculate this:
(Assuming P = 5)
A^5 + A^4 + A^3 + A^2 + A
I have written a method that adds matrices a method that multiplies them, and a method that raises them to the power and they all work correctly.
The problem I am having is the final step which I showed above A^5 + A^4 + A^ 3...
This is where the problem gets even weirder, my program works when the elements in the matrix are all the same... such that a
2 2 2
2 2 2
2 2 2
matrix will give me the CORRECT output, BUT
1 2 3
4 5 6
7 8 9
matrix will give me the WRONG output and I have no idea why.
This is the method in which the problem is occuring
public static void addPowers(int [][] a, int[][] b, int p) {
while( p != 1){
b = addMatrices(powerMatrix(a,p), b) ;
addPowers(a,b,p-1) ;
return ;
}
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < b.length; j++)
System.out.print(b[i][j] + "\t") ;
System.out.println();
}
}
Just in case you ask, reason I have the recursive under a while loop is so it won't print over and over and over again.
Thanks for your time! :)
Edit: More clarifying information.
addMatrices is a method that adds matrices with an two int[][] arguments.
powerMatrix is a method that finds the power of a matrix with (int[][], int) arguments.
EDIT Methods being called...
public static int[][] multiplyMatrices(int matrixA[][], int matrixB[][]) {
int temp[][] = new int[matrixA.length][matrixB.length];
int matrix[][] = new int[matrixA.length][matrixB.length];
int sum = 0 ;
for (int i = 0; i < matrixA.length; i++)
{
for (int j = 0; j < matrixB.length; j++)
{
for (int l = 0; l < matrixA.length; l++)
{
sum += matrixA[i][l] * matrixB[l][j] ;
}
temp[i][j] = sum ;
sum = 0 ;
}
}
matrix = temp;
return matrix ;
}
public static int[][] addMatrices(int matrixA[][], int matrixB[][]) {
int temp[][] = new int[matrixA.length][matrixB.length];
int sum = 0 ;
for (int i = 0; i < matrixA.length; i++)
{
for (int j = 0; j < matrixB.length; j++) {
{
sum = matrixA[i][j] + matrixB[i][j] ;
}
temp[i][j] = sum ;
}
}
return temp ;
}
public static int[][] powerMatrix (int[][] a, int p) {
int[][] result = a;
for (int n = 1; n < p; n++)
result = multiplyMatrices(result, a);
return result;
}
In your addMatrices method, you should remove the third loop.
Like this:
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[i].length; j++) {
temp[i][j] = matrixA[i][j] + matrixB[i][j] ;
}
}
Can someone maybe help me with the following error. Exception in thread main java.lang.arrayindexoutofboundsexception : 3 at RowTrans.encrypt(Rowtrans.java:33)
at RowTrans.main(Rowtrans.java :7)
In my program I want to get a text. Put it in a matrix with 5 columns and determine the rows according to the length of the text. Then i want to change the column and row position so that the row gets the columns position and the column the row. And when a row does not contain 5 values I want to add the character Z in the empty spaces. Can anyone assist me on this error please.
Here is my code
import java.util.Scanner;
public class ColTrans {
public static void main(String[] args)
{
String ori = "This is my horse";
String enc = encrypt(ori);
System.out.println(enc);
// String dec = decrypt(enc);
// System.out.println(dec);
}
static String encrypt(String text)
{
String result = "";
text = text.toUpperCase();
int length = text.length();
int rows = length / 5;
char[][] b = new char[rows][5];
char[][] c = new char[5][rows];
char[] d = new char[length];
if ((length % 5) != 0)
rows = rows + 1;
int k = 0;
for (int i = 0; i < rows; i++)
for (int j = 0; j < 5; j++)
{
if (k > length)
b[i][j] = 'Z';
else
{
d[k] = text.charAt(k);
b[i][j] = d[k];
}
k++;
}
for (int i = 0; i < 5; i++)
for (int j = 0; j < rows; j++)
{
c[i][j] = b[j][i];
result = result + c[i][j];
}
return result;
}
}
Here is the cause:
You are increamenting row variable by one, once you have defined the array.
Move following line before line char [][] b =new char[rows][5];
if ((length % 5) != 0)
rows = rows + 1;
There are 2 issues in your code. First move the mod part before the matrix instantiation :
if ((length % 5) != 0)
rows = rows + 1;
char [][] b =new char[rows][5];
[...]
Then change if ( k > length ) to if ( k >= length )
just change your code as following:
if ((length % 5) != 0)
rows = rows + 1;
char[][] b = new char[rows][5];
char[][] c = new char[5][rows];
char[] d = new char[length];
According to your description:
text = text.toUpperCase();
char[] b = text.toCharArray();
char[][] c = new char[b.length][5];
int bLen = 0;
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < 5; j++) {
if(bLen < b.length)
c[i][j] = b[bLen++];
else
c[i][j] = 'Z';
}
}
//change the column and row position
char[][]d = new char[c[0].length][c.length];
for (int i = 0; i < d.length; i++) {
for (int j = 0; j < d[0].length; j++) {
d[i][j] = c[j][i];
}
}
Output: TI EZZZZZZZZZZZZHSHZZZZZZZZZZZZZI OZZZZZZZZZZZZZSMRZZZZZZZZZZZZZ YSZZZZZZZZZZZZZ
The adjacency matrix looks like this:
A B C D E
A 0 1 0 1 1
B 1 0 0 1 1
C 0 0 0 1 0
D 1 1 1 0 0
E 1 1 0 0 0
But it outputs
A B D E B E C
This is my code for the search, and I was wondering if you could tell me where I was going wrong. It is supposed to make sure that the letter hasn't already been looked at, but it doesn't seem to. Thanks in advance.
public static void breadthFirst(int[][] adjM)
{
int x = 0, y = 0;
Queue<Character> queue = new Queue<Character>();
ArrayList<Character> track = new ArrayList<Character>();
//finding a vertex to use to search.
char ch1;
outerloop:
for (int i = 0; i < adjM.length; i++)
{
for (int j = 0; j < adjM.length; j++)
{
if (adjM[i][j] == 1)
{
x = i; y = j;
ch1 = ((char)(x+65));
queue.enqueue(ch1);
track.add(ch1);
adjM[i][j] = 3; adjM[j][i] = 3;
break outerloop;
}
}
}
while (!queue.isEmpty())
{
char c = queue.dequeue();
System.out.print(c + " ");
for (int i = 0; i < adjM.length; i++)
{
for (int j = 0; j < adjM.length; j++)
{
char chari = ((char)(i+65));
char charj = ((char)(j+65));
if (adjM[i][j] != 0)
{
if (!track.contains(chari))
{
queue.enqueue(chari);
track.add(chari);
adjM[i][j] = 0; adjM[j][i] = 0;
}
else if (!track.contains(charj))
{
queue.enqueue(charj);
track.add(chari);
adjM[i][j] = 0; adjM[j][i] = 0;
}
}
}
}
}
}
In your implementation:
else if (!track.contains(charj))
{
queue.enqueue(charj);
track.add(chari); // this should be charj
adjM[i][j] = 0; adjM[j][i] = 0;
}
An easier way to do this is like this. Don't modify the adjacency matrix and just track the things that you've visited.
while (!queue.isEmpty())
{
char c = queue.dequeue();
System.out.print(c + " ");
char chari = ((int)(c-65));
track.add(chari)
for (int j = 0; j < adjM.length; j++)
{
char charj = ((int)(j+65));
if (adjM[chari][j] != 0 && !track.contains(chari))
{
queue.enqueue(charj);
}
}
}