I want to display minor of a matrix.
First, I have a matrix 3 x 3.
1 2 3
4 5 6
7 8 9
I want to display M11 (delete row 1 and col 1) so it's like
1 3
7 9
But with my program I got something like this
1 2
4 0
Here is my code :
public static double [][] Minor (double [][] M, int bar, int kol, int maxidx){
double [][] minor = new double [2][2];
int mini=0, minj=0;
for (int i=0; i<2;i++){
for (int j=0;j<2;j++){
if (i!=bar | j!=kol){
minor[mini][minj]=M[i][j];
minj++;
if (minj==(maxidx-1)){
mini++;
minj=0;
}
}
}
}
return minor;
}
For display the minor I used this code :
for (int i=0;i<2;i++){
for (int j=0;j<2;j++){
System.out.print(Minor(M,1,1,3)[i][j]+" ");
}
System.out.println();
}
What's wrong with my code?
if (i!=bar | j!=kol)
this | is bitwise operator not logical operator
however, your whole logic is wrong
do this
for (int i=0; i<=2;i++){
if(i!=bar)
{
for (int j=0;j<=2;j++){
if (j!=kol){
minor[mini][minj]=M[i][j];
minj++;
}
}
mini++;
}
}
}
I think this if (i!=bar | j!=kol){ is a problem. You should use || (logic or)
You are using bitwise OR where you should be using logical AND:
if (i!=bar && j!=kol){
^^
Right now you are only skipping the element at the intersection of bar and kol. Instead, you want to be skipping the entire bar row and the entire kol column.
As said in comments, that sounds overkill to loop through the 3x3 matrix just to pick numbers into a 2x2.
/** ?skip : which is the first row/column we should keep (0/1)
** ?last : shall we skip the last item of the row/column.
**/
public static double [][] MyMinor (double [][] M, int vskip, int vlast, int hskip, int hlast){
double [][] minor = new double [2][2];
int mini=0, minj=0;
minor[0][0]=M[vskip][hskip];
minor[0][1]=M[vskip][2-hlast];
minor[1][0]=M[2-vlast][hskip];
minor[1][1]=M[2-vlast][2-hlast];
return minor;
}
// to remove any bar/kol combo:
MyMinor(input,bar==0?1:0,bar==2?1:0,kol==0?1:0,kol==2?1:0);
First if we are trying to remove middle row and column I think your expected result would be:
1 3
7 9
So then I would say this is the code you are looking for:
public static double [][] Minor (double [][] M, int bar, int kol, int maxidx){
double [][] minor = new double [2][2];
int mini=0, minj=0;
for (int i=0; i<3;i++){
for (int j=0;j<3;j++){
if (i!=bar && j!=kol){
minor[mini][minj]=M[i][j];
minj++;
if (minj==(maxidx-1)){
mini++;
minj=0;
}
}
}
}
return minor;
}
Problem was with for loops: for (int i=0; i<2;i++) and for (int j=0;j<2;j++). As you can see it would never reach 3rd row and column in M so you will not be able to have result you expect. And also in your code
if (i!=bar | j!=kol)
should be replaced with
if (i!=bar && j!=kol) as you do not need any elements from both 'bar' row and 'kol' column.
Related
[SOLVED]
The title of this question is vague but hopefully this will clear things up.
Basically, what I am looking for is a solution to rotating this set of data. This data is set up in a specific way.
Here is an example of how the input and output would look like:
Input:
3
987
654
321
Output:
123
456
789
The '3' represents the number of columns and rows that will be used. If you input the number '4', you will be allowed to input 4 sets of 4 integers.
Input:
4
4567
3456
2345
1234
Output:
1234
2345
3456
4567
The goal is to find a way to rotate the data only if needed. You have to make sure the smallest corner number is at the top left. For example, for the code above, you rotated it so 1 is at the top left.
The problem I have is that I don't know how to rotate the data. I am only able to rotate the corners but not the sides. This is what my code does so far:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
I just do not know how to compare those characters and in the end rotate the data.
Any help would be appreciated! Any questions will be answered.
A detailed description of the problem is here(problem J4).
This is just a challenge I assigned myself for practice for next year's contest, so giving me the answer won't "spoil" the question, but actually help me learn.
Here is my code so far:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int max = kb.nextInt();
int maxSqrt = (max * max);
int num[] = new int[max];
String num_string[] = new String[max];
char num_char[] = new char[maxSqrt];
int counter = 0;
int counter_char = 0;
for (counter = 0; counter < max; counter++) {
num[counter] = kb.nextInt();
}
for (counter = 0; counter < max; counter++) {
num_string[counter] = Integer.toString(num[counter]);
}
int varPos = 0, rowPos = 0, charPos = 0, i = 0;
for (counter = 0; counter < maxSqrt; counter++) {
num_char[varPos] = num_string[rowPos].charAt(charPos);
i++;
if (i == max) {
rowPos++;
i = 0;
}
varPos++;
if (charPos == (max - 1)) {
charPos = 0;
} else {
charPos++;
}
}
//
for(int a = 0 ; a < max ; a++){
for(int b = 0 ; b < max ; b++)
{
num_char[counter_char] = num_string[a].charAt(b);
counter_char++;
}
}
//here is where the code should rotate the data
}
}
This is a standard 90 degree clockwise rotation for a 2D array.
I have provided the solution below, but first a few comments.
You said that you're doing this:
take the input of each line and turn them into strings
split those strings into separate characters
store those characters in an array
Firstly youre essentially turning a int matrix into a character matrix. I do not think you need to do this, since even if you do want to compare values, you can use the ints provided.
Secondly, there is no need to compare any 2 data elements in the matrix, since the rotation does not depend on any value.
Here is an adapted solution for java, originally written in C# by Nick Berardi on this question
private int[][] rotateClockWise(int[][] matrix) {
int size = matrix.length;
int[][] ret = new int[size][size];
for (int i = 0; i < size; ++i)
for (int j = 0; j < size; ++j)
ret[i][j] = matrix[size - j - 1][i]; //***
return ret;
}
If you wanted to do a counterCW rotation, replace the starred line with
ret[i][j] = matrix[j][size - i - 1]
Input in row 1 keeps on changing but row 2 is constant,and i want to search a character in row 2 and refer to that index in row 1.
This is all very basic stuff. You should read a Java Tutorial or text book.
How to make a char matrix in java?
Answer:
char[][] matrix = new char[M][N];
What is the syntax for replacing particular character in that matrix?
Answer:
matrix[i][j] = value;
Input in row 1 keeps on changing but row 2 is constant,and i want to search a character in row 2 and refer to that index in row 1.
I don't understand what you are asking.
In addition to Stephen C's good-quality answer, I would like to tackle the
Input in row 1 keeps on changing but row 2 is constant,and i want to
search a character in row 2 and refer to that index in row 1.
issue. Let's suppose your matrix is called matrix. This is how you can search a character in a row:
public char getCharIndex(char[][] matrix, int row, char character) {
for (int i = 0; i < matrix[row].length; i++) {
if (character == matrix[row][i]) return i;
}
return -1; //Not found
}
This is how you can use it:
int charIndex = getCharIndex(matrix, 2, 'a');
if (charIndex >= 0) {
//Do something with matrix[1];
}
Since indexing starts from 0, you might have meant 1 instead of 2 and 0 instead of 1. In that case:
int charIndex = getCharIndex(matrix, 1, 'a');
if (charIndex >= 0) {
//Do something with matrix[0];
}
Scanner in=new Scanner(System.in);
int t=in.nextInt(); //test cases
while(t-->0){
char ch[][]=new char[3][3]; //size of matrix 3
for(int i=0;i<3;i++){
String s=in.next(); //taking first line as input
for(int j=0;j<3;j++){
ch[i][j]=s.charAt(j); // then set all the characters in the matrix
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(ch[i][j]);
}
System.out.println();
}
}
The program I need to write is a square 2d array made of numbers, like this
0 1 2
3 4 5
6 7 8
or this
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
The program reads the number "d" (side of the square 2d array- above are examples of d=3 and d=5), number "n" (how many inputs there will be next) and these n inputs (eg. if n=3, the program should let me insert three numbers, like from the first example, let's say I'd choose 1 and 4 and 3. So the input looks like:
3
3
1 4 2
Then, it needs to calculate the distance between the first and second, second and third input and sum them up. That sum is then the output. Here is the program
if(b==2) {
int d=sc.nextInt();
int n=sc.nextInt();
int[][] array=new int[d][d]; //length and heigth of array
int c=0;
int manhattanDistanceSum=0;
for (int i = 0; i < n; i ++){ //for inserting values
for (int j = 0; j < n; j ++){
if (i < n){
i++;
array[i][j] = sc.nextInt();
}
else {
break;
}
for( i=0; i<array.length;i++) {
for( j=0;j<array[0].length;j++) {
array[i][j]=c; //actual locations of numbers
//numbers in array
c++;
if(manhattanDistanceSum != 0) {
int dx= c / d;
int dy= c % d;
c=Math.abs(dx) + Math.abs(dy);
manhattanDistanceSum+=c;
}
}
}
System.out.print(array[i][j]);
System.out.println();
}
}
System.out.println(manhattanDistanceSum);
}
}
}
*the b doesn't matter, it just means this is going to be a square array, so ignore it. It has nothing to do with this.
This is all I got, and need help with anything that is wrong in my code.
Thankyou
I've just cobbled together this example and tested that it works with positive and negative numbers. It might not do exactly what you want (for example, is the data in your array organised row-by-column or column-by-row) and it might not exactly format the output the way you want, but it should show you how to iterate through the array and analyse and then extract the data to produce a String which can be printed out.
Be sure to conduct your own testing (create unit tests for all cases which your application will need) as I have thrown this together in a few minutes in the hope that it would get you started. It should not be considered a finished product by any means.
public static void main(String[] args) {
int[][] data = {{0, -10734, 2}, {3, 437, 5}, {6, 733838, 8}};
System.out.println("Table:\n" + formatAsTable(data));
}
public static String formatAsTable(int[][] squareNumericArray) {
int cellSpacing = 2;
StringBuilder sb = new StringBuilder();
int squareSide = squareNumericArray.length;
int cellSize = findLargestNumericString(squareNumericArray)
+ cellSpacing;
for (int firstIndex = 0; firstIndex < squareSide; ++firstIndex) {
if (squareNumericArray[firstIndex].length != squareSide) {
throw new IllegalArgumentException(
"Array must have same size in both dimensions.");
}
for (int secondIndex = 0; secondIndex < squareSide; ++secondIndex) {
sb.append(String.format("%-" + cellSize + "d",
squareNumericArray[firstIndex][secondIndex]));
}
sb.append("\n");
}
return sb.toString();
}
private static int findLargestNumericString(int[][] squareNumericArray) {
int maxLength = 0;
for (int firstIndex = 0; firstIndex < squareNumericArray.length;
++firstIndex) {
for (int secondIndex = 0; secondIndex
< squareNumericArray[firstIndex].length; ++secondIndex) {
String numberAsString = Integer.toString(
squareNumericArray[firstIndex][secondIndex]);
if (numberAsString.length() > maxLength) {
maxLength = numberAsString.length();
}
}
}
return maxLength;
}
This code will output the following to the console:
Table:
0 -10734 6
3 437 5
6 733838 19
I know how to shift the row of the 2d array of type double
where i is the matrix size
public static void rowshiftRight(int i, double[][] array) {
int m = array[i].length;
double temp = array[i][m-1];
for (int k=m-1; k>=1; k--){
array[i][k] = array[i][k-1];
}
array[i][0] = temp;
}
I'm trying to change the above logic to shiftcolum, any help will be grateful
//wrong code
public static void colshiftdownorup(int i, double[][] array) {
int m = array.length;
double temp = array[m-1][i];
for (int k=m-1; k>=1; k--){
array[k][i] = array[k-1][i];
}
array[i][0] = temp;
}
The error appears to be at the last line of colshiftRight
Change :
array[i][0] = temp;
to :
array[0][i] = temp;
You may also want to rename the method to colshiftDown
Basically, to shift a column you will need some extra checks since 2D arrays are not always perfect matrices, e.g.:
int[][] array = new int[4][]; might be like this
2 3 4 5
1 1 1
1 2
1 2 3 4
If you want to shift 3rd column (4,1,null,3) you will see the extra work required to control null values.
Hey guys I am having problems writing this part of my code. I have to sum up the elements of this 2-dimensional array using recursion. I understand what I need to do but I am not understanding how to implement this to step through the array. I keep receiving errors. Could someone please help me out?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[][] a;
a = new int[3][4];
int sum = 0;
System.out.println("Enter 12 numbers: ");
Scanner scan = new Scanner(System.in);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
a[i][j] = scan.nextInt();
}
}
sum = sum2D(a, 0, 0);
System.out.println("The sum of the array: " + sum);
}
public static int sum2D(int a[][], int row, int col) {
if (row == a.length-1) {
return a[row][col];
}
if (col == a[row].length-1) {
return a[row][col] + sum2D(a, row++, 0);
}
return a[row][col] + sum2D(a, row, col++);
}
}
The basic plan, when you need a recursive solution, is to look for a way to break down the problem so that it contains a smaller problem (or more than one smaller problem) that looks just like the original problem, only smaller.
For a 2-D array, this can be tricky. Say your array looks like
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
One's first thought might be to write a recursive function that takes a row and column, and adds a[row][column] to the sum of the rest of the array. The problem is that if, for example, row=0 and column=0, the "smaller problem" you have to solve looks like
+---------------------+
1 | 2 3 4 5 |
+---+ |
| 6 7 8 9 10 |
| 11 12 13 14 15 |
+-------------------------+
(please excuse the bad ASCII art). So now your smaller problem doesn't look like an array at all, but some weird polygon. It's still possible to use this approach, by writing a recursive function like
int sumOfWeirdShapedSectionOfArray(int[][] array, int firstRow, int firstCol)
But that's definitely an abuse of recursion. Better would be to break down the array into the "first row" and "the rest of the rows":
1 2 3 4 5
+-------------------------+
| 6 7 8 9 10 |
| 11 12 13 14 15 |
+-------------------------+
(Or you could break it into "the last row" and "the rest of the rows".)
Now, your smaller problem looks a lot like the original problem, right? So your answer would be that "the sum of the elements in the array is the sum of the first row, plus the sum of the elements in the smaller array starting with the next row". The second part of this is a recursive call. The first part, the sum of the first row, would require that you call a new function to add up a row; and since you're still not allowed to use loops, the "add up a row" function would also be recursive, but that should be easy.
Having said all this, nobody would ever use recursion in the real world on this problem. However, if the point is to get familiar with recursion so that you can use it when it's called for, then this sort of thought process is what you need to follow.
To do it without recursion, just have two nested for loops:
int sum = 0;
for(int i=0;i<array.length;i++)
for(int j=0;j<array[i].length;j++)
sum += array[i][j];
return sum;
To do it with recursion:
int sum2D(int a[][], int row, int col) {
if (row == a.length-1)
return a[row][col];
if(col == a[row].length-1)
return a[row][col]+sum2D(a,row+1,0);
return a[row][col]+sum2D(a,row,col+1);
}
Basically you're doing the same thing: going through each row and column and adding it together.
However, note that ther is a limit on how many recursive routines you can use. If you recurse too deep, you'll get a StackOverflow error.
The base condition was wrong in the above code:
Here is the code that works:
public static int addMatrix(int a[][],int r,int c){
if(r==a.length-1 && c==a[r].length-1)
return a[r][c];
if(c==a[r].length-1)
return a[r][c]+addMatrix(a,r+1,0);
return a[r][c]+addMatrix(a,r,c+1);
}
Equivalent "C" program here, but for number of Rows 4 and Number of columns 1 , I get unpredictable result why?
#include <stdio.h>
#include <string.h>
#include <conio.h>
int row,col;
main()
{
int a[][];
int nrow,ncols,summ = 0;
printf("Enter No of Rows:");
scanf("%d",&nrow);
printf("Enter No of Columns:");
scanf("%d",&ncols);
int arraylength,rowlength;
printf("Enter %d numbers: \n",nrow*ncols);
for (int i = 0; i < nrow; i++) {
for (int j = 0; j < ncols; j++) {
scanf("%d",&a[i][j]);
}
}
arraylength=sizeof(a)/sizeof(int);
summ = sum(a,0, 0,nrow,ncols);
printf("\n The sum of the array: %d ",summ);
getch();
}
int sum( int a[row][col],int row,int col,int RowLen,int ColLen)
{
if ((row == RowLen-1) && (col==(ColLen)-1)) {
return a[row][col];
}
if (col == (ColLen)-1)
{
return (a[row][col] + sum(a,row+1,0,RowLen,ColLen));
}
return (a[row][col] + sum(a,row, col+1,RowLen,ColLen));
}