Matrix in methos - java

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);
}

Related

Logical error while inserting elements in to Two dimensional array using Scanner

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

Separate methods for matrix and swapping diagonals

I am supposed to create a matrix and split it into 3 methods, where first one will read matrix, second will print matrix and third one will swap diagonals. Read matrix works but I've tried to pass the parameters to other methods so they can work too but when I call them in main class, it doesn't work.
public static void readMatrix() {
Random rand = new Random();
Scanner in = new Scanner(System.in);
System.out.println("Please insert how many rows and columns you want for matrix");
int ColumnsAndRows = in.nextInt();
int matrix[][] = new int[ColumnsAndRows][ColumnsAndRows];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = rand.nextInt(ColumnsAndRows * ColumnsAndRows) + 1;
}
}
}
public int[][] printMatrix(int matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println("");
}
return matrix;
}
public int[][] swapDiagonals(int ColumnsAndRows, int matrix[][]) {
for (int i = 0; i < ColumnsAndRows; i++) {
int temp = matrix[i][i];
matrix[i][i] = matrix[i][ColumnsAndRows - i - 1];
matrix[i][ColumnsAndRows - i - 1] = temp;
}
printMatrix(matrix);
return matrix;
You can use an int[][] store the matrix returned from readMatrix.
It is redundant here to let printMatrix and swapDiagonals return int[][].
You can let printMatrix and swapDiagonals be static, so you can call them in main method.
Here is a sample:
public class Matrix {
public static int[][] readMatrix() {
Random rand = new Random();
Scanner in = new Scanner(System.in);
System.out.println("Please insert how many rows and columns you want for matrix");
int ColumnsAndRows = in.nextInt();
int matrix[][] = new int[ColumnsAndRows][ColumnsAndRows];
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = rand.nextInt(ColumnsAndRows * ColumnsAndRows) + 1;
}
}
return matrix;
}
public static void printMatrix(int matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}
System.out.println("");
}
}
public static void swapDiagonals(int matrix[][]) {
int ColumnsAndRows = matrix.length;
for (int i = 0; i < ColumnsAndRows; i++) {
int temp = matrix[i][i];
matrix[i][i] = matrix[i][ColumnsAndRows - i - 1];
matrix[i][ColumnsAndRows - i - 1] = temp;
}
printMatrix(matrix);
}
public static void main(String[] args) {
int[][] matrix = readMatrix();
printMatrix(matrix);
System.out.println("swapDiagonals:");
swapDiagonals(matrix);
}
}
Result:
Please insert how many rows and columns you want for matrix
4
12 10 14 5
14 8 9 13
2 15 5 16
11 9 8 10
swapDiagonals:
5 10 14 12
14 9 8 13
2 5 15 16
10 9 8 11

Java Matrix using Arrays

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();
}
}
}

How do I handle multiple inputs using java.util.Scanner?

I am new to Java and when I wrote following code I faced this problem. I want to get a square matrix from user but first I get the number of columns and then I get the matrix and to handle this question I wrote this code:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
n = input.nextInt();
List<List<Integer>> matrix = new ArrayList<List<Integer>>();
for (int i = 0; i < n; i++)
{
matrix.add(new ArrayList<Integer>());
for (int j = 0; j < n; j++)
{
n = input.nextInt();
matrix.get(i).add(n);
}
}
}
}
I want to handle this input:
3
1 0 1
1 0 1
1 1 0
However, I type in:
3<enter>
1 0 1<enter>
Program exits just after the first entered row. How do I fix it?
If you are creating a matrix like used in a graph to show connections and you know how many there will be why not try a 2d array.
public static void main(String []args) {
int n,m ;
Scanner input = new Scanner(System.in);
n = input.nextInt();
int[][] matrix = new int[n][n];
for ( int i = 0 ; i < n ; i++ )
{ int j= 0;
while(input.hasNext() && j< matrix[].lenght)
{
m = input.nextInt();
matrix[i][j] = m;
j++
}
}
}
}
This should help :
import java.util.ArrayList;
import java.util.Scanner;
public class A {
public static void main(String []args) {
int n ;
Scanner input = new Scanner(System.in);
System.out.println("Columns : ");
n = input.nextInt();
ArrayList<List<Integer>> matrix = new ArrayList<List<Integer>>();
for ( int i = 0 ; i < n ; i++ )
{
matrix.add(new List<Integer>());
for ( int j = 0 ; j < n ; j++ )
{
int t = input.nextInt();
matrix.get(i).add(t);
}
}
/* This is to check the contents of the data structure */
for ( int j = 0 ; j < n ; j ++)
{
System.out.println();
for ( int k = 0 ; k < n ; k ++)
{
System.out.print(matrix.get(j).getElement(k) + " ");
}
}
}
}
1 Remember to import some of the features when needed; java.util.Scanner must be explicitly imported.
2 Messing with (Array)List is not needed here; use a regular array.
3 Scanner.nextInt() reads the whole line and parses an int at the beginning. Here you need to split the input by spaces.
Final code:
import java.util.Scanner; // note 1
import java.util.Arrays; // small utility
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt(); // load the size
int[][] matrix = new int[size][size]; // create a new array; note 2
for(int row = 0; row < size; ++row) {
String[] input = sc.nextLine().split(" "); // read a row
input = Arrays.copyOf(input, size); // pad/truncate the array
int[] processed = new int[size]; // for storing a row
for(int entry = 0; entry < size; ++entry)
processed[entry] = Integer.parseInt(input[entry]); // parse integers; note 3
matrix[row] = processed; // set the row
}
// for testing purposes:
for(int row = 0; row < size; ++row) {
for(int col = 0; col < size; ++col)
System.out.print(matrix[row][col] + " ");
System.out.println();
}
}
}

Inputs for column length is returning unintended length

While working on a code for making a irregular 2D-array, I discovered a weird error while messing with different inputted values for the column. While the row works, the column length input returns either the wrong amount or a null pointer error occurs. I'm not sure what might be causing this since inputs such as ( 1 , 2 , 3) returns the correct table but (2 , 1, 3) will not. Also in a row of 4 with column inputs of (2, 3, 4, 5) returns "index out of bounds exception: 5" when there shouldn't be able to be out of bounds because of the while loop that should keep it with in reasonable range. Neither the main nor the display method seems to be saving the intended column length correctly and I can't seem to spot why.
It seems the array is set to 3 rows with column length of 1 , 2 , 3.
The output for row(3) and column(2,3,1) gives:
A:2.0
B:2.0 2.0
C:2.0 2.0 2.0
when I want is:
A:2.0 2.0
B:2.0 2.0 2.0
C:2.0
The code:
import java.util.Scanner;
//================================================================
public class ArrayIrreg {
//----------------------------------------------------------------
private static Scanner Keyboard = new Scanner(System.in);
public static void main(String[] args) {
//----------------------------------------------------------------
char group, rLetter,letter;
String choice;
int sum = 0;
int num = 10; // for test
int rows = 10;
int columns = 8;
//greetings
System.out.println("");
System.out.println("Welcome to the Band of the Hour");
System.out.println("-------------------------------");
// creating 2d array
System.out.print("Please enter number of rows : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
while (rows < 0 || rows >= 10) {
System.out.print("ERROR:Out of range, try again : ");
rows = Keyboard.nextInt();
Keyboard.nextLine();
}
double[][] figures = new double[rows + 1][num];
for(int t = 0; t < rows; t++) {
rLetter = (char)((t)+(int)'A');
System.out.print("Please enter number of positions in row " + rLetter + " : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
while(columns < 0 || columns >= 8) {
System.out.print("ERROR:Out of range, try again : ");
columns = Keyboard.nextInt();
Keyboard.nextLine();
}
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
}
// filling the array
for(int row = 0; row < figures.length; ++row) {
for(int col = 0; col < figures[row].length; ++col) {
figures[row][col] = 2.0;
}
}
// printing the array
for(int row = 1; row < figures.length; ++row) {
// printing data row
group = (char)((row-1)+(int)'A');
System.out.print(group + " : ");
for(int col = 0; col < figures[row].length; ++col) {
System.out.print(figures[row][col] + " ");
System.out.print(" ");
}
System.out.print("["+","+avg(figures)+"]");
System.out.println();
}
//----------MENU
System.out.print("(A)dd, (R)emove, (P)rint, e(X)it : ");
choice = Keyboard.next();
letter = choice.charAt(0);
letter = Character.toUpperCase(letter);
if(letter == 'P') {
display(figures);
}
}
public static void display(double x[][]) {
int average, total;
char group;
System.out.println(" ");
for(int row=1;row<x.length;row++) {
group = (char)((row-1)+(int)'A');
System.out.print(group+" : ");
for(int column=0;column<x[row].length;column++){
System.out.print(x[row][column]+" ");
}
System.out.print("["+","+avg(x)+"]");
System.out.println();
}
}
public static int avg(double[][] temp) {
int sum = 0;
int avg = 0;
for (int col = 0; col < temp[0].length; col++) {
sum = 0;
for (int row = 0; row < temp.length; row++)
sum += temp[row][col];
System.out.println(sum);
}
avg = sum / temp.length;
return avg;
}
}
In Creating 2D Array,
Change this
double[][] figures = new double[rows + 1][num];
to
double[][] figures = new double[rows][num];
and
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
to
figures[t] = new double[columns] ;
In Printing Array
Change this
for(int row = 1; row < figures.length; ++row) {
group = (char)((row-1)+(int)'A');
to
for(int row = 0; row < figures.length; ++row) {
group = (char)((row)+(int)'A');
In display function
Change this
for(int row = 1; row < x.length; ++row) {
group = (char)((row-1)+(int)'A');
to
for(int row = 0; row < x.length; ++row) {
group = (char)((row)+(int)'A');
It's this
for(int j = 0; j <= columns; j++) {
figures[j] = new double[j] ;
}
I think you meant actually
figures[t] = new double[columns];

Categories