I'm struggling to find an answer to the problem below. User inputs rows and columns. Example below is given for 4 x 4 matrix.
1 8 9 16
2 7 10 15
3 6 11 14
4 5 12 13
I cannot find how to relate the numbers when printing the array. The only obvious relation is how it goes downwards and upwards. From my perspective looks really hard. I'm just a beginner.
Not quite sure if there is any point to post the code, but it's just the basic lines:
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your array rows: ");
int rows = scanner.nextInt();
System.out.println("Please enter your array columns: ");
int columns = scanner.nextInt();
int[][] array = new int[rows][columns];
int counter = 0;
for (int j = 0; j < columns; j++){
for (int i = 0; i < rows; i++) {
counter++;
array[i][j]=...(stuck at the beginning);
}
Probably I'd need to use several loops , not only the above-mentioned or probably it is totally wrong ...
Thank you in advance!
I think this should do it.
int counter = 0;
boolean top_to_bottom=true;
for (int j = 0; j < columns; j++){
for (int i = 0; i < rows; i++) {
counter++;
if(top_to_bottom)
array[i][j]=counter;
else
array[rows-1-i][j]=counter;
}
if(top_to_bottom)
top_to_bottom=false;
else top_to_bottom=true;
}
It serves the purpose
import java.util.*;
public class Seq
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter your array rows: ");
int rows = scanner.nextInt();
System.out.println("Please enter your array columns: ");
int columns = scanner.nextInt();
int[][] array = new int[rows][columns];
int counter = 0;
for (int j = 0; j < columns; j++){
if(j%2==0)
{
for (int i = 0; i < rows; i++)
{
counter=counter+1;
array[i][j]=counter;
}
}
else
{
for (int i = rows-1; i >=0; i--)
{
counter=counter+1;
array[i][j]=counter;
}
}
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
System.out.print(array[i][j]+" ");
}
System.out.println();
}
}
}
Related
If I have a partially filled 2D matrix from user input, how can I fill it in some other void method to get spiral matrix:
Here is my code: However, when I run it the dimensions of matrix still remain 1000X1000. How can I fix this problem? I need to have only two methods - fillSpiral and main. The program should get any square matrix from user then change its values in a way it becomes a spiral matrix.
import java.util.Scanner;
public class Spiral {
public static void fillSpiral(int matrix[][]) {
int row1 = 0, row2 = matrix.length, col1 = 0, col2 = matrix[0].length;
int num = 1;
while (num <= matrix.length) {
for (int col = col2-1; col >= col1; col--){
matrix[row2-1][col] = num;
num++;
}
for (int row = row2-2; row >= row1; row--) {
matrix[row][col1] = num;
num++;
}
for (int col = col1+1; col < col2; col++) {
matrix[row1][col] = num;
num++;
}
for (int row = row1+1; row < row2-1; row++) {
matrix[row][col2-1] = num;
num++;
}
row1++;
row2--;
col1++;
col2--;
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
System.out.printf("%12d", matrix[i][j]);
}
System.out.println();
}
}
public static void main(String args[]) {
int n = 0;
int[][] matrixOutput = new int[1000][1000];
Scanner keyboard = new Scanner(System.in);
for (int i=0; i<matrixOutput.length; i++) {
for (int j=0; j<matrixOutput[0].length; j++){
while (keyboard.hasNextInt()) {
matrixOutput[i][j] = keyboard.nextInt();
n++;
}
}
}
fillSpiral(matrixOutput);
}
}
example
Input
1 2 3
4 5 6
7 8 9
Output
5 6 7
4 9 8
3 2 1
Since the algorithm for an spiral matrix is not new i assume your only problem is to read a matrix of an fixed size. Then addressing only your main method use this
//i preferr buffered reader over scanner
try(BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)))
{
ArrayList<String> rows=new ArrayList();
String line=null;
do
{
//example 1,2,3,4,5
System.out.println("Enter an row for this matrix all elements , seperated or an empty string to end input");
line=reader.readLine().trim();
if(!(line.isEmpty() || line.isBlank())){rows.add(line);}
else{line=null;}
}
while(line!=null);
//i assume a square matrix so rows=columns
int n=rows.size();
int[][] matrix=new int[n][n];
for(int i=0;i<n;i++)
{
//split at comma to get columns
String[] columns=rows.get(i).split(",");
//assign each column to the ith row
for(int j=0;j<n;j++){matrix[i][j]=Integer.parseInt(columns[j]);}
}
fillSpiral(matrix);
}
Trying to change this code so I can get user input instead of a predefined array. Can anyone help? This code needs to have the method sum with the double[][] parameter. The method should return the sum of the elements of the array passed to it and should be rectangular.
import java.util.Scanner;
class Array2_1
{
public static double sum (double[][] array)
{
double sum = 0;
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[0].length; j++)
{
sum += array[i][j];
}
}
return sum;
}
public static void main(String[] args)
{
System.out.println("")
double a [][] = {
{1.2, 2},
{6, 7.2},
{11, 12}
};
System.out.println(sum(a));
}
}
You can use Scanner to read values from the keyboard. First, read the values for the dimensions of the array and then input values for the individual indices using nested loops.
You can also define a method to display the array in the tabular form.
Demo:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();
double array[][] = new double[rows][cols];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.printf("Enter value for array[%d][%d]: ", i, j);
array[i][j] = scanner.nextDouble();
}
}
System.out.println("The array:");
print(array);
System.out.println("Sum of elements: " + sum(array));
}
public static double sum(double[][] array) {
double 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;
}
public static void print(double[][] array) {
for (double[] row : array) {
for (double col : row) {
System.out.print(col + "\t\t");
}
System.out.println();
}
}
}
A sample run:
Enter the number of rows: 3
Enter the number of columns: 2
Enter value for array[0][0]: 1.2
Enter value for array[0][1]: 2
Enter value for array[1][0]: 6
Enter value for array[1][1]: 7.2
Enter value for array[2][0]: 11
Enter value for array[2][1]: 12
The array:
1.2 2.0
6.0 7.2
11.0 12.0
Sum of elements: 39.4
I have added comments to the code for your understanding. Hope it answers your query.
public static void main(String[] args) {
//You can use the Scanner class for taking input
Scanner scan = new Scanner(System.in);
//take input for the number of rows in array
System.out.println("Enter no. of rows in array");
int row = scan.nextInt();
//take input for the number of columns in array
System.out.println("Enter no. of columns in array");
int col = scan.nextInt();
//create an array with row and col as dimensions of the 2D array
double[][] arr = new double[row][col];
//this for loop is for inputting elements in your array
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++)
arr[i][j] = scan.nextInt();
//this for loop is for printing out the elements
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
scan.close();
//now give a call to your sum() method and print the result
System.out.println(sum(arr));
}
I'm trying to sum of rows of Matrix
When I just put elements in 2D array output is right but when I'm trying using Scanner output result is different
SAMPLE INPUT
2
1 2
3 4
Output:
3
7
Below code result correct
import java.io.*;
import java.util.*;
public class matrix {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int a[][] = {
{1, 2,},
{ 3, 4}
};
int rows, cols, sumRow, sumCol;
//Initialize matrix a
//Calculates number of rows and columns present in given matrix
rows = a.length;
cols = a[0].length;
//Calculates sum of each row of given matrix
for(int i = 0; i < rows; i++){
sumRow = 0;
for(int j = 0; j < cols; j++){
sumRow = sumRow + a[i][j];
}
System.out.println(sumRow);
}
//Calculates sum of each column of given matrix
for(int i = 0; i < cols; i++){
sumCol = 0;
for(int j = 0; j < rows; j++){
sumCol = sumCol + a[j][i];
}
}
}
}
Result incorrect if I'm trying with Scanner
import java.io.*;
import java.util.*;
public class matrix {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int column = sc.nextInt();
int [][] a = new int[row][column];
for (int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++) {
a[i][j] = sc.nextInt();
}
}
int rows, cols, sumRow, sumCol;
//Initialize matrix a
//Calculates number of rows and columns present in given matrix
rows = a.length;
cols = a[0].length;
//Calculates sum of each row of given matrix
for(int i = 0; i < rows; i++){
sumRow = 0;
for(int j = 0; j < cols; j++){
sumRow = sumRow + a[i][j];
}
System.out.println(sumRow);
}
//Calculates sum of each column of given matrix
for(int i = 0; i < cols; i++){
sumCol = 0;
for(int j = 0; j < rows; j++){
sumCol = sumCol + a[j][i];
}
}
}
}
With the sample input you've provided, you shouldn't be reading the number of rows and columns, but just a single int for the number of both rows and columns:
int size = sc.nextInt();
int [][] a = new int[size][size];
for (int i = 0; i < size; i++) {
for(int j = 0; j < size; j++) {
a[i][j] = sc.nextInt();
}
}
I do not see any logical problem with your code. However, it is equally important to keep your code clean and user friendly. I recommend you address the following points if you are serious about programming:
The following declaration is unnecessary:
rows = a.length;
cols = a[0].length;
You can simply use row and column instead of creating rows and cols for the same thing.
You should remove all such unnecessary things which create noise in your code.
You have missed printing the sum of each column i.e.
System.out.println(sumCol);
You do not need to declare throws IOException with main for this code.
You should always display a message describing the input; otherwise, the user remains clueless about what he/she is supposed to input.
Given below is the code incorporating these comments:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int row = sc.nextInt();
System.out.print("Enter the number of columns: ");
int column = sc.nextInt();
int[][] a = new int[row][column];
for (int i = 0; i < row; i++) {
System.out.println("Enter " + column + " integers: ");
for (int j = 0; j < column; j++) {
a[i][j] = sc.nextInt();
}
}
int sumRow, sumCol;
// Calculates sum of each row of given matrix
for (int i = 0; i < row; i++) {
sumRow = 0;
for (int j = 0; j < column; j++) {
sumRow = sumRow + a[i][j];
}
System.out.println("Sum of row " + i + ": " + sumRow);
}
// Calculates sum of each column of given matrix
for (int i = 0; i < column; i++) {
sumCol = 0;
for (int j = 0; j < row; j++) {
sumCol = sumCol + a[j][i];
}
System.out.println("Sum of column " + i + ": " + sumCol);
}
}
}
A sample run:
Enter the number of rows: 3
Enter the number of columns: 4
Enter 4 integers:
1 9 2 8
Enter 4 integers:
2 8 3 7
Enter 4 integers:
3 7 4 6
Sum of row 0: 20
Sum of row 1: 20
Sum of row 2: 20
Sum of column 0: 6
Sum of column 1: 24
Sum of column 2: 9
Sum of column 3: 21
I try to print the matrix AxA with all of the values are showed in there, but I failed.
Output should be something look like this:
1 2 3
4 5 6
Thank you
So this is my code:
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++)
array[i][j] = input.nextInt();
}
System.out.println(" " + array);
}
}
Updated:
I was able to print out the matrix, but now I run into the second question is calculating the average of each rows and columns of the matrix. I tried to use this code, but it didn't work, and I know that I have a major problem right here, but I couldn't find one.
I have been doing it since this morning until now. Not going to lie, this is my homework which to test my basic knowledge.
My new output should be:
1, 2, 3, ave=2
4, 5, 6, ave=5
ave=2.5, 3.5, 4.5
And this is my current code right now:
import java.util.Scanner;
public class Lab2 {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number for rows: ");
int rows = input.nextInt();
System.out.print("Enter a number for columns: ");
int columns = input.nextInt();
int[][] array = new int[rows][columns];
System.out.println("Enter the numbers in array: ");
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
array[i][j] = input.nextInt();
}
}
for(int i=0 ; i<rows ; i++)
{
for(int j=0 ; j<columns ; j++)
{
System.out.print(array[i][j] + " , ");
}
System.out.println("\n");
}
}
public static doube averageRow(int[][] array) {
int rowTotal = 0;
double average = 0;
for (int rows = 0; rows < array.length; rows++) {
for (int columns = 0; columns < array[rows].length; columns++) {
rowTotal += array[rows][columns];
}
average = rowTotal / array[rows].length;
System.out.println(average);
rowTotal = 0;
}
return rowTotal;
}
public static doube averageColumn(int[][] array) {
int columnTotal = 0;
double average = 0;
for (int columns = 0; columns < array.length; columns++) {
for (int rows = 0; rows < array[columns].length; rows++) {
columnTotal += array[rows][columns];
}
average = columnTotal / array[columns].length;
System.out.println(average);
columnTotal = 0;
}
return columnTotal;
}
}
You can use same logic for reading and writing array elements,Try this code
Reading an array...
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
array[i][j] = input.nextInt();
}
}
Printing array elements...
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
System.out.print(array[i][j] + " ");
}
System.out.println("\n");
}
Use
Stream.of(array).map(Arrays::toString).forEach(System.out::println);
Which will print :
[1 ,2, 3]
[4, 5, 6]
or
System.out.println(Arrays.deepToString(array));
Reference
Keep in mind that you can't simply print the whole array. I.e.: System.out.println(" " + array);
You're on the right track but you need to print using a for loop (give printf a try, it's powerful):
for (int i = 0; i < array.length; i++)
{
for (int j = 0; j < array[i].length; j++){
System.out.printf("%d ", array[i][j]);
}
System.out.printf("\n");
}
There is another single loop way I can think of:
for (int[] a : array) {
String str = Arrays.toString(a);
System.out.println(str.substring(1, str.length()-1).replaceAll("[,]", ""));
}
The for loop basically iterates over each row, i.e. value of 'a' is an array (row) in the matrix.
Arrays.toString(a) returns the string equivalent of the array, e.g. for a = [1,2,3,4,5], it would return "[1, 2, 3, 4, 5]". Now simply remove the brackets (substring) and replace commas (",") with "", and you have the desired result.
Note that the first parameter of the replaceAll is a regex, not the string itself.
I computed the product, sum, and transpose(of product), but I have no clue where to start on the cofactor and determinent of the product matrix.
Ive seen a couple examples but none that resemble my particular code so if anyone could show me how i could incorporate these two methods into my program I'd high appreciate it.
please dont ask me what i've tried because as I stated I am clueless at the moment
//here is the code I wrote for the product:
package programEx;
import java.io.*;
import java.util.*;
import java.io.File.*;
import java.util.Scanner;
public class progEx {
public static void main(String[] args) {
//Establishing Input Stream
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in A: ");
int rowsInA = s.nextInt();
System.out.print("Enter number of columns in A / rows in B: ");
int columnsInA = s.nextInt();
System.out.print("Enter number of columns in B: ");
int columnsInB = s.nextInt();
int[][] a = new int[rowsInA][columnsInA];
int[][] b = new int[columnsInA][columnsInB];
//Taking user input for 1st matrix
System.out.println("Enter matrix A");
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
a[i][j] = s.nextInt();
}
}
//Taking user input for 2nd matrix
System.out.println("Enter matrix B");
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < b[0].length; j++) {
b[i][j] = s.nextInt();
}
}
//calling the multiplication method and passing it to both matrices
int[][] c = multiply(a, b);
System.out.println("Product of A and B is");
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < c[0].length; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
//Separate method for the multiplication of 1st and 2nd matrices
public static int[][] multiply(int[][] a, int[][] b) {
int rowsInA = a.length;
int columnsInA = a[0].length;
int columnsInB = b[0].length;
int[][] c = new int[rowsInA][columnsInB];
for (int i = 0; i < rowsInA; i++) {
for (int j = 0; j < columnsInB; j++) {
for (int k = 0; k < columnsInA; k++) {
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
return c;
}
}
Well,a 3*3 matrix has 3 columns and 3 rows to begin with.
Each starts with an index 0.
Determinant can be calculated as:
int d=determinant();
int determinant()
{
int x=a[0][0]*((a[1][1]*a[2][2])-(a[2][1]*a[1][2]));
int y=-a[0][1]*((a[0][1]*a[2][2])-(a[2][0]*a[1][2]));
int z=a[0][2]*((a[1][0]*a[2][1])-(a[1][1]*a[2][0]));
int r=x+y+z;
return r;
}
This is only for finding the determinant of a 3*3 matrix.