I made 2D arrray which prints some random elements.
Now i need a method which calculates the sum of that elements but just elements below the main diagonal.
Here is my code...
class Init {
public static void main(String[] args) {
int n = 0;
int m = 0;
int aray[][];
Random random = new Random();
Scanner tastatura = new Scanner(System.in);
int[][] array = new int[n][m];
n = tastatura.nextInt();
m = tastatura.nextInt();
array = new int[n][m];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
array[i][j] = random.nextInt(20);
}
}
for (int[] a : array) {
System.out.println(Arrays.toString(a));
}
}
}
I did it like this... Now i can sum, but when i try to multyply same numbers i am geting 0 Why is that?
Scanner scanner = new Scanner(System.in);
System.out.print("Unesite duzinu kolona i redova : ");
int rows = scanner.nextInt();
int columns = rows;
int[][] matrix = new int[rows][rows];
Random random = new Random();
System.out.println("Nasumicni/random brojevi su :");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
matrix[i][j] = random.nextInt(20);
}
}
for (int[] a : matrix) {
System.out.println(Arrays.toString(a));
}
//here is the logic which sum those elements
int sum = 0;
for (int i = 1; i < rows; i++) {
for (int j = i - 1; j >= 0; j--) {
sum = sum + matrix[i][j];
}
}
System.out.println("\nMatrix is : ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("Proizvod elemenata ispod glavne dijagonale je: " + sum);
What about this?
int s = 0;
for(int i = 1; i < m; ++i)
for(int j = 0; j < i; ++j)
s += a[i][j];
This selectively loops through the elements below the main diagonal and sums them up, without looping through the entire matrix and making it lengthier.
The main diagonal of a matrix consists of those elements that lie on the diagonal that runs from top left to bottom right. But since you want those elements "below" the main diagonal, here is an algorithm I came up with for that.
int sum = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (i == j && (i + 1 < n))
{
int temp = i + 1;
while (temp < n)
{
sum += arr[temp][j];
temp++;
}
}
Also, you declare int[][] array multiple times. You need to declare it only once, after you get the values for n and m.
for(i=0;i
for(j=0;j
{
if(j>i)
d1+=a[i][j];. // Above the diagon
else
if(i>j)
d2+=a[i][j];. // Below the diagonal
}
Related
I need the maximum elements position if there is more than one maximum element then the first one is to be printed.
My code prints the position of the maximum element but not the first one.
I don't understand why the last iteration is not working as I intend it to.
Please solve it using only Java.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
}
}
// System.out.print(i + " " + j);
}
// System.out.print(max + " ");
// print index of highest element
// int pos1 = 0;
// int pos2 = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (matrix[i][j] == max) {
System.out.print(i + " " + j);
break;
}
// pos2 += 1;
break;
}
// pos1 += 1;
// break;
}
}
}
There is no need to go through the matrix twice. When you are searching for the max, store also the coordinates of the matrix where that max was found. A code example:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner sc = new Scanner(System.in);
// define lengths
int n = sc.nextInt();
int m = sc.nextInt();
// add length to matrix
int[][] matrix = new int[n][m];
// insert elements
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
matrix[i][j] = sc.nextInt();
}
}
// define max
int max = Integer.MIN_VALUE, row=0, col=0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
row=i;
col=j;
}
}
}
System.out.print("max: "+max + " is at: ");
System.out.print(col + " " + row); //indexes starting from zero
}
}
Create a new variable to hold the position of the max value and set it in the current loop
int max = matrix[0][0];
int[] maxPos = new int[2];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] > max) {
max = matrix[i][j];
maxPos[0] = i;
maxPos[1] = j;
}
}
}
and then remove the rest of the code and print the result
System.out.printf("Max is %d and is found at [%d, %d]\n", max, maxPos[0], maxPos[1]);
I'm trying to create a 2D int array of numbers that are the product of 2 via user input defining the length of the rows and columns, as the one below:
1 2 4 8
2 4 8 16
4 8 16 32
8 16 32 64
I've only got up to here, and cannot figure out how to make the matrix to start from 1 and to look like the one above. I'd appreciate your help on this one!
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
int[][] matrix = new int[n][n];
matrix[0][0] = 1;
int temp = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = temp * 2;
temp *= 2;
}
}
System.out.println(Arrays.deepToString(matrix));
I'd say that each element of the matrix would be:
matrix[i][j] = (int) Math.pow(2, i+j) ;
So, your loop would look like this:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = (int) Math.pow(2, i+j);
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
int[][] matrix = new int[n][n];
matrix[0][0] = 1;
int temp = 1;
for (int i = 0; i < n; i++) {
temp = (int)Math.pow(2, i);
for (int j = 0; j < n; j++) {
matrix[i][j] = temp;
temp *= 2;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j]+" ");
}
System.out.println();
}
}
I have created a 5x5 matrix out of random double numbers. I need help to also output the largest element (number) from each row and column. It would output it on a seperate line like "the largest elements in the rows are: [x, x ,x ,x,x] and the same for the columns.
I have tried to create two seperate methods but trying to call them is not working.
public class HomeworkOne {
private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double[n][n];
double[] randomArray = new double[n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Integer r = rand.nextInt() % 100;
randomMatrix[i][j] = Math.abs(r);
}
}
return randomMatrix;
}
public static void main(String[] args) {
double[][] matrix = RandomArray(5);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(matrix[i][j]);
}
System.out.println("");
}
}
}
I also keep getting the numbers in the matrix crunched up as in their is no space between the numbers. How could I format them to have a space between each number?
You can loop through the columns and rows and find the max; maxRow and maxCol both hold the maximum values, starting at index zero for both (so you know which row and column the max is from).
double[] maxRow = new double[5];
double[] maxCol = new double[5];
double[] row = new double[5];
double[] col = new double[5];
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 5; y++) {
row[y] = matrix[x][y];
col[y] = matrix[y][x];
}
Arrays.sort(row, 0, 4);
Arrays.sort(col, 0, 4);
maxRow[x] = row[4];
maxCol[x] = col[4];
}
I also keep getting the numbers in the matrix crunched up as in their is no space between the numbers. How could I format them to have a space between each number?
System.out.print(matrix[i][j] + " ");
import java.util.Random;
public class HomeworkOne{
private static double[][] RandomArray(int n) {
double[][] randomMatrix = new double [n][n];
double[] randomArray = new double [n];
Random rand = new Random();
rand.setSeed(System.currentTimeMillis());
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Integer r = rand.nextInt()% 100;
randomMatrix[i][j] = Math.abs(r);
}
}
return randomMatrix;
}
public static void main(String[] args){
System.out.println("\u000C");
int size = 5;
double[][] matrix= RandomArray(size);
for(int i=0; i<5; i++){
for(int j=0; j<5; j++){
System.out.printf("%6.1f", matrix[i][j]);
}
System.out.println("");
}
maxRow(size,matrix);
maxCol(size,matrix);
}
public static void maxRow(int size,double[][] randomMatrix){
double[] rows = new double[size];
for(int i = 0; i < size; i++){
rows[i] = randomMatrix[i][0];
for(int j = 1; j < size; j++){
if(randomMatrix[i][j] > rows[i]) rows[i] = randomMatrix[i][j];
}
}
System.out.println();
System.out.println("Max Rows");
for(int i = 0; i < size; i++){
System.out.println(i + " " + rows[i]);
}
}
public static void maxCol(int size,double[][] randomMatrix){
double[] cols = new double[size];
for(int j = 0; j < size; j++){
cols[j] = randomMatrix[0][j];
for(int i = 1; i < size; i++){
if(randomMatrix[i][j] > cols[j]) cols[j] = randomMatrix[i][j];
}
}
System.out.println();
System.out.println("Max Cols");
for(int i = 0; i < size; i++){
System.out.printf("%6d",i);
}
System.out.println();
for(int i = 0; i < size; i++){
System.out.printf("%6.1f",cols[i]);
}
}
}
I'm trying to fill a matrix vertically, but 1 row is missing. Can you help me ? There is the code. Maybe there is an easier way to fill a matrix verically, but i cant find it.
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of matrix: ");
int n = input.nextInt();
int [][] matrix = new int [n][n];
for (int i = 1; i < matrix.length; i++) {
matrix[0][i] = matrix[0][i -1] + n;
}
for(int i = 1; i < matrix.length; i++){
for (int j = 0; j < matrix.length; j++){
matrix[i][j] = matrix[i -1][j] + 1;
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
input.close();
}
Output:
Enter the value of matrix: 4
1 5 9 13
2 6 10 14
3 7 11 15
Your row is missing because you never printed it in your first loop (the one that is initializing your first line) - you should have a row of 0 4 10 12 at the beginning. But you could do it much easier with only one nested loop.
Try
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.print("Enter the value of matrix: ");
int n = input.nextInt();
int [][] matrix = new int [n][n];
matrix[0][0]=0; //you have forgotten the first value
for (int i = 1; i < matrix.length; i++) {
matrix[0][i] = matrix[0][i -1] + n;
//initializing the first line
}
for(int i = 1; i < matrix.length; i++){
for (int j = 0; j < matrix.length; j++){
matrix[i][j] = matrix[i -1][j] + 1;
}
// re-loop to display but this time start with i=0
for(int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix.length; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
input.close();
}
To fill a matrix vertically, you must loop through columns in the outer loop and through rows in the inner(nested) loop. For example:
for(int j = 0; j < matrix.length; j++) {
for(int i = 0; i < matrix.length; i++) {
matrix[i][j] = /* The value you want to fill */;
.../* Other stuff you wanna do */
}
}
There is an easier way of doing this:
keep a variable like count and iterate the matrix on columns first then rows:
int count = 1; // or 0 if you start with 0
int[][] a = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
a[j][i] = count; // notice j first then i
count++;
}
After that you can easly print out the values:
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
System.out.println(a[i][j]);
I am trying to print out the largest number in a 2D array. My problem is that my output are three numbers instead of one - the largest. Why?
Here is my code:
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int maxRows = 3;
int maxCols = 4;
int [] onedArray = new int [maxRows];
for (int i = 0; i < maxRows; i++){
onedArray[i] = (int) ((Math.random() * 100) * maxCols);
}
int [][] twodArray = new int[maxRows][];
for (int i = 0; i < maxRows; i++){
twodArray[i] = new int[maxCols];
}
for (int i = 0; i < twodArray.length; i++){
for (int j = 0; j < twodArray[i].length; j++){
twodArray[i][j] = (int) (Math.random() * 100);
}
}
System.out.println("2 - The 2D array: ");
for (int i = 0; i < twodArray.length; i++){
for (int j = 0; j < twodArray[i].length; j++){
System.out.print(twodArray[i][j] + " ");
}
System.out.println("");
}
int maxValue = 1;
System.out.println("\nMax values in 2D array: ");
for (int i = 0; i < twodArray.length; i++) {
for (int j = 0; j < twodArray.length; j++)
if (twodArray[i][j] > maxValue) {
maxValue = twodArray[i][j];
}
System.out.println(maxValue);
}
}
}
Everything up until the last sequence of instructions is correct (although poorly formatted).
Here is original:
int maxValue = 1;
System.out.println("\nMax values in 2D array: ");
for (int i = 0; i < twodArray.length; i++) {
for (int j = 0; j < twodArray.length; j++)
if (twodArray[i][j] > maxValue) {
maxValue = twodArray[i][j];
}
System.out.println(maxValue);
}
Here is better version:
int maxValue = 0;
System.out.println("\nMax values in 2D array: ");
for (int i = 0; i < twodArray.length; i++) {
for (int j = 0; j < twodArray[i].length; j++) {
if (twodArray[i][j] > maxValue) {
maxValue = twodArray[i][j];
}
}
System.out.println("Max value of row " + i + ": " + maxValue);
}
Look carefully and you'll see that I added the { character after the second for-loop.
If you wanted to find total max, and minimize open and close curly-braces here is another version:
int maxValue = 0;
System.out.println("\nMax values in 2D array: ");
for (int i = 0; i < twodArray.length; i++)
for (int j = 0; j < twodArray[i].length; j++)
if (twodArray[i][j] > maxValue)
maxValue = twodArray[i][j];
System.out.println("Maximum value: " + maxValue);
Good luck.
int m,n,max;
int a[][]=new int[10][10];
Scanner S=new Scanner(System.in);
System.out.println("Enter m*n matrix");
m=S.nextInt();
n=S.nextInt();
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=S.nextInt();
}
}
max=a[0][0];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(a[i][j]>max)
{
max=a[i][j];
}
}
}
System.out.println(max);
Your line System.out.println(maxValue); needs to come out of the loop over the variable i. It's being printed 3 times because it's inside this loop.
This would be easier to see if your code was indented properly; this is a good habit to get into anyway.
The answer is in your code once it's indented correctly:
for (int i = 0; i < twodArray.length; i++) {
for (int j = 0; j < twodArray.length; j++)
if (twodArray[i][j] > maxValue) {
maxValue = twodArray[i][j];
}
System.out.println(maxValue);
}
}
Don't underestimate how useful good indentation can be for catching this kind of bug :)
int max;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows : ");
int n = sc.nextInt();
System.out.println("Enter number of columns : ");
int m = sc.nextInt();
int[][] array = new int[n][m];
System.out.println("Enter the elements of array : ");
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
System.out.print("X[" + i + "," + j + "]" + "=");
array[i][j] = sc.nextInt();
}
}
max = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (array[i][j] > max) {
max = array[i][j];
}
}
}
System.out.println("Max value of the array is " + max);
}