I'm creating a program to create an Identity Matrix - which is pretty easy. But now I need to create the Identity Matrix, but backwards. The result needs to be like so:
0 0 1
0 1 0
1 0 0
Here is the program I'm using that is creating the Identity Matrix:
import java.util.*;
class Lab19Part2 {
public static int[][] create(int size) {
int[][] matrix = new int[size][size];
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
matrix[i][j] = (i == j) ? 1 : 0;
return matrix;
} public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter size of matrix: ");
int size=input.nextInt();
int matrix[][]=create(size);
for (int i=0 ; i < matrix.length ; i++) {
System.out.println();
for (int j=0 ; j < matrix[i].length ; j++){
System.out.print(matrix[i][j]+" ");
}
}
}
}
Though it prints out the Identity Matrix like so:
1 0 0
0 1 0
0 0 1
Question is, how do I make it so it prints out like the first Identity Matrix? I know it has something to do with the for loops but I can't pinpoint it.
Thanks!
You would need to change your condition that controls whether the value is 1 or 0:
matrix[i][j] = (i + j == size - 1) ? 1 : 0;
So that if size is 3, positions [0][2], [1][1], and [2][0] get 1's.
Change
matrix[i][j] = (i == j) ? 1 : 0;
to
matrix[i][j] = (i == size - j - 1) ? 1 : 0;
Why not do this for your identity case:
for(int i = 0; i < size; i++) {
matrix[i][i] = 1;
}
Then for the other case use:
for(int i = 0; i < size; i++) {
matrix[i][size - (i+1)] = 1;
}
Here is the brief example how to create it with la4j (Linear Algebra for Java):
Matrix a = new Basic2DMatrix(Matrices.asIdentitySource(3)).transpose();
// will create a 3x3 matrix
//
// 0 0 1
// 0 1 0
// 1 0 0
Related
code :
class test1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt(); // input number rows & colums
int twoD[][] = new int[a][];
int z;
for (z = 0 ; z < a ; z++) {
twoD[z] = new int[z + 1];
}
int i,j,k = 0;
for (i = 0 ; i < a ; i++) {
for (j = 0 ; j <= i ; j++){
twoD[i][j] = k;
k++;
}
for (i = 0 ; i < a ; i++ ) {
for (j = 0 ; j <= i ; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}
my expected output is ( for a = 4) :
0
1 2
3 4 5
6 7 8 9
my output is (for a = 4):
0
0 0
0 0 0
0 0 0 0
please help me fix my problem. according to me the lopping is correct. there might be mistake somewhere else...
The loop that prints the contents of the array is contained within the loop that is supposed to fill the 2D array with values. Since it uses the same variables, it interferes with the execution of the first loop. Move it out:
int i,j,k = 0;
for (i = 0 ; i < a ; i++) {
for (j = 0 ; j <= i ; j++){
twoD[i][j] = k;
k++;
}
}
for (i = 0 ; i < a ; i++ ) {
for (j = 0 ; j <= i ; j++){
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
You could have avoided this by
using and editor or IDE that automatically formats your code, so that is shows you how the control structures are nested
using common idioms like declaring the loop variables with the smallest necessary scope:
for (int i = 0 ; i < a ; i++)
I am newbie to Java. Here is my scenario,
I need to read the multiple square matrix at once and process the same elements of the matrix to find the inverse. I am able to process a single matrix. How can I convert this code to read multiple square matrices and produce the expected result.
import java.util.Scanner;
public class Matrix {
public static void main(String args[]) {
int i, j;
int determinant, temp;
int matrix[][] = new int[2][2];
Scanner sc = new Scanner(System.in);
for(i = 0; i < 2; ++i)
for(j = 0; j < 2; ++j)
matrix[i][j] = sc.nextInt();
System.out.print("\n");
determinant = (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]);
temp = matrix[0][0];
matrix[0][0] = matrix[1][1];
matrix[1][1] = temp;
matrix[0][1] = - matrix[0][1];
matrix[1][0] = - matrix[1][0];
System.out.println("\nMatrix 1:");
for(i = 0; i < 2; ++i) {
for(j = 0; j < 2; ++j) {
System.out.print((matrix[i][j]/determinant) + " ");
}
System.out.print("\n");
}
}
}
I am able to read and process the single input.
Input:
------
1 0
0 1
3 7
1 4
output:
------
Matrix 1:
1 0
0 1
Matrix2:
0 -1
0 0
I have been working on Magic Square formation, after reading through the algo, I found out there are certain set of rules to be followed while forming the MagicSquare.
The algo which I'm following is :
The magic constant will always be equal to n(n^2 + 1)/2, where n is the dimension given.
Numbers which magicSquare consists will always be equals 1 to n*n.
For the first element that is 1, will always be in the position (n/2, n-1).
Other elements will be placed like (i--,j++)
The condition to be put through for placing an elements are :
a) If i < 0, then i = n-1.
b) If j == n, then j = 0.
c) This is a special case, if i < 0 and j=n happens at the same time, then i = 0, j = n-2.
d) If the position is already occupied by some other element, then i++, j = j-2.
Then input the element inside the magicSquare based upon the conditions.
Based upon the above algo, I have written down a code, and due to some reason I'm getting
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at Main.generateMagicSquare(Main.java:25)
at Main.main(Main.java:58)
This is weird. I have checked, and feels like it is safe to use the code to get the desired result, but I don't know where I'm going wrong.
Code
static void generateMagicSquare(int n){
int[][] magicSquare = new int[n][n];
//initialising for pos of the elem 1
int i = n/2, j = n-1;
magicSquare[i][j] = 1;
//the element consist by the magic square will always be equal to 1 to n*n
for(int num=2; num <= n*n; num++){
//it must go like this, for any other element
i--; j++;
// if the element is already present
if(magicSquare[i][j] != 0){
i++;
j -= 2;
}else{
if(i < 0)
i = n-1;
if(j == n)
j = 0;
if(i < 0 && j == n){
i = 0;
j = n-2;
}
}
magicSquare[i][j] = num;
}
for(int k=0; k<n; k++){
for(int l=0; l<n; l++){
System.out.print(magicSquare[k][l] + " ");
}
System.out.println();
}
}
Any help would be appreciated. Thanks. Since I could have copied and pasted the code from internet, but I want to learn it in my way, and your help would help me achieve what I want. :)
EDITS
After reading through the exception, I made some amendments in my code, but still some of the result didn't come upto the mark.
Here is my updated code =======>
static void generateMagicSquare(int n){
int[][] magicSquare = new int[n][n];
//initialising for pos of the elem 1
int i = n/2, j = n-1;
magicSquare[i][j] = 1;
//the element consist by the magic square will always be equal to 1 to n*n
for(int num=2; num <= n*n; num++){
//it must go like this, for any other element
i--; j++;
if(i < 0){
i = n-1;
}
if(j == n){
j = 0;
}
if(i < 0 && j == n){
i = 0;
j = n-2;
}
if(magicSquare[i][j] != 0){
i++;
j -= 2;
}else{
magicSquare[i][j] = num;
}
}
for(int k=0; k<n; k++){
for(int l=0; l<n; l++){
System.out.print(magicSquare[k][l] + " ");
}
System.out.println();
}
}
I get this output :
2 0 6
9 5 1
7 3 0
Still not the right answer to follow.
This line throws the error:
if(magicSquare[i][j] != 0)
and the problem is that the array magicSquare is initialized as:
int[][] magicSquare = new int[n][n];
meaning that it has n columns with indexes from 0 to n - 1 (indexes are zero based).
The variable j is initialized as
j = n-1;
and later this line:
j++;
makes j equal to n
so when you access magicSquare[i][j] you are trying to access magicSquare[i][n] which does not exist.
The index of an array is an integer value that has value in interval [0, n-1], where n is the size of the array. If a request for a negative or an index greater than or equal to size of array is made, then the JAVA throws a ArrayIndexOutOfBounds Exception. You have to check the value of i and j before using it in array. You can use the below code :
for(int num=2; num <= n*n; num++){
i--; j++;
//Here We have to check the value of i and j i.e. it should less than or equal to the length of array.
if((i <= magicSquare[0].length-1 && j <= magicSquare[0].length-1))
{
if(magicSquare[i][j] != 0){
i++;
j -= 2;
}else{
if(i < 0)
i = n-1;
if(j == n)
j = 0;
if(i < 0 && j == n){
i = 0;
j = n-2;
}
}
magicSquare[i][j] = num;
}
}
For understanding ArrayIndexOutOfBoundsException, Please visit :
https://www.geeksforgeeks.org/understanding-array-indexoutofbounds-exception-in-java/
I am trying to find the counts for negative numbers in a 2d-array ( square- matix). In matrix if you go from up to down and left to write number increases. Logic here is to start from last column and proceed to the left. If you find the neg num then increase the row index and proceed the same way till the last row. I am getting the error in java code but not in python.
public class O_n
{
public static void main(String[] args)
{
int firstarray[][] = {{-2,-1,0},{-1,0,1},{0,1,2}};
int secondarray[][] = {{-4,-3,-2},{-3,-2,-1},{-2,-1,0}};
System.out.print ("First array has"+count_neg(firstarray));
System.out.println("negative numbers");
System.out.print ("Second array has"+count_neg(secondarray));
System.out.println("negative numbers");
}
public static int count_neg(int x[][]){
int count = 0;
int i = 0; //rows
int j = x.length - 1; //columns
System.out.println("max column index is: "+j);
while ( i >=0 && j<x.length){
if (x[i][j] < 0){ // negative number
count += (j + 1);// since j is an index...so j + 1
i += 1;
}
else { // positive number
j -= 1;
}
}
return (count);
}
}
I am getting this output
max column index is: 2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at O_n.count_neg(O_n.java:22)
at O_n.main(O_n.java:9)
/home/eos/.cache/netbeans/8.1/executor-snippets/run.xml:53: Java
returned: 1
BUILD FAILED (total time: 0 seconds)
What is wrong with this code? the same thing worked in python...
def count_neg(array):
count = 0
i = 0 # row
j = len(array) -1 # col
# since we are starting from right side
while j >= 0 and i < len(array):
if array[i][j] < 0:
count += (j + 1)
i += 1
else:
j -= 1
return count
print(count_neg([[-4,-3,-1,1],[-2,-2,1,2],[-1,1,2,3],[1,2,4,5]]))
I would write the method like this, just go through the 2d array and increase count each time a negative number is found
public static int count_neg(int x[][]){
int count = 0;
for(int i = 0; i < x.length; i++){
for(int j = 0; j < x[i].length; j++){
if(x[i][j] < 0){
count++;
}
}
}
return (count);
}
Your indexes are reversed from the python version:
while j >= 0 and i < len(array)
To the Java version:
while (i >= 0 && j < x.length)
// Change to
while (j >= 0 && i < x.length)
Output:
max column index is: 2
3
If you are using Java8, you can use streams to implement count_neg:
public static int countNeg(int x[][]) {
long count = Stream.of(x)
.flatMapToInt(arr -> IntStream.of(arr))
.filter(i -> i < 0)
.count();
return Math.toIntExact(count);
}
First of all your algorithm don't find the count of negative numbers.
Here are the results of the python code:
print(count_neg([[1, 1, -1],[1, 1, -1],[1, 1, -1]])) result - 9
print(count_neg([[1, 1, -1],[1, 1, 1],[1, 1, 1]])) result - 3
So the provided code finds sum of column indexes + 1 for some negative numbers, not all. And for your test arrays it's return pseudo correct counts.
To find the count of negative numbers in a two-dimentional array you just have to get each number, check if the one is less than zero and increase the counter by one if it's true. So it's impossible to get the correct result with complexity better than O(n2).
Here the correct code in Java of doing that:
public static int count_neg(int x[][]){
int count = 0;
for(int i = 0; i < x.length; i++){
for(int j = 0; j < x[i].length; j++){
if(x[i][j] < 0) count++;
}
}
return count;
}
Here a small change in the algorithms to produce correct result with columns which don't contain negative numbers:
while j >= 0 and i < len(array):
if array[i][j] < 0:
count += (j + 1)
i += 1
else:
j -= 1
if j < 0:
i += 1
j = len(array) - 1
You can test it with the following array [[1,2,4,5],[-2,-2,1,2],[-1,1,2,3],[1,2,4,5]]
I need to build a code that bubble sort 2D array. The trick here is that I cannot use an one dimensional array helper, or move the items to another array.
The sorting need to be on the 2D array.
Now I built my function. But something is going wrong. This is my output
1 1 2 6 12 32
49 44 54 55 100 344
is to close to be done, and I cant think how to do it.
public static int [] [] sortMatrix(int[][]matrix){
for(int x = matrix.length ; x >0 ; x-- ){
for(int i = matrix[0].length ; i > 0 ; i-- ){
for(int j = 0 ; j < x ; j++){
for(int t = 0 ;t < i ; t++){
if(t < matrix[0].length - 1 && matrix[j][t] > matrix[j][t+1] ){
swap(matrix , j , t, t+1);
}
else if(t == matrix[0].length - 1 && j != matrix.length -1&& matrix[j][t] > matrix[j+1][0] ){
swap1(matrix ,j , t , j + 1);
}
}
}
}
}
Try
public static int [] [] sortMatrix(int[][]matrix){
// for loop of matrix rows: -
for(int x = 0 ; x < matrix.length; x++){
// for loop of matrix columens: -
for(int i =0; i < matrix[x].length; i++){
// for loop of comparison and swapping
for(int t = 0; t < matrix[x].length - i - 1; t++){
if(matrix[x][t] > matrix[x][t+1]){
// Swapping operation: -
int temp = matrix[x][t];
matrix[x][t] = matrix[x][t+1];
matrix[x][t+1] = temp;
}
}
}
}
return matrix;
}
instead of
public static int [] [] sortMatrix(int[][]matrix){
for(int x = matrix.length ; x >0 ; x-- ){
for(int i = matrix[0].length ; i > 0 ; i-- ){
for(int j = 0 ; j < x ; j++){
for(int t = 0 ;t < i ; t++){
if(t < matrix[0].length - 1 && matrix[j][t] > matrix[j][t+1] ){
swap(matrix , j , t, t+1);
}
else if(t == matrix[0].length - 1 && j != matrix.length -1&& matrix[j][t] > matrix[j+1][0] ){
swap1(matrix ,j , t , j + 1);
}
}
}
}
}
Below is the code for sorting 2D array, trick is that you have to think of the 2D array as one dimensional array and then derive the appropriate row, offset pairs for indices.
import java.util.Arrays;
public class Bubble2DSort {
public static void main(String[] args) {
System.out.println("Started");
int[][] matrix = {{49,44,54,55,100,344}, {1,1,2,6,12,32}};
sortMatrix(matrix);
System.out.println("Printing output ");
for(int[] rowArr : matrix) {
System.out.println(Arrays.toString(rowArr));
}
}
private static void sortMatrix(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
int totalCount = row * col;
System.out.println("totalCount : " +totalCount);
boolean noSwaps = false;
for(int i = 0; !noSwaps; i++) {
noSwaps = true;
for(int j = 1; j < totalCount - i; j++) {
int currentRow = (j-1) / col;
int currentOffset = (j-1) % col;
int nextRow = j / col;
int nextOffset = j % col;
if( matrix[currentRow][currentOffset] > matrix[nextRow][nextOffset]) {
//swapping
int temp = matrix[nextRow][nextOffset];
matrix[nextRow][nextOffset] = matrix[currentRow][currentOffset];
matrix[currentRow][currentOffset] = temp;
noSwaps = false;
}
}
}
}
}
Output:
Started
totalCount : 12
Printing output
[1, 1, 2, 6, 12, 32]
[44, 49, 54, 55, 100, 344]