Change int to string in a matrix - java

I want to convert some integers into a * based on a rule. I can determine which places in the matrix it should convert, but cannot convert it.
I give the program the first matrix and it should return the second matrix:
5 4 5 5 8
5 4 6 4 1
3 4 5 4 6
7 8 4 3 6
5 4 5 5 *
5 4 * 4 1
3 4 5 4 6
7 * 4 3 6
my code is this:
for(int i=1; i<r-1; i++) {
for(int a=1; a<c-1; a++){
if(matrix[i-1][a] < matrix[r][a] && matrix[i+1][a] < matrix[r][a] && matrix[i][a-1] < matrix[r][a] &&
matrix[i][a+1] < matrix[r][a]) {
matrix[r][a] = *;
}
}
}
Edit:
The matrix is an int type. I can determine which locations in the matrix should be converted, however the convertion itself does not work.
I get this error: Error: Syntax error on token "*", invalid Expression

you can use matrix of type Integer instead of int and then mark a * cell with null
Then when printing or using matrix show null values with *

You could leave int[][] matrix, and e.g. mark a * cells with some illegal number (e.g. Integer.MAX_VALUE). And when you print or use this matrix, do like: System.out.print(matrix[i][k] != Integer.MAX_VALUE ? matrix[i][k] : '*')
public static void main(String... args) {
int[][] matrix = new int[5][5];
modifyMatrix(matrix);
print(matrix);
}
public static void modifyMatrix(int[][] matrix) {
for (int row = 0; row < matrix.length; row++)
for (int col = 0; col < matrix[row].length; col++)
if (isStar(row, col, matrix))
matrix[row][col] = Integer.MAX_VALUE;
}
private static boolean isStar(int row, int col, int[][] matrix) {
// TODO your condition to place a '*'
return false;
}
private static void print(int[][] matrix) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0, max = matrix[row].length; col < msx; col++) {
System.out.print(matrix[row][col] != Integer.MAX_VALUE ? matrix[row][col] : '*');
System.out.println(col != max - 1 ? ' ' : '\0');
}
System.out.println();
}
}

In an int matrix you can't put characters or symbols(like '*')
The easiest thing to do is to change the type of the matrix. You should use char instead of int.
char[][] matrix = new char[r][c];
If you want to use an element from the matrix for equations you can use the
Character.getNumericValue(matrix[i][j]);
With this code it will return the number and if it has not numeric value it will return -1
You can check this link for the getNumericValue
click here

you should create an new array of strings the size of your matrix.
then run trough your matrix and either add the number or change it into a string, like this:
public String[] convert(int[] matrix,int rule) {
String[][] arr = new String[matrix.length][matrix[0].length];
for(int i = 0;i<matrix.length;i++) {
for(int j = 0; j<matrix[i].length;j++) {
if(matrix[i][j] == rule)
arr[i][j] = "*";
else
arr[i][j] = String.valueOf(matrix[i][j]);
return arr;

Related

How to count the numbers of letters for each column in a String [][]?

I want to count the number of letters in a String [][] by column , so far my code is this :
for(int j = 0 ; j<matrix[0].length ;j++){
for(int i = 0 ; i< matrix.length ;i++ )
if (Character.isLetter(matrix[j][i].charAt(j)))
countChar++;
}
System.out.println(countChar + "letters");
return countChar;
but the output of the program counts how many elements the string has
for example if the String is :
String [][] C = {
{"abc", "abcd" , "abcd"},
{"oroeo", "kakakak" , "alsksjk"},
{"abcdef", "asdasdasdasd", "asdasdasdasd"},
};
the result is 9 , but should be 14 (number of letters by column )
Any help is greatly apreciated thank you !
You can define a 2D matrix as an array of rows or an array of columns. I'm assuming you have defined it as an array of rows and now want to get the values in a certain column.
So your data looks like this:
abc abcd abcd
oroeo kakakak alsksjk
abcdef asdasdasdasd asdasdasdasd
three rows and three columns.
to get for example the values in the middle column (with index 1) you would need to get the array elements:
matrix[0][1]
matrix[1][1]
matrix[2][1]
I think you are trying to count the total of the lengths of all values in each column. That would go like this:
// assume that the matrix has at least one row and thas the same number of columns in each row
// take the number of columns in the first row for reference
int numberOfColumns = matrix[0].length;
for(int col = 0; col < numberOfColumns; col++) {
int count = 0;
// iterate over all the rows
for(String[] row : matrix) {
// count the length of the element in position col of this row
count += row[col].length();
}
System.out.printf("%s characters in column %s", count, col);
}
int n = 0;
// iterate row by row
for (int i = 0; i < C.length; i++) {
n += C[i][0].length();
// get the string at index 0 (or 1 or 2.. whichever you want) of the array and append its length
// if you expect the string to contain numbers, then
// run a for-loop on the string and check if its a letter
}
System.out.println(n);
Try below the problem is with your for loop for which the no. of iterations are limited to the size of your matrix:
for(int i = 0 ; i<C[0].length ;i++) {
String matrixElement = C[i][0];
System.out.println(matrixElement);
for(int k =0 ;k < matrixElement.length();k++)
if (Character.isLetter(matrixElement.charAt(k)))
countChar++;
}
Please, format out your code and brush up the loop:
private static int countByColumn(String[][] matrix, int column) {
if (column < 0)
return 0; // Or throw exception
int countChar = 0;
for (String[] line : matrix) {
//DONE: jagged array: it may appear that the line is too short
if (line.length <= column)
continue;
String item = line[column];
for (int i = 0; i < item.length; ++i)
if (Character.isLetter(item.charAt(i)))
countChar += 1;
}
return countChar;
}
Test:
// 14
int test = countByColumn(C, 0);

How to print parts of an 2d array

Im not asking for the answer per say im asking necessarily what would i need to change in order to print out sections of a 2d array for example if the array has 5 rows and 5 columns how would i print out the last 3 rows and last three columns.
import java.util.Scanner;
public class multiplication {
static int a,b;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
a =input.nextInt();
b = input.nextInt();
int[][] matrix = new int[a][b];
matrix = timesTable(a,b);
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(" "+matrix[row][column] + "\t|");
}
System.out.println();
}
}
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[c][c];
for ( r = 0; r < yes.length ; r++)
{
for (c = 0; c < yes[r].length; c++)
{
yes[r][c] = (r+1)*(c+1);
}
}
return yes;
}
}
if((row = 0 && col > 1) ||( row > 1 && col != 1)) {
//print
}
This logic should work for your example. But I don't understand what you're trying to do.
Can you try explain a bit more what you want to do ?
Edit: you might wanna check this. Oracle documentation bottom of the page with arraycopy and arraymanipulation
Is the goal of this exercise to build the matrix and then print the matrix -or- do you simply need to display the desired output? I assume this is a class assignment.
Hint: Think about this .. if you enter 2 & 5, do you want a 2x5 matrix or a 4x4 matrix? It's important when you alloc your matrix size.

Copy 2D array and increase size to fill new values

I would like to first apologize if my question is worded badly. I have an exam tmmrw and the prof gave a sample final exam for us to practice with. He unfortunately isn't responding with the solutions on the forum so I am trying to provide solutions on there. I seem to be stuck on this question. I have to write a method that accepts and NxM array filled with integer values as a parameter. The method is to return an (N+1)x(M+1) array which contains the contents of the original array in the first N rows and M columns plus a count of items greater than or equal to zero in each row/column at the end of that row/column and put the value -1 in the bottom right corner. for example.
1 -2 0 returns 1 -2 0 2
3 -4 -5 3 -4 -5 1
2 0 1 -1
I seem to be able to copy the array yet I am puzzled as to how I can enter the values in the outer parts of the new array. Here is what I have so far.
public static void main(String[] args) {
int[][] arr = { { 1, -2, 0 }, { 3, -4, -5 } };
int[][] newMatrix = processing2D(arr);
printArray(newMatrix);
}
//Method where I am having problems
public static int[][] processing2D(int[][] arr) {
int[][] matrix = new int[arr.length][arr[0].length];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
matrix[row][col] = arr[row][col];
}
}
// assign the corner -1 here
return matrix;
}
public static void printArray(int[][] list) {
for (int row = 0; row < list.length; row++) {
for (int col = 0; col <= list.length; col++) {
System.out.print(list[row][col] + " ");
}
System.out.println();
}
}
First off you are initializing the new array wrong it should be
int[][] matrix = new int[arr.length+1][arr[0].length+1];
You don't want it to be the same length you want it to be the length +1. Also in your for loops you want to go by the length of arr not matrix since thats what you're taking from. While putting the values into the new N+1xM+1 array, increment the value of the corresponding last element in that row and column by 1 if it is >=0.
for (int row = 0; row < arr.length; row++) {
for (int col = 0; col < arr[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
if(arr[row][col]>=0){
matrix[row][matrix[row].length-1] = matrix[row][matrix[row].length-1] + 1;
matrix[matrix.length-1][col]= matrix[matrix.length-1][col] + 1;
}
matrix[row][col] = arr[row][col];
}
After putting all the values back into the new N+1xM+1 array you should now take the values in the n sized and m sized arrays and put them into the corresponding slot in the N+1xM+1 array. After that just put the -1 in the bottom right slow manually.
matrix[matrix.length-1][matrix[0].length-1]=-1;
In your process2D method start off by creating an array with the correct size which has 1 more row and 1 more column than the original:
int[][] matrix = new int[arr.length+1][arr[0].length+1];
Then to populate the matrix array you do like you were doing before, but you need to take care not to reference an index of the arr array that is out of bounds. Because your matrix index is bigger than arr. If you are populating the new indexes then you can just use random numbers.
if(row < arr.length && col < arr[0].length)
{
matrix[row][col] = arr[row][col];
}
else
{
matrix[row][col] = new Random().nextInt(10);
}
So here is the full method process2D:
public static int[][] processing2D(int[][] arr) {
int[][] matrix = new int[arr.length+1][arr[0].length+1];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
// once I reach the last pos I enter the count
// of numbers greater than or equal to zero in that row/col
if(row < arr.length && col < arr[0].length)
{
matrix[row][col] = arr[row][col];
}
else
{
matrix[row][col] = new Random().nextInt(10);
}
}
}
// assign the corner -1 here
return matrix;
}

how to calculate the sum of elements after the diagonal in 2D array in java?

I have a function that I need to calculate the sum of elements after the diagonal in the 2D array, but the problem is that the function return the sum of the elements in the diagonal.
What I need is that if I have a matrix like this:
1 2 3
4 5 6
7 8 9
The elements of the diagonal are = 1 5 9
What I need is to calculate the numbers that follow after these diagonal numbers, so it will be like this:
1 2 3
4 5 6
7 8 9
sum = 2+3+6 = 11
I would appreciate it if someone could help me to fix my problem.
this my code:
public int calculate(){
int sum = 0;
for(int row = 0; row <matrix.length; row++){
for(int col = 0; col < matrix[row].length; col++){
if(row == col){
sum = sum + row+1 ;
}
}
}
System.out.println("the sum is: " + sum );
return sum;
}
public static void main(String[] args) {
int[][] ma = new int[2][2];
Question2 q2 = new Question2(2, 2, ma);
q2.fill();
q2.calculate();
}
the output is:
2 1
2 1
the sum is: 3
You want col to go through all elements, being always bigger than the diagonal.
Therefore try:
int sum = 0;
for(int i = 0 ; i < a.length ; ++i) {
for(int j = i + 1 ; j < a[i].length ; ++j) {
sum += a[i][j];
}
}

Java Diagonal Matrix

I have been wondering how to diagonally wrap, from bottom left, a String into a matrix.
For example:
String str = "123456789";
//Output matrix:
// 479
// 258
// 136
//Or if str = "123456789123456";
//Output would be:
// 2
// 73
// 484
// 2595
// 13616
Here is what I have so far:
int index = 0;
for(int i = 0; i < matrix.length; i++)
{
for(int k = matrix.length - 1; k > -1; k--)
{
if(index == word.length())
break;
matrix[k][i] = "" + str.charAt(index);
index++;
}
}
This is reasonably efficient implementation which I believe is relatively easy to understand.
This code loops over successive diagonals, and when the current position is inside the matrix, it assigns the next character from the string.
In the below chart, the question mark positions are on the diagonal but they're not inside the matrix. No character is taken from the input string for these question mark positions.
Diagonal Matrix
4 ?
3 ??
2 479
1 258?
0 136??
The loop goes through rows in ascending order, but the assignment to each row is done in reverse because your matrix is upside down when viewed from the normal Java way of indexing arrays: matrix[size - row - 1] instead of matrix[row].
There is no need for special treatment of below, at and above the diagonal this way.
public static void main(String[] args) throws Exception {
String str = "123456789";
int size = 3;
int[][] matrix = new int[size][size];
{
int index = 0;
for (int diagonal = 0; diagonal < size * 2 - 1; diagonal++) {
int row = diagonal;
int column = 0;
while (row >= 0) {
if (row < size && column < size) {
matrix[size - row - 1][column] = Character.getNumericValue(str.charAt(index++));
}
row--;
column++;
}
}
}
}
It also works for larger sized matrices (4x4, 5x5 etc.) but you can only encode values up to 9 in your string - if you want higher values, it's better to encode them in a comma-separated string and split the string into an array of strings.
Not making any claims about efficiency here, but it should work so long as your string fits into a square matrix:
static char[][] toDiag(String s)
{
int sideLen = (int) Math.sqrt(s.length()); // assume string fits into
// square matrix
char[][] m = new char[sideLen][sideLen];
int index = 0;
//fill lower-left section of array
for (int i = m[0].length - 1; i >= 0; i--)
{
for (int k = 0; k <= m[0].length-1-i; k++)
{
m[i+k][k] = s.charAt(index++);
}
}
//fill upper-right section of array
for (int i = sideLen%2==1?sideLen/2:sideLen/2 -1; i <= m[0].length; i++)
{
for (int k = 0; k <= m[0].length-1-i; k++)
{
m[k][i+k] = s.charAt(index++);
}
}
return m;
}
public static void main(String[] args)
{
String inString = "123456789";
int N = (int) Math.sqrt((double) inString.length());
int out[][] = new int[N][N];
int index=0;
//fills elements below the diagonal
for(int i=0;i<N-1;i++)
for(int j=0;j<=i;j++)
out[N-1-i+j][j] = Character.getNumericValue(inString.charAt(index++));
//fills the diagonal
for(int i=0;i<N;i++)
out[i][i] = Character.getNumericValue(inString.charAt(index++));
//fills elements above the diagonal
for(int i=N-2;i>=0;i--)
for(int j=0;j<=i;j++)
out[j][N-1-i+j] = Character.getNumericValue(inString.charAt(index++));
//prints the output
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
System.out.print(out[i][j] + "\t");
}
System.out.println();
}
}

Categories