I'm currently trying to figure out how to redifine my toString method so that it will display the matrix. Here's the code..
import java.util.Random;
public class TextLab09st
{
public static void main(String args[])
{
System.out.println("TextLab09\n\n");
Matrix m1 = new Matrix(3,4,1234);
Matrix m2 = new Matrix(3,4,1234);
Matrix m3 = new Matrix(3,4,4321);
System.out.println("Matrix m1\n");
System.out.println(m1+"\n\n");
System.out.println("Matrix m2\n");
System.out.println(m2+"\n\n");
System.out.println("Matrix m3\n");
System.out.println(m3+"\n\n");
if (m1.equals(m2))
System.out.println("m1 is equal to m2\n");
else
System.out.println("m1 is not equal to m2\n");
if (m1.equals(m3))
System.out.println("m1 is equal to m3\n");
else
System.out.println("m1 is not equal to m3\n");
}
}
class Matrix
{
private int rows;
private int cols;
private int mat[][];
public Matrix(int rows, int cols, int seed)
{
this.rows = rows;
this.cols = cols;
mat = new int[rows][cols];
Random rnd = new Random(seed);
for (int r = 0; r < rows; r ++)
for (int c = 0; c < cols; c++)
{
int randomInt = rnd.nextInt(90) + 10;
mat[r][c] = randomInt;
}
}
public String toString()
{
return ("[" + mat + "]");
}
public boolean equals(Matrix that)
{
return this.rows == (that.rows)&&this.cols == that.cols;
}
}
I know how to display it and how to redifine the equals method, I feel like it's just late and I'm missing something silly. Sorry for any inconvience!
EDIT: Sorry, I forgot to specify that it had to be shown as a 2 dimensional row x column display.
EDIT2: Now I'm having trouble redefining the equals method, as it is required for my assignment. I rewrote it to this:
public boolean equals(Matrix that)
{
return this.mat == that.mat;
}
and it still outputs:
m1 is not equal to m2
m1 is not equal to m3
Is there any easy way to fix this?
You'd have to make a nested loop for each cell in your matrix.
public String toString()
{
String str = "";
for (int i = 0 ; i<this.rows ; i ++ ){
for (int j = 0 ; j < this.cols ; j++){
str += mat[i][j]+"\t";
}
str += "\n";
}
return str;
}
As for the "equal" method, I'm not quite sure what is the criteria.
Does your application consider two matrixes to be equal if they both have the same number of rows and cols?
P.S.
Overriding the equal method is a very good practice, but it is a better practice to override the "hashCode" method as well.
Might not be relevant to your app, but it is important.
Hope that would help :)
Use Arrays.deepToString:
public String toString()
{
return Arrays.deepToString(mat);
}
Related
I have two 2d boolean arrays, the smaller array (shape) is going over the larger array (world).
I am having trouble to find a method to find out when the smaller array can "fit" into the larger one.
When I run the code it either just goes through the larger array, never stopping, or stops after one step (incorrectly).
public void solve() {
ArrayList<Boolean> worldList=new ArrayList<>();
ArrayList<Boolean> shapeList=new ArrayList<>();
for (int i = 0; i < world.length; i++) {
for (int k = 0; k < world[i].length; k++) {
worldList.add(world[i][k]);
display(i, k, Orientation.ROTATE_NONE);
for (int j = 0; j < shape.length; j++) {
for (int l = 0; l < shape[j].length; l++) {
shapeList.add(shape[j][l]);
if(shapeList.equals(worldList)) {
return;
}
}
}
}
}
}
A good place to start with a problem like this is brute force for the simplest case. So, for each index in the world list, just check to see if every following index of world and shapes match.
Notice we only iterate to world.size()-shapes.size(), because naturally if shapes is longer than the portion of world we haven't checked, it won't fit.
import java.util.ArrayList;
public class Test {
ArrayList<Boolean> world = new ArrayList<>();
ArrayList<Boolean> shapes = new ArrayList<>();
public static void main(String[] args) {
new Work();
}
public Test() {
world.add(true);
world.add(false);
world.add(false);
world.add(true);
shapes.add(false);
shapes.add(true);
// Arraylists initialized to these values:
// world: T F F T
// shapes: F T
System.out.println(getFitIndex());
}
/**
* Get the index of the fit, -1 if it won't fit.
* #return
*/
public int getFitIndex() {
for (int w = 0; w <= world.size()-shapes.size(); w++) {
boolean fits = true;
for (int s = 0; s < shapes.size(); s++) {
System.out.println("Compare shapes[" + s + "] and world["+ (w+s) + "]: " +
shapes.get(s).equals(world.get(w+s)));
if (!shapes.get(s).equals(world.get(w+s))) fits = false;
}
System.out.println();
if (fits) return w;
}
return -1;
}
}
When we run this code, we get a value of 2 printed to the console, since shapes does indeed fit inside world, starting at world[2].
You can find the row and column of fitting like this
public void fit() {
int h = world.length - shape.length;
int w = world[0].length - shape[0].length;
for (int i = 0; i <= h; i++) {
for (int k = 0; k <= w; k++) {
boolean found = true;
for (int j = 0; j < shape.length && found; j++) {
for (int l = 0; l < shape[j].length && found; l++) {
if (shape[j][l] != world[i + j][k + l])
found = false;
}
}
if (found) {
//Your shape list fit the world list at starting index (i, k)
//You can for example save the i, k variable in instance variable
//Or return then as an object for further use
return;
}
}
}
Currently I'm trying to implement a way to be able to use vector- and matrix-multiplication in java, right now I have the code:
package ai2;
public class MyMatrix {
int[][] alpha;
int a;
int b;
int rowsB;
int colsB;
public MyMatrix(int a, int b) {
this.a = a;
this.b = b;
alpha = new int[a][b];
for (int k = 0; k < a; k++) {
for (int l = 0; l < b; l++) {
alpha[k][l] = 0;
}
}
}
public void insertValue(int o, int q, int z) {
this.alpha[o][q] = z;
}
public void print() {
for (int k = 0; k < a; k++) {
for (int l = 0; l < b; l++) {
System.out.print(this.alpha[k][l] + " ");
}
System.out.println();
}
}
public void multiplyMatrix(MyMatrix B) {
MyMatrix created = new MyMatrix(this.a, B.b);
for (int m = 0; m < a; m++) {
for (int k = 0; k < b; k++) {
for (int l = 0; k < this.a; l++) {
myMatrixC[i][j] += myMatrixA[i][k] * myMatrixB[k][j];
}
}
}
}
public static void main(String[] args) {
MyMatrix a = new MyMatrix(2, 2);
a.insertValue(0, 0, 1);
a.insertValue(1, 1, 1);
a.print();
MyMatrix b = new MyMatrix(2, 2);
b.insertValue(0, 0, 1);
b.insertValue(1, 0, 1);
// System.out.println(a);
}
}
The problem is my multiplyMatrix method, it takes a MyMatrix object but I cant reach the values using for example:
MyMatrixA[k][l]
I need some sort of idea to reach those values or perhaps a smarter implementation, I cannot use packages outside of java, thankful for any help!
Square brackets in Java are only for accessing array elements.
Your syntax there will not compile, and you cannot access your matrix elements that way.
Why don't you just implement a getAlpha getter in your MyMatrix class that returns the value for alpha (or better, a copy thereof, to ensure immutability)?
You could then reference it with theMatrixInstance.getAlpha()[k][l].
You could also simplify a bit and implement a get method taking two indices.
That would allow you to check whether the given indices are within the bounds of your two-dimensional array and throw a custom exception (or return some default value) rather than the ArrayIndexOutOfBoundsException you'd otherwise get.
Replace this line
myMatrixC[i][j] += myMatrixA[i][k] * myMatrixB[k][j];
with
created.alpha[i][j] += this.alpha[i][k] * B.alpha[k][j];
Or better yet, replace
MyMatrix created = new MyMatrix(this.a, B.b);
with
MyMatrix A = this;
MyMatrix C = new MyMatrix(this.a, B.b);
then you can do
C.alpha[i][j] += A.alpha[i][k] * B.alpha[k][j];
Which reads a little more clearly.
Finally, no need to initialize alpha with 0's in your constructor, this happens automatically.
So I need to make a diamond_look of numbers using 2D array in Java. I got my results but with null before the diamond. For drawNumDiamond(9) I have to get a diamond look that goes until 5 and back. I know I can make it without using array, but I want to learn more about 2D arrays :this is how it should look like and what are my results
public class Example1{
private static void drawNumDiamond(int h) {
if(h%2 != 0) {
int size = h/2 +1;
int count = 1;
int loop = 1;
String[][] dijamant = new String[h][];
for(int row = 0; row < dijamant.length; row++) {
dijamant[row] = new String[row+1];
for(int kolona=0; kolona<=row; kolona++) {
dijamant[0][0] = "1";
for(int i=0; i< loop;i++) {
dijamant[row][kolona]+= count;
}
}
count++;
loop+=2;
}
for (int k = 0; k < size; k++) {
System.out.printf("%" + h + "s", dijamant[k]);
h++;
System.out.println();
}
h--;
for (int q = size - 2; q>=0; q--) {
h--;
System.out.printf("%" + h + "s", dijamant[q]);
System.out.println();
}
}
}
public static void main(String[] args) {
drawNumDiamond(9);
}
}
The issue is in this line :
dijamant[row][kolona] += count;
if dijamant[row][kolona] is null and count is 2, the result of the string concatenation will be "null2". Try adding the following if statement before to initialize with an empty string :
if (dijamant[row][kolona] == null) {
dijamant[row][kolona] = "";
}
This will get your code working, but there are still things to think about. E.g. you keep setting dijamant[0][0] = "1"; in the loop.
I am supposed to write a method that accepts 3 2-D arrays of This method should determine whether one of the matrices is the result of matrix addition of the other two.
public class Matrix {
public static void main(String[]args){
int [][] a = {{5,2,3},{4,1,6},{0,7,2}};
int [][] b = {{1,2,3},{4,5,6},{0,1,2}};
int [][] t = {{6,4,6},{8,6,12},{0,8,4}};
System.out.println(add(a,b));
System.out.println(check(a,b,t));
}
public static int [][] add(int[][]a,int[][]b){
int i=0;
int j=0;
int[][] r = new int [3][3];
while (i<a.length){
r[i][j] = a[i][j] + b[i][j];
i++;
j++;
}
return r;
}
public static boolean check(int[][]a,int[][]b,int[][]t){
int i = 0;
int j = 0;
while(i<t.length){
if(t==add(a,b))
return true;
}
return false;
}
}
add returns an array. Arrays in Java are objects, but they do not override the toString() method. When printing, you'd print their default toString() call, which is implemented by Object as return getClass().getName() + "#" + Integer.toHexString(hashCode());.
Luckily, Java provides a utility in the form of java.util.Arrays.deepToString(Ojbect[]) to generate a more readable string output:
System.out.println(Arrays.deepToString(add(a,b)));
EDIT:
Your add method is also wrong. Your code iterates i and j together, so it only sums the elements along the matrix's diagonal instead of adding all of them. You should use a nested loop instead:
public static int [][] add(int[][]a, int[][]b) {
int[][] r = new int [3][3];
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
r[i][j] = a[i][j] + b[i][j];
}
}
return r;
}
Your check method, by the way, is also wrong - it attempts to compare the array itself instead of is elements:
public static boolean check(int[][]a, int[][]b, int[][]t) {
int[][] r = add(a, b);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (r[i][j] != t[i][j]) {
return false;
}
}
}
return true;
}
I am working on writing a matrix, but unfortunately I am stuck with the output.
Instead of showing a matrix, it shows me something like:
actual matrix is
Matrix#512fb063
I need to convert the matrix to a string so that the output will look like this:
expected the matrix:
3 8 72
4 6 60
253 2 1
the code that I've written is this:
import java.util.Random;
final public class Matrix {
private final int size1; // number of rows
private final int size2; // number of columns
private final int[][] data; // M-by-N array
// create size1-by-size2 matrix of 0's
public Matrix(int size1, int size2) {
this.size1 = size1;
this.size2 = size2;
data = new int[size1][size2];
}
// create matrix based on 2d array
public Matrix(int[][] data) {
size1 = data.length;
size2 = data[0].length;
this.data = new int[size1][size2];
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
this.data[i][j] = data[i][j];
}
// creates and returns a random size1-by-size1 matrix with values between 0 and 255
public String toString(int size1, int size2) {
Matrix A = new Matrix(size1, size2);
String str = " ";
final int white = 0;
final int black = 255;
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
{
A.data[i][j] = white + (int)(Math.random() * ((black ) ));
str = (A.data[i][j]+"\t"+A.data[i][j+1]);
if (i==size1 &&j==size2) str = (A.data[i][j]+"\n");
}
return str;
}
You need to override the public String toString() function. What you are doing now is creating a new function called String toString(int size1, int size2).
Your new function is not called when writing:
System.out.println(myMatrix);
You could either do:
System.out.println(myMatrix.toString(2, 2));
or override the default toString() function.
So the following code should work:
#Override
public String toString() {
Matrix A = new Matrix(size1, size2);
String str = " ";
final int white = 0;
final int black = 255;
for (int i = 0; i < size1; i++)
for (int j = 0; j < size2; j++)
{
A.data[i][j] = white + (int)(Math.random() * ((black ) ));
str = (A.data[i][j]+"\t"+A.data[i][j+1]);
if (i==size1 &&j==size2) str = (A.data[i][j]+"\n");
}
return str;
}
where size1 and size2 are variables in the class.
Your output of actual matrix is Matrix#512fb063 is actually the memory address in Java that your instance of the class Matrix sits in. That's because your program doesn't know how to "print" this class - it doesn't magically know that you want a row/column representation of it.
You've got a number of options:
Your toString(int size1, int size2) is perfect. So when you want to print your matrix, you can go System.out.println(someMatrix.toString(2,2)) will work where someMatrix is an instance of your Matrix class.
If you want it to work properly by you just going System.out.println(someMatrix) then you will need to overwrite your Matrix class' toString() function. You -almost- did that in your toString(int size1, int size2) function but it didn't work because it needs to match exactly the parameters, ie: toString() should take 0 parameters. You will need to write a toString() method which can then call your toString(int size1, int size2)
Somehow you get the hashcode. Maybe you can use http://math.nist.gov/javanumerics/jama/doc/ matrix implementation.
I think this line is not working
str = (A.data[i][j]+"\t"+A.data[i][j+1]);
Don't you get an IndexOutOfBoundexception? Anyway A.data[i][j+1] is always empty within the loop. By the way, Variables in Java are always lower case.
You can simply do :
#Override
public String toString()
{
return toString(size1,size2);
}
Edit : If you want to reflect the real content of your current Matrix :
#Override
public String toString()
{
StringBuilder sbResult = new StringBuilder();
for(int i = 0; i < size1;i++)
{
for(int j = 0; j < size2;j++)
{
sbResult.append(A.data[i][j]);
sbResult.append("\t");
sbResult.append(A.data[i][j+1]);
if(i == size1 && j == size2)
{
sbResult.append("\n");
}
}
}
return sbResult.toString();
}