Printing two 2D Arrays Next to Each Other - java

So I've been fiddling around with 2D arrays in java. I am practicing by using the arrays as matrices. I create 2 Matrix objects, which have a myMatrix 2D array field. In the main method, I call the first Matrix object to add itself to the second matrix if it is possible, through the addMatrix method. I have a printResultDetail method to actually print out what is happening. I want the first object's myMatrix to print out with rows and columns properly formatted. Then I want the second object's myMatrix object to print out on the right of the previous. I then want the new output matrix, given by the first object's myResultMatrix 2D array, to printed out again to the right.
How do I make the arrays print out side by side?
Note: the printResultDetail is incorrect. I was just trying to figure out how to do it.
import java.util.Arrays;
import java.util.Random;
public class Matrix {
int[][] myMatrix;
int[][] myResultMatrix;
int myMatrixRow;
int myMatrixCol;
Random rand = new Random();
public Matrix(int rowSize, int colSize, int maxVal, int minVal){
myMatrixRow = rowSize;
myMatrixCol = colSize;
myMatrix = new int[rowSize][colSize];
for(int i = 0; i < rowSize; i++){
for(int k = 0; k < colSize; k++){
myMatrix[i][k] = rand.nextInt((maxVal - minVal) + 1) + minVal; //assigns each part of array to rand #
}
}
for(int i = 0; i<myMatrixRow; i++){
System.out.print("[");
for(int j = 0; j<myMatrixCol; j++){
System.out.print(" " + myMatrix[i][j] + " ");
}
System.out.print("]");
System.out.println();
}
//System.out.println(Arrays.deepToString(myMatrix));
}
public int[][] multMatrix(Matrix matrix2){
if(canMultiply(matrix2) == true){
myResultMatrix = new int[myMatrixRow][matrix2.myMatrixCol];
for (int i = 0; i < myMatrixRow; i++) {
for (int j = 0; j < matrix2.myMatrixCol; j++) {
for (int k = 0; k < myMatrixCol; k++) {
myResultMatrix[i][j] += myMatrix[i][k] * matrix2.myMatrix[k][j];
}
}
}
return myResultMatrix;
}else{
myResultMatrix = null;
return null;
}
}
public boolean canMultiply(Matrix matrix2){ //can only multiply if the columns of
//first matrix is equal to the rows of the second
if(myMatrixCol == matrix2.myMatrixRow){
return true;
}else{
return false;
}
}
public int[][] addMatrix(Matrix matrix2){
if(myMatrixRow == matrix2.myMatrixRow && myMatrixCol == matrix2.myMatrixCol){
myResultMatrix = new int[myMatrixRow][myMatrixCol];
for(int i = 0; i < myMatrixRow; i++){
for(int k = 0; k < myMatrixCol; k++){
myResultMatrix[i][k] = myMatrix[i][k] + matrix2.myMatrix[i][k];
}
}
return myResultMatrix;
}else{
myResultMatrix = null;
return null;
}
}
public void printResultDetail(Matrix matrix2){
for(int i = 0; i<myMatrixRow; i++){
System.out.print("[");
for(int j = 0; j<myMatrixCol; j++){
System.out.print(" " + myMatrix[i][j] + " ");
}
System.out.print("] ");
System.out.println();
for(int k = 0; k<matrix2.myMatrixRow; k++){
System.out.print("[");
for(int x = 0; x<matrix2.myMatrixCol; x++){
System.out.print(" " + matrix2.myMatrix[k][x] + " ");
}
System.out.print("]");
}
}
}
public static void main(String[] args){
Matrix firstMatrix = new Matrix(3, 3, 5, 1);
Matrix secondMatrix = new Matrix(3, 3, 5, 1);
System.out.println(Arrays.deepToString(firstMatrix.addMatrix(secondMatrix)));
//System.out.println(Arrays.deepToString(firstMatrix.addMatrix(secondMatrix)));
}
}

This code below will print:
maybe you can use as sample.
public class Test {
public static void main(String[] args) {
double[][] matrixLeft = {{1,5,2,8,4,70,55,80},{3,7,4,2,6,60,30,70}};
double[][] matrixRight = {{8,1,6,4,2,10,40,60},{1,5,2,8,4,70,50,80},{3,7,4,2,6,60,30,70}};
int endOfLoop = matrixLeft.length > matrixRight.length ? matrixLeft.length : matrixRight.length;
for(int i = 0; i < endOfLoop; i++){
if(matrixLeft.length > i){
printLine(matrixLeft[i]);
System.out.print(" ");
} else {
printBlankLine(matrixLeft[0].length);
}
if(matrixRight.length > i){
printLine(matrixRight[i]);
}
System.out.println();
}
}
private static void printLine(double[] line){
for(double number : line){
System.out.print(number + " ");
}
}
private static void printBlankLine(int lenght){
for(int i=0; i < lenght; i++){
System.out.print(" ");
}
}
}

Related

How can I check if every single int in a randomly generated array is even and make it create another random array if it's not?

So I'm trying to create a program that creates a randomly generated array with numbers between 0 and 10.
Every time a number inside the 4x4 array is odd I want it to generate a brand new array and print every array discarded aswell until it creates a 4x4 array with only even numbers.
The problem right now is that I can't understand how to fix the last for and make it work properly with the boolean b that is supposed to restart the creation of the array.
import java.util.Scanner;
public class EvenArrayGenerator {
public static void main(String a[]) {
Boolean b;
do {
b = true;
int[][] Array = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
Array[i][j] = (int) (Math.random() * 11);
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (Array[i][j] % 2 != 0)
b = false;
}
}
} while (b);
}
}
public class ArrayGen {
private int[][] array = new int[4][4];
private int iterations = 1; // you always start with one iteration
public static void main (String[] args) {
ArrayGen ag = new ArrayGen();
ag.reScramble();
while(!ag.isAllEven()) {
ag.reScramble();
ag.iterations++;
}
// this is just a nice visualisation
for (int i = 0; i < 4; i++) {
System.out.print("[");
for (int j = 0; j < 4; j++) {
System.out.print(ag.array[i][j] +((j != 3)? ", " : ""));
}
System.out.print("]\n");
}
System.out.println(ag.iterations + " iterations needed to get all-even array.");
}
private void reScramble () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = (int)(Math.random() * 11);
}
}
}
private boolean isAllEven () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (array[i][j] % 2 == 1) {
return false;
}
}
}
return true;
}
}
I think this is a good solution. Refactoring your code into structured methods is never a bad idea. I hope this helps!
You are looping until you get an array that's all even. You should initialize b to be false, and update it to true in the (nested) for loop. Note that once's you've set it to false, there's no reason checking the other members of the array, and you can break out of the for loop.
Note, also, that using stream could make this check a tad more elegant:
b = Arrays.stream(arr).flatMapToInt(Arrays::stream).anyMatch(x -> x % 2 != 0)
What about generating random numbers up to 5 and double it? Then you don't have two check if they are even.
Instead of your last for loop:
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(Array[i][j] % 2!=0){
b=false;
break;
}
}
if(!b){
break;
}
}
if(!b){
break;
}
Alternatively, you could do an oddity check when you are generating the elements. Something like:
int element;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
do{
element = (int)(Math.random()*11);
}while(element % 2 !=0)
Array[i][j] = element;
}
}
That way you don't have to check the values, they will always be even.
This should work:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
anyOdd |= Array[i][j] % 2!=0;
}
}
} while(anyOdd);
}
}
As you can see, I just modified the condition from b to anyOdd, so if there is any odd number, it will iterate again.
Also, you can check it when you generate the random numbers, so you avoid a second loop:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
anyOdd |= array[i][j] % 2 != 0;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
} while(anyOdd);
}
}
public class EvenArrayGenerator {
public static void main(String a[]) {
int[][] arr = createAllEvenArray(4);
printArray(arr);
}
private static int[][] createAllEvenArray(int size) {
while (true) {
int[][] arr = createArray(size);
printArray(arr);
if (isAllEven(arr))
return arr;
}
}
private static int[][] createArray(int size) {
int[][] arr = new int[size][size];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
arr[i][j] = (int)(Math.random() * 11);
return arr;
}
private static void printArray(int[][] arr) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j > 0)
System.out.print("\t");
System.out.format("%2d", arr[i][j]);
}
System.out.println();
}
System.out.println();
}
private static boolean isAllEven(int[][] arr) {
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
if (arr[i][j] % 2 != 0)
return false;
return true;
}
}

ArrayIndexOutOfBoundsException when trying to find the determinant of a 2D Array/Matrix

this is my first Stack Overflow post, and I am fairly new to java, so I may not initially comprehend some of the feedback you give me.
With this program, I am supposed to find the determinant of a matrix recursively with a size determined by the user. When I do so, however, I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at Determinant.Copy<Determinant.java:55>
at Determinant.det<Determinant.java:31>
at Determinant.main<Determinant.java:15>
I understand what this error means, but I don't understand why it's happening.
Here are the classes I am using (both printmatrix and the main method were written by my teacher, I had to complete the Copy and det methods):
import javax.swing.JOptionPane;
public class Determinant
{
public static void main(String args[])
{
String sizeStr = JOptionPane.showInputDialog("What size?");
int size = Integer.parseInt(sizeStr);
int[][] matrix = new int[size][size];
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
matrix[i][j] = (int)(Math.random()*40)-20;
printArray(matrix);
System.out.println("\nThe determinant = "+det(matrix));
}
public static int det(int[][] A)
{
int answer = 0;
int place = 0;
int[][] temp;
int[][] temp1;
if(A.length==1){
return(A[0][0]);
}
for(int i = 0; i<A.length; i++){
temp = new int[A.length-1][A[0].length-1];
temp1 = Copy(temp, i);
if(i%2==0){
place = 1;
}
else{
place = -1;
}
answer = answer + place * A[0][i] * det(temp1);
}
return answer;
}
public static int[][] Copy(int[][] B, int i)
{
int[][] C = new int[B.length-1][B.length-1];
for(int j = 1; j<B.length; j++){
for(int k = 0; k<B[0].length; k++){
if(k>i){
C[j-1][k-1]=B[j][k];
}
else{
C[j-1][k]=B[j][k];
}
}
}
return C;
}
public static void printArray(int[][] A)
{
for(int i=0; i<A.length; i++)
{
for(int j=0; j<A.length; j++)
{
int num = A[i][j];
if(num<-9)
System.out.print(" ");
else if(num<0||num>9)
System.out.print(" ");
else
System.out.print(" ");
System.out.print(A[i][j]);
}
System.out.println();
}
}
}
The error occurs at the else statement in Copy and temp1 = Copy(temp, i).
I am confused, as if either j or k = 1, shouldn't that be a position in the array? What am I missing?
The size of C array in method copy, should be same as B array.
Reason: You are copying B array into C array, they should have same size.
Try the following:
import javax.swing.JOptionPane;
public class Determinant
{
public static void main(String args[])
{
String sizeStr = JOptionPane.showInputDialog("What size?");
int size = Integer.parseInt(sizeStr);
int[][] matrix = new int[size][size];
for(int i=0; i<size; i++) {
for(int j=0; j<size; j++) {
matrix[i][j] = (int) (Math.random() * 40) - 20;
}
}
printArray(matrix);
System.out.println("\nThe determinant = "+det(matrix));
}
public static int det(int[][] A)
{
int answer = 0;
int place = 0;
int[][] temp;
int[][] temp1;
if(A.length==1){
return(A[0][0]);
}
for(int i = 0; i<A.length; i++){
temp = new int[A.length-1][A[0].length-1];
temp1 = Copy(temp, i);
if(i%2==0){
place = 1;
}
else{
place = -1;
}
answer = answer + place * A[0][i] * det(temp1);
}
return answer;
}
public static int[][] Copy(int[][] B, int i)
{
//The C array size should be same as B
int[][] C = new int[B.length][B[0].length];
for(int j = 1; j<B.length; j++){
for(int k = 0; k<B[0].length; k++){
if(k>i){
C[j-1][k-1]=B[j][k];
}
else{
C[j-1][k]=B[j][k];
}
}
}
return C;
}
public static void printArray(int[][] A)
{
for(int i=0; i<A.length; i++)
{
for(int j=0; j<A.length; j++)
{
int num = A[i][j];
if(num<-9)
System.out.print(" ");
else if(num<0||num>9)
System.out.print(" ");
else
System.out.print(" ");
System.out.print(A[i][j]);
}
System.out.println();
}
}
}
Hope this explains, enjoy!
You should declare your matrix in Copy function in this way:
int[][] C = new int[B.length][B[0].length];
Otherwise you are declaring a matrix without a row and column. The fact that you start to use from 0 doesn't mean you should declare one row in less!

Sorting multidimensional array without sort method?

I was tasked with creating a 2D array (10-by-10), filling it with random numbers (from 10 to 99), and other tasks. I am, however, having difficulty sorting each row of this array in ascending order without using the array sort() method.
My sorting method does not sort. Instead, it prints out values diagonally, from the top leftmost corner to the bottom right corner. What should I do to sort the numbers?
Here is my code:
public class Program3
{
public static void main(String args[])
{
int[][] arrayOne = new int[10][10];
int[][] arrayTwo = new int[10][10];
arrayTwo = fillArray(arrayOne);
System.out.println("");
looper(arrayTwo);
System.out.println("");
sorter(arrayTwo);
}
public static int randomRange(int min, int max)
{
// Where (int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
return (int)(Math.random()* ((max - min) + 1) + min);
}
public static int[][] fillArray(int x[][])
{
for (int row = 0; row < x.length; row++)
{
for (int column = 0; column < x[row].length; column++)
{
x[row][column] = randomRange(10,99);
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
return x;
}
public static void looper(int y[][])
{
for (int row = 0; row < y.length; row++)
{
for (int column = 0; column < y[row].length; column++)
{
if (y[row][column]%2 == 0)
{
y[row][column] = 2 * y[row][column];
if (y[row][column]%10 == 0)
{
y[row][column] = y[row][column]/10;
}
}
else if (y[row][column] == 59)
{
y[row][column] = 99;
}
System.out.print(y[row][column] + "\t");
}
System.out.println();
}
//return y;
}
public static void sorter(int[][] z)
{
int temp = 0;
int tempTwo = 0;
int lowest;
int bravo = 0;
int bravoBefore = -1;
for (int alpha = 0; alpha < z.length; alpha++)
{
//System.out.println(alpha + "a");
lowest = z[alpha][bravoBefore + 1];
bravoBefore++;
for (bravo = alpha + 1; bravo < z[alpha].length; bravo++)
{
//System.out.println(alpha + "b");
temp = bravo;
if((z[alpha][bravo]) < lowest)
{
temp = bravo;
lowest = z[alpha][bravo];
//System.out.println(lowest + " " + temp);
//System.out.println(alpha + "c" + temp);
tempTwo = z[alpha][bravo];
z[alpha][bravo] = z[alpha][temp];
z[alpha][temp] = tempTwo;
//System.out.println(alpha + "d" + temp);
}
}
System.out.print(z[alpha][bravoBefore] + "\t");
}
/*
for (int alpha = 0; alpha < z.length; alpha++)
{
for (int bravo = 0; bravo < z.length - 1; bravo++)
{
if(Integer.valueOf(z[alpha][bravo]) < Integer.valueOf(z[alpha - 1][bravo]))
{
int[][] temp = z[alpha - 1][bravo];
z[alpha-1][bravo] = z[alpha][bravo];
z[alpha][bravo] = temp;
}
}
}
*/
}
}
for(int k = 0; k < arr.length; k++)
{
for(int p = 0; p < arr[k].length; p++)
{
least = arr[k][p];
for(int i = k; i < arr.length; i++)
{
if(i == k)
z = p + 1;
else
z = 0;
for(;z < arr[i].length; z++)
{
if(arr[i][z] <= small)
{
least = array[i][z];
row = i;
col = z;
}
}
}
arr[row][col] = arr[k][p];
arr[k][p] = least;
System.out.print(arr[k][p] + " ");
}
System.out.println();
}
Hope this code helps . Happy coding
let x is our unsorted array;
int t1=0;
int i1=0;
int j1=0;
int n=0;
boolean f1=false;
for(int i=0;i<x.length;i++){
for(int j=0;j<x[i].length;j++){
t1=x[i][j];
for(int m=i;m<x.length;m++){
if(m==i)n=j+1;
else n=0;
for(;n<x[m].length;n++){
if(x[m][n]<=t1){
t1=x[m][n];
i1=m;
j1=n;
f1=true;
}
}
}
if(f1){
x[i1][j1]=x[i][j];
x[i][j]=t1;
f1=false;
}
}
}
//now x is sorted; "-";

How to find the saddlePoint in IntMatrix [duplicate]

This question already has answers here:
How to find a saddle point of a matrix using Java? [closed]
(2 answers)
Closed 8 years ago.
This is my program in finding the Saddle Point of a Matrix (IntMatrix). Please help me make another method for IntMatrix m, for the Parameters inside the saddlePoints method?
public class SaddlePoint{
public void saddlePoints(IntMatrix m, int[] rows, int[] cols) {
int rows = m.length;
int cols = m[0].length;
boolean[][] flagArr = new boolean[rows][cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
if(m[i][j]==0){
flagArr[i][j]=true;
}
}
}
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
if(flagArr[i][j]==true){
/*for rows*/
for(int k=0; k<rows; k++){
m[k][j]=0;
}
/*for cols*/
for(int z=0; z<cols; z++){
m[i][z]=0;
}
}
}
}
}
}
this is the requirement
but i need the saddlePoint method only because I already have the other methods
IntMatrix Class:
//represents a 2-dimensional matrix of integers
Constructor Signature:
IntMatrix(int rows, int cols, int ... elements)
//elements are provided in row major order
IntMatrixUtilityClass
Static Methods:
IntMatrix sum(IntMatrix ... matrices)
//returns the sum of its arguments
IntMatrix product(IntMatrix m1, IntMatrix m2, IntMatrix ... others)
//returns the product of its arguments
boolean[] saddlePoints(IntMatrix m, int[] rows, int[] cols)
/*for each of the row and column pairs, returns true if the specified element of m is a saddle
point for the matrix; returns false otherwise*/
this is my program, I only need the saddlePoints
public class IntMatrix {
private int[][] matrix;
private int rows;
private int cols;
private int[] elements;
public IntMatrix(int r, int c, int... e) {
this.rows = r;
this.cols = c;
this.elements = e;
matrix = new int[rows][cols];
int l = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
this.matrix[i][j] = elements[l];
l++;
}
}
}
public static IntMatrix sum(IntMatrix... matrices) {
int[] result = new int[matrices[0].rows * matrices[0].cols];
for (IntMatrix matrix : matrices) {
int l = 0;
for (int i = 0; i < matrix.rows; i++) {
for (int j = 0; j < matrix.cols; j++) {
result[l] += matrix.matrix[i][j];
l++;
}
}
}
IntMatrix m3 = new IntMatrix(matrices[0].rows, matrices[0].cols, result);
return m3;
}
public static IntMatrix product(IntMatrix m1, IntMatrix m2,
IntMatrix... others) {
int[] result = new int[m1.rows * m2.cols];
int l = 0;
for (int i = 0; i < m1.rows; i++) {
for (int j = 0; j < m2.cols; j++) {
for (int k = 0; k < m1.cols; k++) {
result[l] += (m1.matrix[i][k] * m2.matrix[k][j]);
}
l++;
}
}
IntMatrix m3 = new IntMatrix(m1.rows, m2.cols, result);
for (IntMatrix other : others) {
int length = others.length;
l = 0;
int[] result2 = new int[(m3.rows * others[length - 1].cols)];
for (int i = 0; i < m3.rows; i++) {
for (int j = 0; j < other.cols; j++) {
for (int k = 0; k < m3.cols; k++) {
result2[l] += (m3.matrix[i][k] * other.matrix[k][j]);
}
l++;
}
}
m3 = new IntMatrix(m3.rows, others[length - 1].cols, result2);
}
return m3;
}
public String toString() {
return String.valueOf(rows) + " " + " " + String.valueOf(cols)
+ Arrays.toString(elements);
}
}// end of Matrix Class
First I want to say please do some research on your own before asking. From Here How to find a saddle point of a matrix using Java? you can find accepted ans but here I tell you that is not according to Wikipedia definition
Sadle Point:
A saddle point is an element of the matrix which is both the largest element in its
column and the smallest element in its row.
OR in simple words A matrix is said to have a saddle point if some entry a[x][y] is the smallest value in the x'th row and the largest value in the y'th column. A matrix may have more than one saddle point.
This Code is according to wikipedia defination
package com.mubasher.main;
import java.util.Random;
public class SaddlePoint {
private int[][] intMatrix;
private int[] colMaxima;
private int[] rowMinima;
public SaddlePoint(int col, int row){
intMatrix = new int[row][col];
colMaxima = new int[col];
rowMinima = new int[row];
fillMatrix();
}
private void fillMatrix() {
Random random = new Random();
for(int row = 0; row<intMatrix.length;row++){
for(int col = 0;col<intMatrix[0].length;col++){
intMatrix[row][col] = random.nextInt(21) - 10;
}
}
printMatrix();
}
private void printMatrix(int[][] intMatrix) {
for(int row = 0;row<intMatrix.length;row++){
for(int col = 0; col<intMatrix[0].length;col++){
System.out.print(intMatrix[row][col]+" ");
}
System.out.println("");
}
for(int i=0;i<intMatrix[0].length;i++)
System.out.print("----");
System.out.println("");
}
public void printMatrix() {
printMatrix(intMatrix);
}
public void printArray(int[] array,boolean isHorizontaly) {
for(int i = 0;i<array.length;i++){
if(isHorizontaly){
System.out.print(array[i]+" ");
} else {
System.out.println(array[i]);
}
}
if(isHorizontaly){System.out.println("");
for(int i=0;i<array.length;i++)
System.out.print("----");
} else {
System.out.println("----");
}
System.out.println("");
}
public void run(){
int maxVal = 0,minVal=0;
//minimum in each row
for(int row = 0; row<intMatrix.length;row++){
for(int col = 0;col<intMatrix[0].length;col++){
if(col == 0 ) {
rowMinima[row]=intMatrix[row][col]; // assume first val at (row,0) is minimum
} else {
if(intMatrix[row][col]<rowMinima[row]){
rowMinima[row]=intMatrix[row][col]; // assign new minimum val
}
}
}
}
//maximum in each column
for(int col = 0; col<intMatrix[0].length;col++){
for(int row = 0;row<intMatrix.length;row++){
if(row == 0 ) {
colMaxima[col]=intMatrix[row][col]; // for
} else {
if(intMatrix[row][col]>colMaxima[col]){
colMaxima[col]=intMatrix[row][col]; // assign new max val
}
}
}
}
printArray(colMaxima,true);
printArray(rowMinima,false);
int colIndx=0,rowIndx=0;
for(int i =0;i<colMaxima.length;i++){
if(i == 0 ) {
minVal= colMaxima[i];
colIndx=i;
} else {
if(colMaxima[i]<minVal){
minVal= colMaxima[i];
colIndx=i;
}
}
}
for(int i =0;i<rowMinima.length;i++){
if(i == 0 ) {
maxVal= rowMinima[i];
rowIndx = i;
} else {
if(rowMinima[i]>maxVal){
maxVal= rowMinima[i];
rowIndx = i;
}
}
}
if(minVal == maxVal){
System.out.println("We Have Saddle Point "+maxVal+" at ("+(rowIndx+1)+","+(colIndx+1)+")");
} else {
System.out.println("There is no saddle point");
}
}
public static void main(String[] args) {
SaddlePoint sp = new SaddlePoint(3, 4);
sp.run();
}
}
you can modify run method according to your needs. run method is calculating saddle point

How to print a two dimensional array?

I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a "1".
The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the "1" with an "X". The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.
public void printGrid() {
System.out.println...
}
you can use the Utility mettod. Arrays.deeptoString();
public static void main(String[] args) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
System.out.println(Arrays.deepToString(twoD));
}
public void printGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
And to replace
public void replaceGrid()
{
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
}
}
}
And you can do this all in one go:
public void printAndReplaceGrid()
{
for(int i = 0; i < 20; i++)
{
for(int j = 0; j < 20; j++)
{
if (a[i][j] == 1)
a[i][j] = x;
System.out.printf("%5d ", a[i][j]);
}
System.out.println();
}
}
Something like this that i answer in another question
public class Snippet {
public static void main(String[] args) {
int [][]lst = new int[10][10];
for (int[] arr : lst) {
System.out.println(Arrays.toString(arr));
}
}
}
public static void printTwoDimensionalArray(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.printf("%d ", a[i][j]);
}
System.out.println();
}
}
just for int array
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
You should loop by rows and then columns with a structure like
for ...row index...
for ...column index...
print
but I guess this is homework so just try it out yourself.
Swap the row/column index in the for loops depending on if you need to go across first and then down, vs. down first and then across.
How about trying this?
public static void main (String [] args)
{
int [] [] listTwo = new int [5][5];
// 2 Dimensional array
int x = 0;
int y = 0;
while (x < 5) {
listTwo[x][y] = (int)(Math.random()*10);
while (y <5){
listTwo [x] [y] = (int)(Math.random()*10);
System.out.print(listTwo[x][y]+" | ");
y++;
}
System.out.println("");
y=0;
x++;
}
}
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
I am also a beginner and I've just managed to crack this using two nested for loops.
I looked at the answers here and tbh they're a bit advanced for me so I thought I'd share mine to help all the other newbies out there.
P.S. It's for a Whack-A-Mole game hence why the array is called 'moleGrid'.
public static void printGrid() {
for (int i = 0; i < moleGrid.length; i++) {
for (int j = 0; j < moleGrid[0].length; j++) {
if (j == 0 || j % (moleGrid.length - 1) != 0) {
System.out.print(moleGrid[i][j]);
}
else {
System.out.println(moleGrid[i][j]);
}
}
}
}
Hope it helps!
more simpler approach , use java 5 style for loop
Integer[][] twoDimArray = {{8, 9},{8, 10}};
for (Integer[] array: twoDimArray){
System.out.print(array[0] + " ,");
System.out.println(array[1]);
}

Categories