Matrix diagonal - java

I would like to let you know that I'm new to this platform, I'm trying to solve this question, could anyone help me?
statement
The user must be prompted for the size of the matrix to be created. After user input, a square matrix is ​​created with the information obtained.
Example: The user entered the value 3 so we will have it.
[][][]
[][][]
[][][]
However, when printing the matrix on the screen, the diagonal must be filled with the values ​​1 and the value 0 for the other positions, but the diagonal must start on the right side. Example of the expected solution:
[0][0][1]
[0][1][0]
[1][0][0]

I think this question I would start by figuring out how to create the matrix with input, then I would probably keep some type of pointer that starts at the end of the first row as it is being built then I would decrement the pointer after each row till I am at index 0 of the last row with the pointer value in this case an integer.
I will code it below:
import java.util.*;
public class QuestionOne {
public static int[][] createMatrix(Integer n) {
int pointer = n - 1;
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (pointer == j) {
matrix[i][j] = 1;
pointer--;
continue;
}
matrix[i][j] = 0;
}
}
return matrix;
}
public static void printMatrix(int[][] matrix, int n) {
for(int i = 0; i < n; i++) {
for(int k = 0; k< n-1; k++) {
System.out.print(matrix[i][k] + ",");
}
System.out.print(matrix[i][n-1]);
System.out.println("");
}
}
public static void main(String[] args) {
System.out.print("Enter a number for declaring size:");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[][] mat = createMatrix(n);
printMatrix(mat, n);
}
}

Related

Tower of Hanoi using 2D arrays issue

I'm working on a Tower of Hanoi project for school which needs to ask the user how many disks there are and then it needs to create and then solve the tower with a visual included. How I decided to do it is by using 2D arrays and for the most part its working, my only problem is that I don't know how to move the disks while keeping it modular. Here is my code.
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of disks");
int num = scan.nextInt();
int temp = num-(num-1);
int measure = num;
//initializing the towers
int[][] towers = new int[num][num];
for(int i = 0 ; i < num; i++)
{
for(int j=0; j <3; j++)
{
}
}
createRings(towers, num, temp);
moveDisk(towers,num);
}
// creating the rings
private static void createRings (int[][]towers, int num, int temp)
{
for(int i = 0; i<num; i++)
{
for(int j=0; j<3;j++)
{
towers[i][0] = temp;
}
temp = temp+1;
}
displayTower(towers, num);
}
// prints the array for display purposes
private static void displayTower (int[][] towers, int num)
{
for(int i = 0; i<num; i++)
{
for(int j = 0; j<3; j++)
{
System.out.print(towers[i][j]+"\t");
}
System.out.println();
}
}
//moves the numbers in the array that represents disks
private static void moveDisk(int[][]towers, int num)
{
System.out.println();
displayTower(towers, num);
}
Does anyone have any suggestions on what I could do?
I've changed your code a bit to make it more readable for me.
I changed the towers array. Now each tower is its own array inside the towers array (makes more sense IMHO).
Arrays in Java know their size. So you don't have to pass the length of the array as a parameter to every method.
I added a method getHighestIdx() which returns the index before the first 0 value in the array
I don't know, how the function moveDisk() was intended to work. I changed the declaration so that it makes sense to me. It now moves a disk from tower i to tower j
This should help you to implement the algorithm from the linked question.
Here is the changed code:
public static void main(String[] args) {
int numberOfRings = 6;
int[][] towers = new int[3][numberOfRings];
createRings(towers);
displayTowers(towers);
moveDisk(towers, 0, 2);
displayTowers(towers);
}
private static void createRings(int[][] towers) {
for (int j = 0; j < towers[0].length; j++) {
towers[0][j] = j + 1;
}
}
private static void displayTowers(int[][] towers) {
for (int i = 0; i < towers[0].length; i++) {
for (int j = 0; j < towers.length; j++) {
System.out.print(towers[j][i] + " ");
}
System.out.println("");
}
}
private static void moveDisk(int[][] towers, int fromIdx, int toIdx) {
int valToMove = towers[fromIdx][getHighestIdx(towers[fromIdx])];
towers[fromIdx][getHighestIdx(towers[fromIdx])] = 0;
towers[toIdx][getHighestIdx(towers[toIdx]) + 1] = valToMove;
}
private static int getHighestIdx(int[] tower) {
int i = 0;
while (i < tower.length && tower[i] != 0) {
i++;
}
return i - 1;
}

Java - Getting compile error incompatible types int can't be converted to [][] [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Having trouble understanding compile error. Main should be left unchanged. I believe MakeandFillMatix method is the problem and I can't figure it out. I think it's how I created the method.
import java.util.*;
/*
*/
public class TesterProject
{
public static void main(String [] args)
{
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(n);
printMatrix(m);
}
public static int getMatrixSize()
{
Scanner S = new Scanner(System.in);
System.out.println("give me a int to create the matrix");
int n = S.nextint();
return n;
}
public static void makeAndFillMatrix(int [][] r)
{
Random generator = new Random(5);
int rand = generator.nextInt(10);
for(int i = 0; i < r.length; i++)
{
for(int j = 0; j < r; j++)
{
r[i][j]= rand;
}
}
return r;
}
public static void printMatrix(int [][] matrix)
{
for(int r = 0; r < matrix.length; r++)
{
for(int c = 0; c < matrix[r].length; c++)
{
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
}
Hint
You have many problems in your code :
int n = S.nextint(); it should be int n = S.nextInt(); with Upper I
You can't compare an int with an array for (int j = 0; j < r; j++) { i think you need this for (int j = 0; j < i; j++) {
void makeAndFillMatrix(int[][] r) it not return any thing, and your return an array in the end.
makeAndFillMatrix(int[][] r) take an array of 2D and not an int int[][] m = makeAndFillMatrix(n);
Fix this problem and your problem is solve :)
EDIT
Then you have to change your code to be like this :
public static void main(String[] args) {
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(n);//<<<----Problem 4
printMatrix(m);
}
public static int getMatrixSize() {
Scanner S = new Scanner(System.in);
System.out.println("give me a int to create the matrix");
int n = S.nextInt();//<<--------------Problem 1
return n;
}
public static int[][] makeAndFillMatrix(int n) {//<<<---Problem 3
Random generator = new Random(5);
int[][] r = new int[n][n];
int rand = generator.nextInt(10);
for (int i = 0; i < r.length; i++) {
for (int j = 0; j < i; j++) {//<<<-----------Problem 2
r[i][j] = rand;
}
}
return r;
}
public static void printMatrix(int[][] matrix) {
for (int r = 0; r < matrix.length; r++) {
for (int c = 0; c < matrix[r].length; c++) {
System.out.print(matrix[r][c] + " ");
}
System.out.println();
}
}
Change makeAndFillMatrix(int[][] r) to makeAndFillMatrix(int r)
You want the matrix size, which is an integer, so take integer instead of a multidimensional array.
And in the for loop after that, change r.length to just r
Change void to int [][] in the method declaration.
In the method add a line int[][] q; and change r[i][j] = rand to q[i][j] = rand
And change return r to return q
The error you are receiving is due to you calling
int[][] m = makeAndFillMatrix(n);
in your main method.
You set n as an int in the line above, meaning n is a number, BUT, makeAndFillMatrix(int[][]) takes in a 2d array of ints. (A 2d array is a matrix, by the way.)
If you want to make a matrix of the size entered in by the user, then instead of passing n into your makeAndFillMatrix method, you would need to pass in a matrix of size n. You can do this in two ways. Option 1 is to pass in the matrix to your makeAndFillMatrix method like so:
public static void main(String [] args)
{
int n = getMatrixSize();
int[][] m = makeAndFillMatrix(new int[n][n]); // new int matrix of size n
printMatrix(m);
}
Or (the more conventional way, in my opinion), you can give makeAndFillMatrix the size of the matrix (like you are doing), and you can have makeAndFillMatrix make the array:
public static void makeAndFillMatrix(int matrixSize)
{
int[][] r = new int[matrixSize][matrixSize];
Random generator = new Random(5);
int rand = generator.nextInt(10);
for(int i = 0; i < r.length; i++)
{
for(int j = 0; j < r[i].length; j++) //~~~I modified this line as well~~~
{
r[i][j]= rand;
}
}
return r;
}
Anyways, you can take your pick at which approach you want to take to this problem, but regardless, I noticed that your makeAndFillMatrix method had an error. I fixed it and wrote //~~~I modified this line as well~~~
Your inner for loop originally said for(int j = 0; j < r; j++), but r is a matrix. For the inner loop, you would want to increase j until it has reached the size of the current row you are on in the matrix, so I changed that line as well. (Your inner loop was correct in your printMatrix method.) Whichever approach you take for your first issue, the inner loop in your makeAndFillMatrix method will need to be modified as well.
I hope this helps!
You are trying to cast 'int' (in the main function) to an 'int[][]' (the parameter of 'makeAndFillMatrix'. Also, makeAndFillMatrix returns 'void'.
I believe you want to rewrite your function to something like this:
public static int[][] makeAndFillMatrix(int r)
{
// Create a new matrix
int[][] matrix = new int[r][r];
// Get a random value
Random generator = new Random(5);
int rand = generator.nextInt(10);
// Assign random value to each cell of the matrix
for(int i = 0; i < r; i++)
{
for(int j = 0; j < r; j++)
{
r[i][j] = rand;
}
}
// Return the matrix
return matrix;
}

2D array trouble finding char element(s)

I am trying to find the longest series of horizontal O's in my 2d array and just print out the longest path. I don't see my logic error, I keep reading over this but don't see my error. I have been stuck here for about 2 days. I am thinking maybe there is something wrong with my finding max length statement? I get an out of bounds error on line 58 and 31. Any advice to what I'm doing wrong would be much appreciated.
public class game {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner kbd = new Scanner(System.in);
System.out.println("ENTER A SINGLE INTEGER: ");
int n = kbd.nextInt();
char[][] mazeValue = new char[n][n];
System.out.println("ENTER A PATH: ");
for(int i = 0; i < mazeValue.length; i++ ){
for(int j = 0; j< mazeValue[i].length; j++){
mazeValue[i][j]= kbd.next().charAt(0);
}
}
printMaze(mazeValue);
horizontalPath(mazeValue);
}
public static void printMaze(char mazeValue[][])
{
System.out.println("MAZE");
for(int i = 0; i < mazeValue.length; i ++)
{
for (int j = 0; j < mazeValue[i].length; j++)
{
System.out.printf("%4c",mazeValue[i][j]);
}
System.out.printf("\n");
}
}
public static void horizontalPath(char mazeValue[][])
{
int horizontalPath=0;
int maxHorizontalCount=0;
int i;
int j;
for(i= 0; i<mazeValue.length; i++){
for(j = 0; j<mazeValue[i].length; j++){
if(mazeValue[i][j]== 'o'){
horizontalPath = horizontalPath + mazeValue[i][j];
}
}
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
}
System.out.printf("Longest horizontal path row %d length %d",i,maxHorizontalCount);
}
}
I'm guessing you have some imports before your code which offsets the line numbers, and your problem is in line 47 in the code above:
if(horizontalPath < mazeValue[i][j])
maxHorizontalCount = mazeValue[i][j];
This block is outside of your for loop over j. This means that by the time control gets here, j will be equal to n, thus causing an index out of bounds.
Also note you're not actually computing a max value of anything, just setting maxHorizontalCount to the value at [i][j]. To compute a max, you should do something like
maxHorizontalCount = maxHorizontalCount > mazeValue[i][j] ? maxHorizontalCount : mazeValue[i][j];
or use Math.max() of course.

2D Array Methods & Demo

I have an assignment to design and implement methods to process 2D Arrays.
It needs to have an implementation class (Array2DMethods) that has the following static methods:
readInputs() to read the number of rows and columns fro the user then reads a corresponding entry to that size. Ex: if a user enters 3 for # of rows and 3 for # of columns it'll declare an array of 10 and reads 9 entries.
max(int [][] anArray) it returns the max value in the 2D parameter array anArray
rowSum(int[][] anArray) it returns the sum of the elements in row x of anArray
columnSum(int[][] anArray) it returns the sum of the elements in column x of anArray **careful w/ rows of different lengths
isSquare(int[][] anArray) checks if the array is square (meaning every row has the same length as anArray itself)
displayOutputs(int[][] anArray) displays the 2 Dim Array elements
It also needs a testing class (Arrays2DDemo) that tests the methods.
I've commented the parts I'm having problems with. I'm not sure how to test the methods besides the readInputs method and also not sure how to format the part where you ask the user to enter a number for each row.
Here's my code so far:
import java.util.Scanner;
class Array2DMethods {
public static int [][] readInputs(){
Scanner keyboard = new Scanner(System.in);
System.out.print(" How many rows? ");
int rows = keyboard.nextInt();
System.out.print(" How many columns? ");
int columns = keyboard.nextInt();
int [][] ret = new int[rows][columns];
for (int i = 0; i<ret.length; i++) {
for (int j = 0; j < ret[i].length; j++) {
System.out.print("please enter an integer: "); //Need to format like Enter [0][0]: ... Enter [0][1]: ...etc.
ret[i][j] = keyboard.nextInt();
}
}
return ret;
}
public static int max(int [][] anArray) {
int ret = Integer.MIN_VALUE;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
if (anArray[i][j] > ret) {
ret = anArray[i][j];
}
}
}
return ret;
}
public static void rowSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i<anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static void columnSum(int[][]anArray) {
int ret = 0;
for (int i = 0; i < anArray.length; i++) {
for (int j = 0; j < anArray[i].length; j++) {
ret = ret + anArray[i][j];
}
}
}
public static boolean isSquare(int[][]anArray) {
for (int i = 0, l = anArray.length; i < l; i++) {
if (anArray[i].length != l) {
return false;
}
}
return true;
}
public static void displayOutputs(int[][]anArray) {
System.out.println("Here is your 2Dim Array:");
for(int i=0; i<anArray.length; i++) {
for(int j=0; j<anArray[i].length; j++) {
System.out.print(anArray[i][j]);
System.out.print(", ");
}
System.out.println();
}
}
}
Class Arrays2DDemo:
public class Arrays2DDemo {
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int [][] anArray = Array2DMethods.readInputs();
Array2DMethods.max(anArray);
Array2DMethods.rowSum(anArray);
//need to print out and format like this: Ex Sum of row 1 = 60 ...etc
Array2DMethods.columnSum(anArray);
//need to print out and format like this: Ex Sum of column 1 = 60 ...etc.
Array2DMethods.isSquare(anArray);
//need to print out is this a square array? true
Array2DMethods.displayOutputs(anArray);
//need it to be formatted like [10, 20, 30] etc
}
}
Assuming you want anArray to be the array you read in during your inputting, you should name that variable, as such...
public static void main(String[] args){
System.out.println("Let's create a 2Dim Array!");
int[][] anArray = Array2DMethods.readInputs();
System.out.println("max " + Array2DMethods.max(anArray));
Array2DMethods.rowSum(anArray);
Array2DMethods.columnSum(anArray);
System.out.println("Square " + Array2DMethods.isSquare(anArray));
Array2DMethods.displayOutputs(anArray);
}
Say you have a function f which takes a single input x. The problem is you're asking the computer to evaluate f(x) without ever telling it what x is. If you give x a value, however, such as x = 3, then asking f(x) becomes legal, because it becomes f(3), which can be evaluated.

Null Pointer Exception - Printing 2d array

I'm having an issue with attempting to print a 2 dimensional array, I continually get a nullpointer exception at the first for loop in printArray(), and at printArray(). I do know what a nullpointerexception means, I'm just having a hard time understanding why I'm getting it. I've ran into this problem before while trying to print an array and it'd be great for me to finally figure this out.
import java.lang.*;
import java.util.*;
public class Board {
int N = 3;
static int [][] unittest;
//construct a board from an N-by-N array of blocks
//(where blocks[i][j] = block in row i, column j)
public Board(int[][] blocks){
blocks = new int[N][N]; //creates array of size N
//generates random numbers 0 inclusive to # exclusive
//Random r = new Random(); uses blocks[i][j] = r.nextInt();
for (int i = 0; i < blocks.length; i++){
for (int j = 0; j < blocks[i].length; j++){
blocks[i][j] = randInt(0,9);
}
}
unittest = blocks.clone();
}
//generates random numbers in a range
private static int randInt( int min, int max){
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
//board size N
public int size(){
return 0; //placeholder
}
//number of blocks out of place
public int hamming(){
return 0; //placeholder
}
//sum of manhattan distances between blocks and goal
public int manhattan(){
return 0;
}
//is this board the goal board?
public boolean isGoal(){
return true; //placeholder
}
//is the board solvable?
public boolean isSolvable(){
return true; //placeholder
}
//does this board equal y?
//Object because can only take objects
//does it use Comparable?
public boolean equals(Object y){
return true; //placeholder
}
//all neighboring boards
public Iterable<Board> neighbors(){
Stack<Board> placeholder = new Stack<Board>();
return placeholder;
}
//string representation of the board
public String toString(){
return "placeholder";
}
//unit test
private static void printArray(){
for (int i = 0; i < unittest.length; i++){ //**NULL POINTER EXCEPTION
for (int j = 0; j < unittest[i].length; j++){
System.out.print(unittest[i][j]);
if (j < unittest[i].length - 1){
System.out.print(" ");
}
}
System.out.println();
}
}
public static void main(String[] args){
//prints out board
printArray(); //**NULL POINTER EXCEPTION
}
}
The problem lies in the test condition of printArray() function:
for (int i = 0; i < unittest.length; i++)
Here, unitest is a null object and when you try to apply length method on it, its throwing and exception.
Basically, you are not initializing the unittest object (2D array in your case). You can do something like this to avoid the exception:
private static void printArray(){
if(unittest == null)
System.out.println("its NULL");
else{
for (int i = 0; i < unittest.length; i++){ //**NULL POINTER EXCEPTION
for (int j = 0; j < unittest[i].length; j++){
System.out.print(unittest[i][j]);
if (j < unittest[i].length - 1){
System.out.print(" ");
}
}
System.out.println();
}
}
}
Hope it helps :)
static int [][] unittest;
is null when you call it
you have never initialized the array, nor put anything into it
Beyond initializing the array you have an off by one error
public Board(int[][] blocks){
blocks = new int[N][N]; //creates array of size N
//generates random numbers 0 inclusive to # exclusive
//Random r = new Random(); uses blocks[i][j] = r.nextInt();
for (int i = 0; i < blocks.length; i++){ <----------------- blocks length should be blocks.length-1
for (int j = 0; j < blocks[i].length; j++){ <---------------------also blocks [i].length - 1
blocks[i][j] = randInt(0,9);
}

Categories