I'm having trouble with jetbrains academy tasks - java

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

Related

Determine if matrix is Markov matrix; answer is always false

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

how to display the unique number in 2d array and sum the unique number

import java.io.*;
public class Arrayact {
public static void main(String[] args) throws IOException {
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
int row, maxRow, col, maxCol;
int yctr = 0;
int sum = 0;
int y;
System.out.print("Number of row/s: ");
maxRow = Integer.parseInt(cin.readLine());
System.out.print("Number of colmun/s: ");
maxCol = Integer.parseInt(cin.readLine());
int arr[][] = new int[maxRow][maxCol];
System.out.println();
for (row = 0; row < maxRow; row++) {
for (col = 0; col < maxCol; col++) {
System.out.print("Index[" + row + "][" + col + "]: ");
arr[row][col] = Integer.parseInt(cin.readLine());
}
}
System.out.println();
for (row = 0; row < maxRow; row++) {
for (col = 0; col < maxCol; col++) {
y = arr[row][col];
if (arr[row][col] == y) {
yctr++;
sum += arr[row][col];
}
}
}
System.out.println("ther are " + yctr + "unique element and their sum is " + sum);
}
}
here is my code, i want to display the unique number and the sum of the unique number, but im just getting the number of input and the whole sum of the input. anyone knows what the wrong here?
You can refactor the part that calculates the sum of unique elements to use a Set, a data structure that can hold unique elements. So, for each y you can check if it exists in the set, and if it doesn't you add it to the sum and add this number to the set so that it doesn't get added to the sum again.
Set<Integer> numbers = new HashSet<>();
for (row = 0; row < maxRow; row++) {
for (col = 0; col < maxCol; col++) {
y = arr[row][col];
if (!numbers.contains(y)) {
numbers.add(y);
sum += y;
}
}
}
System.out.println("ther are " + numbers.size() + "unique element and their sum is " + sum);

Assistance with Java

please help me with the question below, I'm a beginner at programming trying to get my head around it
public class LandVille {
private int[][] land;
private boolean hasHouse;
public static void main(String args[]) {
LandVille landVille = new LandVille(3, 4);
landVille.displayLand();
}
// Task A - constructor
LandVille(int numRows, int numColumns) {
land = new int[numRows][numColumns];
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < numColumns; ++j) {
land[i][j] = 0;
}
}
hasHouse = false;
}
// Task B
public void displayLand() {
for (int i = 0; i < land.length; ++i) {
for (int j = 0; j < land[i].length; ++j) {
System.out.print(land[i][j] + " ");
}
System.out.println();
}
}
// Task C
public void clearLand() {
for (int i = 0; i < land.length; ++i) {
for (int j = 0; j < land[i].length; ++j) {
land[i][j] = 0;
}
}
hasHouse = false;
}
}
From the main method, ask the player for the row and column of the land. The number of rows
and the number of columns should be greater than 0 and less than or equal to 10. If any input is
not correct, show an error message and ask for that input again.
If all inputs are correct, create an object of LandVille class from main method. The row and column
values are passed as the parameter of its constructor.
Here's the code to accept the values using Scanner class:
Scanner ob = new Scanner(System.in);
int row = 0, col = 0;
while(true)
{
System.out.println("Enter the number of rows:");
row = ob.nextInt();
if(row <= 10 && row > 0) break;
else System.out.println("Invalid input. Try again.");
}
while(true)
{
System.out.println("Enter the number of columns:");
col = ob.nextInt();
if(col <= 10 && col > 0) break;
else System.out.println("Invalid input. Try again.");
}
LandVille landVille = new LandVille(row, col);
The purpose of the while loop:
If the user enters an invalid number, then the loop continues, asking the user to enter again.
If the user enters a valid number, then the loop stops, and the program continues.
ob is an object of Scanner class, and calling ob.nextInt() allows the user to input a number. The links provided in the comments may help to understand.
I understand your request. Below is some code that does what you need.
First, you need to use the object Scanner to interact with the user.
Second, it is better to use the do ... while synthax. With it, the user will enter at least one time in the loop before quit it if the provide answer is correct.
Finally, others comments are in the code.
Best regards.
/* You need to use the object Scanner to interact with the user */
import java.util.Scanner;
public class LandVille {
private int[][] land;
private boolean hasHouse;
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
int row = 0, col = 0;
// enter the number of rows
// loop until you enter the right row (row can be 1-10)
do {
System.out.print("Enter the number of rows:");
row = keyboard.nextInt();
} while (row > 10 || row <= 0);
// enter the number of colums
// loop until you enter the right col (col can be 1-10)
do {
System.out.print("Enter the number of columns:");
col = keyboard.nextInt();
} while (col > 10 || col <= 0);
// when the variables (row, col) are correct, then the object LandVille can be created.
LandVille landVille = new LandVille(row, col);
landVille.displayLand();
}
// Task A - constructor
LandVille(int numRows, int numColumns) {
land = new int[numRows][numColumns];
for (int i = 0; i < numRows; ++i) {
for (int j = 0; j < numColumns; ++j) {
land[i][j] = 0;
}
}
hasHouse = false;
}
// Task B
public void displayLand() {
for (int i = 0; i < land.length; ++i) {
for (int j = 0; j < land[i].length; ++j) {
System.out.print(land[i][j] + " ");
}
System.out.println();
}
}
// Task C
public void clearLand() {
for (int i = 0; i < land.length; ++i) {
for (int j = 0; j < land[i].length; ++j) {
land[i][j] = 0;
}
}
hasHouse = false;
}
}

Finding the location of a number in a 2d array

I am trying to create a program that lets you find how many times a curtain number occurs in a 2d array. One of the things that I am required to do is to create a method called countInstence which counts the amount of times a number occurs but also where they are located in the array. the problem i'm having is how do I output the location of the the number
public int[][] createArray(int rSize, int cSize) {
Random rnd = new Random();
int[][] array = new int[rSize][cSize];
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
array[row][col] = rnd.nextInt(26);
}
}
return array;
}
public void print2dArray(int[][] array) {
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
System.out.print(array[row][col] + "\t");
}
System.out.println("\n");
}
}
public int countInstence(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search)
count++;
}
}
return count;
}
public static void main(String[] args) {
Journal5b call = new Journal5b();
Scanner in = new Scanner(System.in);
int[][] myArray;
int value;
myArray = call.createArray(10, 10);
call.print2dArray(myArray);
System.out.println("Enter a number to search for: ");
value = in.nextInt();
System.out.println("Your number occurred "
+ call.countInstence(myArray, value) + " Times");
}
Just insert a one line print statement inside of the if-statement and format to print the row and column of the current index, as below...
public int countInstance(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search) {
System.out.printf("Instance found at [%d, %d]\n", row, col);
count++;
}
}
}
return count;
}
If you aren't familiar with the System.out.printf call or the %d symbols, you can read more about it here.
Just add this line to the for loop
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search) {
System.out.printf("Instance found at [%d, %d]\n", row, col);// add this line
count++;
}
}
}
If you want to also use location at other place then just declare a List and add location to that list while searching for element.
public static List<String> location=new ArrayList<String>();
public int countInstence(int[][] array, int search) {
int count = 0;
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
if (array[row][col] == search)
{
count++;
String loc=row+","+col;
location.add(loc);
}
}
}
return count;
}
public static void main(String[] args) {
Test call = new Test();
Scanner in = new Scanner(System.in);
int[][] myArray;
int value;
myArray = call.createArray(10, 10);
call.print2dArray(myArray);
System.out.println("Enter a number to search for: ");
value = in.nextInt();
System.out.println("Your number occurred "
+ call.countInstence(myArray, value) + " Times");
System.out.println("locations :");
for(int i = 0; i < location.size(); i++) {
System.out.println(location.get(i));
}
}
I suggest using Points:
List<Point> locations=new ArrayList<Point>();
....
if (array[row][col] == search)
{
count++;
locations.add(new Point(row,col));
}

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