Determine if matrix is Markov matrix; answer is always false - java

I'm writing a program to allow a user to input either 3x3 or 2x2 matrix (generated randomly) and each column has to equal a total 1 otherwise it is not a Markov matrix. My issue is that regardless of the input, it will only say that it is not a Markov matrix. I can't find exactly what is wrong with the logic below:
public static boolean isMarkovMatrix(double[][] m) {
//test if matrix is markov or not
for(int i = 0;i< m[0].length; i++) { //rows
for(int j = 0; j< m[0].length; j++) { //col
//check if numbers are positive
if(m[i][j] < 0) {
System.out.println("It is not a Markov Matrix");
return false;
}
else {
//check if numbers in columns equal to the sum of 1
//if the sum of columns is not equal to 1 it is not a markov matrix
for(int col = 0; col < m[0].length; col++) {
int total = 0;
for(int row = 0; row < m.length; row++) {
total += m[row][col];
if(total != 1) {
System.out.println("It is not a Markov Matrix");
return false;
}
else
System.out.println("It is a Markov Matrix");
return true;
}
}
}
}
}
return true;
}
public static void main(String[] args) {
//generate random number between 2 and 3 - size of matrix
Scanner input = new Scanner(System.in);
int n = (int)(Math.random() *(2)) + 2;
double [][] matrix = new double[n][n];
//prompt user to input elements in matrix
System.out.println("Enter " + n + " by " + n + " matrix row by row: ");
//allow user input for each element
for(int i = 0; i < matrix.length;i++) {
for(int j =0; j<matrix[i].length;j++) {
matrix[i][j] = input.nextDouble();
}
}
isMarkovMatrix(matrix);
}
}

Related

How to create a method in java which prints out the elements of a matrix in shown pattern?

The contents of the matrix starts from 1 to the product of rows and columns. The method "scan" should print out as per following:
If the row is entered 4 and column is entered 7, the contents of the matrix should look like the image provided here:
the correct matrix
So far I have tried absolutely noting because I just don't know how to make this possible. I can print in zigzag, spiral but I just have no idea about this one. Please have mercy on me and grant me an insight.
This code currently prints out in a spiral pattern.
How should I modify this "scan" method so it satisfies the aforementioned condition?
import java.util.Scanner;
import java.util.Random;
public class that {
public static void main(String[] args) {
int range;
range = 100;
Scanner scn = new Scanner(System.in);
while(true) {
int m, n;
System.out.println("Enter the number of row: ");
m = scn.nextInt();
System.out.println("Enter the number of column: ");
n = scn.nextInt();
if(m <= 0||n <= 0) break;
int[][] tab = new int[m][n];
generate(tab, range);
scan(tab);
}
scn.close();
}
static int len(int x) { return (""+x).length(); }
static void generate(int[][] tab, int range) {
// Random generation
Random rg = new Random();
for(int i=0; i<tab.length; ++i)
for(int j=0; j<tab[0].length; ++j)
tab[i][j] = rg.nextInt(2*range) - range;
}
static void scan(int[][] tab) {
int m = tab.length;
int n = tab[0].length;
int totalWidth = 0;
int num = 1;
int rowStart = m - 1, rowEnd = 0, colStart = 0, colEnd = n - 1;
// Compute column widths
int[] colw = new int[n];
for(int j=0; j<n; ++j) { // For every column look down
colw[j] = len(j); // (""+j).length();
for(int i=0; i<m; ++i) {
int w = len(tab[i][j]); //("" + tab[i][j]).length();
if(w > colw[j]) colw[j] = w;
}
totalWidth += colw[j];
}
// Printing
int ris = len(m-1); // row index size
System.out.printf("%"+ris+"s ", " ");
for(int j=0; j<n; ++j)
System.out.printf("%" + colw[j] +"d ", j);
System.out.println();
System.out.printf("%"+ris+"s+"," ");
for(int j=0; j<totalWidth+n-1; ++j)
System.out.printf("-");
System.out.println();
while (rowStart >= rowEnd && colStart <= colEnd) {
// Print leftmost column from bottom to top
if (colStart <= colEnd) {
for (int i = rowStart; i >= rowEnd; i--) {
tab[i][colStart] = num++;
}
colStart++;
}
// Print top row from right to left
if (rowStart >= rowEnd) {
for (int i = colStart; i <= colEnd; i++) {
tab[rowEnd][i] = num++;
}
rowEnd++;
}
// Print rightmost column from top to bottom
if (colStart <= colEnd) {
for (int i = rowEnd; i <= rowStart; i++) {
tab[i][colEnd] = num++;
}
colEnd--;
}
// Print bottom row from left to right
if (rowStart >= rowEnd) {
for (int i = colEnd; i >= colStart; i--) {
tab[rowStart][i] = num++;
}
rowStart--;
}
}
// Prints the matrix
for(int i=0; i<m; ++i) {
System.out.printf("%"+ris+"d|", i);
for(int j=0; j<n; ++j)
System.out.printf("%" + colw[j] +"d ", tab[i][j]);
System.out.println();
}
System.out.println();
}
}

I'm having trouble with jetbrains academy tasks

I'm supposed to do this.
Multi-dimensional array Cinema
The cinema has n rows, each row consists of m seats (n and m do not
exceed 20). The two-dimensional matrix stores the information on the
sold tickets, number 1 means that the ticket for this place is already
sold, the number 0 means that the place is available. You want to buy
k tickets to the neighboring seats in the same row. Find whether it
can be done.
Input data format
On the input, the program gets the number of n rows and m seats. Then,
there are n lines, each containing m numbers (0 or 1) separated by
spaces. The last line contains a number k.
Output data format
The program should output the number of the row with k consecutive
available seats. If there are several rows with k available seats,
output the first row with these seats. If there is no such a row,
output the number 0.
But I'm stuck at finding a proper if statement to find the same adjacent coordinates k number of times
import java.util.Scanner;
import java.util.*;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner= new Scanner(System.in);
int dim1=scanner.nextInt();
int dim2=scanner.nextInt();
int[][] twoDimArray=new int[dim1][dim2];
// for (int i = 0; i < twoDimArray.length; i++) {
// twoDimArray[i][i]=scanner.nextInt();
//System.out.println(Arrays.toString(twoDimArray[i]));
// }
for (int i=0;i<dim1;i++){
for (int j=0;j<dim2;j++){
int current=scanner.nextInt();
twoDimArray[i][j]=current;
}
}
/* for (int k = 0; k< dim1; k++)
{
for (int l= 0; l< dim2;l++)
{
System.out.print(twoDimArray[k][l] + " ");
}
System.out.println("");
}
*/
int seatsToBuy=scanner.nextInt();
for (int k = 0; k< dim1; k++)
{
for (int l= 0; l< dim2;l++)
{
if ((twoDimArray[k][l]==twoDimArray[k][l+1])&&l<dim2){
System.out.println(twoDimArray[k]);
break;
}
}
System.out.println("");
}
I modified your code a bit. Can you try the below modified code?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int dim1 = scanner.nextInt();
int dim2 = scanner.nextInt();
int[][] twoDimArray = new int[dim1][dim2];
for (int i = 0; i < dim1; i++) {
for (int j = 0; j < dim2; j++) {
int current = scanner.nextInt();
twoDimArray[i][j] = current;
}
}
for (int i = 0; i < dim1; i++) {
for (int j = 0; j < dim2; j++) {
System.out.print(twoDimArray[i][j] + " ");
}
System.out.println();
}
int seatsToBuy=scanner.nextInt();
int minConsSeats = seatsToBuy - 1;
int rowNum = 0;
for (int k = 0; k< dim1; k++)
{
int count = 0;
for (int l= 0; l< dim2;l++) {
if (twoDimArray[k][l] == 0 && count == minConsSeats) {
count ++;
} else if (l+1 < dim2 && twoDimArray[k][l] == 0 && twoDimArray[k][l+1] == 0) {
count++;
}
}
if (count >= seatsToBuy) {
rowNum = k + 1;
break;
}
}
System.out.println("Available row number: " + rowNum);
}
}
First I'd name variables with expressive names, not i, j, k, etc ..
So first gather inputs, I think you did that fine, I just renamed variables:
Scanner scanner = new Scanner(System.in);
System.out.print("Number of Rows: ");
int nbRows = scanner.nextInt();
System.out.print("Number of Cols: ");
int nbCols = scanner.nextInt();
int[][] seats = new int[nbRows][nbCols];
for (int row = 0; row < nbRows; row++) {
System.out.println("Row " + row);
for (int col = 0; col < nbCols; col++) {
System.out.print("Col " + col +": ");
int availability = scanner.nextInt();
seats[row][col] = availability;
}
}
System.out.print("Number of Seats to buy: ");
int seatsToBuy = scanner.nextInt();
Then it is always useful to have a little sanity check on what was input, so here is a little snippet to print out the seats for debugging
for (int row = 0; row < nbRows; row++) {
for (int col = 0; col < nbCols; col++) {
System.out.print(seats[row][col] + " ");
}
System.out.println();
}
Then I would use the following algorithm:
starts a counter at the beginning of the row to keep track of the maximum number of adjacent seats (maxAdjacentSeatsInRow). Then go seat by seat, if it is available, then increment the counter. If it is not, reset the counter to zero.
If at any point the counter equals the required number of seats, then that row is the one you want to return:
int availableRow = -1;
for (int row = 0; row < nbRows; row++) {
int maxAdjacentSeatsInRow = 0;
for (int col = 0; col < nbCols; col++) {
if(seats[row][col] == 0)
maxAdjacentSeatsInRow++;
else
maxAdjacentSeatsInRow = 0;
if (maxAdjacentSeatsInRow == seatsToBuy) {
availableRow = row;
break; // break out of the col loop
}
}
if(availableRow >= 0) {
break; // break out of the row loop if we found a row
}
}
// print out result
if(availableRow == -1) {
System.out.println("No seats available");
} else {
System.out.println("Seats available at row: " + availableRow);
}
Sample output:
Number of Rows: 3
Number of Cols: 4
Row 0
Col 0: 1
Col 1: 1
Col 2: 1
Col 3: 1
Row 1
Col 0: 1
Col 1: 0
Col 2: 0
Col 3: 1
Row 2
Col 0: 1
Col 1: 1
Col 2: 0
Col 3: 0
Number of Seats to buy: 2
1 1 1 1
1 0 0 1
1 1 0 0
Seats available at row: 1
The row index in the answer is zero based.
Also don't hesitate to make methods it makes things easier to read. Here is a version of the same thing but with methods:
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.print("Number of Rows: ");
int nbRows = scanner.nextInt();
System.out.print("Number of Cols: ");
int nbCols = scanner.nextInt();
int[][] seats = gatherSeatsInputs(nbRows, nbCols);
System.out.print("Number of Seats to buy: ");
int seatsToBuy = scanner.nextInt();
printSeats(seats);
int availableRow = findAvailableRow(seats, seatsToBuy);
if(availableRow == -1) {
System.out.println("No seats available");
} else {
System.out.println("Seats available at row: " + availableRow);
}
}
private static int[][] gatherSeatsInputs(int nbRows, int nbCols) {
int[][] seats = new int[nbRows][nbCols];
for (int row = 0; row < nbRows; row++) {
System.out.println("Row " + row);
for (int col = 0; col < nbCols; col++) {
System.out.print("Col " + col +": ");
int current = scanner.nextInt();
seats[row][col] = current;
}
}
return seats;
}
private static int findAvailableRow(int[][] seats, int seatsToBuy) {
for (int rowIndex = 0; rowIndex < seats.length; rowIndex++) {
if(rowHasEnoughSeats(seats[rowIndex], seatsToBuy)) {
return rowIndex;
}
}
return -1;
}
private static boolean rowHasEnoughSeats(int[] row, int seatsToBuy) {
int maxAdjacentSeatsInRow = 0;
for (int seatAvailability : row) {
if (seatAvailability == 0) {
maxAdjacentSeatsInRow++;
if (maxAdjacentSeatsInRow == seatsToBuy) {
return true;
}
} else {
maxAdjacentSeatsInRow = 0;
}
}
return false;
}
private static void printSeats(int[][] seats) {
for (int[] row : seats) {
for (int seat : row) {
System.out.print(seat + " ");
}
System.out.println();
}
}

i wrote this code to find the largest and smallest number from a numbers array populated by user but it does not work

I am getting user input for function (smallest or largest) and for populating array. Then according to the input function i want to compare consecutive elements and find the smallest or largest number. I cannot understand why and how to fix my code.
The code runs but does not work as supposed to. The smallest and largest numbers are all wrong
import java.util.Scanner;
public class App {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Are you trying to find the Smallest or Largest number in an array of numbers? S/L");
String functionExpected = sc.nextLine();
System.out.println("How many elements you plan to enter? ");
int lengthOfArray = sc.nextInt();
// Populating array according to input and length
int[] numbersArray = new int[lengthOfArray];
for (int i = 0; i < numbersArray.length; i++) {
System.out.println("Enter an element here: ");
numbersArray[i] = sc.nextInt();
}
// Print out array
for (int i = 0; i < numbersArray.length; i++) {
System.out.print(numbersArray[i] + " ");
}
System.out.println();
if (functionExpected.equalsIgnoreCase("L")) {
int temp = 0;
System.out.println("We are going to find the largest number in the array of elements you enter!");
for (int i = 0; i < numbersArray.length; i++) {
for (int j = 1; j < numbersArray.length;) {
if (numbersArray[i] > numbersArray[j]) {
temp = numbersArray[i];
break;
} else {
temp = numbersArray[j];
break;
}
}
}
System.out.println("Largest of the three numbers is : " + temp);
}
if (functionExpected.equalsIgnoreCase("S")) {
int temp = 0;
System.out.println("We are going to find the smallest number in the array of elements you enter!");
for (int i = 0; i < numbersArray.length; i++) {
for (int j = 1; j < numbersArray.length;) {
if (numbersArray[i] > numbersArray[j]) {
temp = numbersArray[j];
break;
} else {
temp = numbersArray[i];
break;
}
}
}
System.out.println("Smallest of the three numbers is : " + temp);
}
}
}
As pointed out by the comments the inner loops (j based) are completely unnecessary.
int temp = numbersArray[0];
for (int i = 1; i < numbersArray.length; i++) {
if(numbersArray[i] > temp) {
temp = numbersArray[i]
}
}
Just switch the > to < in the if for smallest/largest.

how to find prime number in 2d array and copy these numbers to another array

i have a code that create 2d array by asking user to enter the input than the system check if the elements are prime or not and if they are prime the system will copy them to an 1d array.
i can create the 2d array but i am stuck in the checking on the prime number and copied to a second array
this is the code
package question6;
import java.util.Scanner;
public class MtrixPrime {
public static void main(String[] args) {
int rows;
int cols;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of row");
rows = sc.nextInt();
System.out.println("Enter number of column");
cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
int[] array = new int[rows];
System.out.println("Enter numbers in the matrix");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
if(matrix[i][j] % matrix[i][j] ==0 && matrix[i][j] %1 == 0){
////here i am stuck can anyone help me ??
array[i * j];
}
matrix[i][j] = sc.nextInt();
}
}
for(int row = 0 ;row<matrix.length; row++){
for(int col = 0 ; col< matrix.length; col++){
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
}
I know it's old post but this might help others.
Used isPrime a boolean flag to save the state of matrix[i][j] value.
If reminder is 0 isPrime will hold false state of matrix[i][j].
Everything is similar like finding prime number of single number. Just have to use 3 for loops for matrix index, before that I have taken matrix values separately.
here's the code.
public static void main(String[] args) {
int rows, cols, remainder;
boolean isPrime = true;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of row and colums : ");
rows = sc.nextInt();
cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
System.out.println("Enter numbers in the matrix");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
matrix[i][j] = sc.nextInt();
}
}
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix.length; j++) {
for (int k = 2; k <= matrix[i][j] / 2; k++) {
remainder = matrix[i][j] % k;
if (remainder == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println(matrix[i][j] + " is a Prime number");
} else
System.out.println(matrix[i][j] + " is not a Prime number");
}
}
}
One tricky thing to look out for is that since you don't know how many primes you're going to get, and you're using regular arrays, you need a 1d array at least the total size of your 2d array, or you should just use an ArrayList. If you're set on using a primitive array, you could just add a counter that increases every time you find a new prime, and use that counter value as your index. This however would leave you with zeros on the back end of your array. If you want your index to correspond to the multi-dimensional array index, you multiply the row index by the number of members in the row, and then add the column index in order to get a 1d index as shown below. This would leave you with zeros inbetween elements in your array. Having zeros shouldn't necessarily be a bad thing since it isn't prime, but its still way easier in my mind to use an ArrayList.
int[][] nums2d = {{0,1,2},{3,4,5},{6,7,8}};
int[] nums1d = new int[9];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int index = i * 3 + j;
nums1d[index] = nums2d[i][j];
}
}

how would i get this program to print random numbers in the two dimensional array?

I would like some advice on taking away the numbers I manually inserted and adding random numbers?
And if its possible to print random decimal numbers? looking for some advice or maybe a site that could help with two dimensional arrays don't really get them that well.
import java.util.Scanner;
public class TwoDimensions
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
final int ROW = 3;
final int COLUMN = 4;
double scores[ ][ ] = { {66.7,77.8,88.9,55.6},
{88.4,82.1,99.4,85.4},
{55.6,66.6,77.6,69.4}
};
System.out.print(" ");
for (int heading = 0; heading < scores[0].length; heading++)
System.out.printf("%4d ",heading + 1);
System.out.println();
for (int row = 0; row < scores.length; row++)
{
System.out.printf("%d ",row+1);
for (int column = 0; column < scores[row].length; column++)
System.out.printf("%4.1f ", scores[row][column]);
System.out.println();
}
for (int row = 0; row < ROW; row++)
{
double average = 0;
for (int column = 0; column < COLUMN; column++)
average += scores[row][column];
System.out.printf("Average scores for row %d is %.2f\n",
(row + 1), (average / COLUMN));
}
}
}
If I understood your question correctly, how about something like this?
import java.util.Random;
import java.util.Scanner;
public class RandomDecimalValue {
public static void main(String[] args) {
final int ROW = 3;
final int COLUMN = 4;
double scores[][] = new double[ROW][COLUMN];
Random randGenerator = new Random();
Scanner sc = new Scanner(System.in);
// Initialize 2D array with appropriate random decimal values
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COLUMN; j++) {
scores[i][j] = (randGenerator.nextDouble() * 99.0) + 1.0;
}
}
// Print out array values
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COLUMN; j++) {
System.out.printf("%4.1f ", scores[i][j]);
}
System.out.println();
}
int randomRow = randGenerator.nextInt(ROW);
int randomCol = randGenerator.nextInt(COLUMN);
// Get a random decimal value from the 2D array
System.out.println("\nRandom decimal value: ");
System.out.printf("%-5.1f%n", scores[randomRow][randomCol]);
// Prints out random decimal value from selected row/column
System.out.printf("%nEnter a row number (1-%d): ", ROW);
int selectedRow = sc.nextInt();
System.out.printf("Enter a column number (1-%d): ", COLUMN);
int selectedCol = sc.nextInt();
if((selectedRow >= 1 && selectedRow <= ROW) &&
(selectedCol >= 1 && selectedCol <= COLUMN))
{
System.out.printf("%nRandom decimal value at Row %d, Column %d: ",
selectedRow, selectedCol);
System.out.printf("%4.1f%n",
scores[selectedRow - 1][selectedCol - 1]);
}
else
{
System.out.println("Invalid row/column values");
}
sc.close();
}
}
Output:
47.5 25.7 72.9 4.7
95.8 88.9 49.7 43.7
66.5 10.1 93.9 41.6
Random decimal value:
72.9
Enter a row number (1-3): 1
Enter a column number (1-4): 2
Random decimal value at Row 1, Column 2: 25.7
first instantiate a random object Random generator = new Random(); then fill your array as below double scores[ ][ ] = { {generator.nextInt(100),generator.nextInt(100),generator.nextInt(100),generator.nextInt(100)},
{generator.nextInt(100),generator.nextInt(100),generator.nextInt(100),generator.nextInt(100)},
{generator.nextInt(100),generator.nextInt(100),generator.nextInt(100),generator.nextInt(100)}
}; Note - you can change the bound i.e.100 as required and modify your code to handle int instead of double if you want to print decimals.

Categories

Resources