Can not get precise results for the hourglass algorithm - java

Here is the link for definition of the hourglass problem:
https://www.hackerrank.com/challenges/30-2d-arrays
I wrote the following program:
package day11;
import java.util.Scanner;
public class Solution {
public static void main(String ... args){
Scanner scan = new Scanner(System.in);
int[][] arr = new int[6][6];
int maxHourGlassValue = 0;
int temp = 0;
int currMax = 0;
int k = 0, l = 0;
for(int i = 0 ; i < 6 ; i++){
for(int j = 0 ; j < 6 ; j++){
arr[i][j] = scan.nextInt();
}
}
for(int i = 1 ; i < 5 ; i++){
for(int j = 1 ; j < 5 ; j++){
if(maxHourGlassValue < currMax){
maxHourGlassValue = currMax;
}
}
}
System.out.println(maxHourGlassValue);
}
}
I could only run 6 out of 8 given test cases. What could possibly go wrong ????

Try this code, i did not write that code, i just copy it and modified it from here
import java.util.Scanner;
public class Test {
public static void main(String ... args){
Scanner scan = new Scanner(System.in);
int size = 6;
int[][] m = new int[size][size];
//numbers input
for(int i=0; i<size; i++)
{
for(int j=0; j<size; j++)
{
m[i][j] = scan.nextInt();
}
}
int temp = 0, MaxSum = -99999;
for (int i=0; i<size; ++i) {
for (int j=0; j<size; ++j) {
if (j+2 < size && i+2 < size) {
temp = m[i][j] + m[i][j+1] + m[i][j+2] + m[i+1][j+1] + m[i+2][j] + m[i+2][j+1] + m[i+2][j+2];
if (temp >= MaxSum) {
MaxSum = temp;
}
}
}
}
System.out.println(MaxSum);
}
}

Below is the code which will run successfully for all the test cases of hourglass problem.
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
int[][] arr = new int[6][6];
int maxHourGlassValue = -63;//Assigning (-9*7=)-63 which is the minimum possible value of "hourglass sum".
//Reading inputs.
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
arr[i][j] = scan.nextInt();
}
}
//Logic.
/**
* Index of both i and j will run from 1 to 4 (one less than n-1 where n = 6)
* So for each i and j iteration calculating the sum of hourglass.
*/
int iHGValueTemp = 0;
for (int i = 1; i < 5; i++) {
for (int j = 1; j < 5; j++) {
iHGValueTemp = arr[i][j] + /*Main element*/
arr[i - 1][j - 1] + arr[i - 1][j] + arr[i - 1][j + 1]+ /*Top three elements of main element.*/
arr[i + 1][j - 1] + arr[i + 1][j] + arr[i + 1][j + 1]; /*Bottom three elements of main element.*/
if (iHGValueTemp > maxHourGlassValue) {
maxHourGlassValue = iHGValueTemp;
}
}
}
//Output.
System.out.println(maxHourGlassValue);
}
}
I have written description within code in the comments only. Please refer to that and discuss with me if any doubt.

Related

How can i make this matrix example with jagged array in java

I've this codes:
public class matrixExample {
public static void main(String[] args) {
int m[][] = new int[5][5];
int count = 1;
for (int i=0; i<m.length; i++)
for(int j=0; j<i+1; j++)
m[i][j] = count++;
for (int i=0; i<m.length; i++)
{
for (int j=0; j<m[i].length; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
And output:
How can I do as in the screenshot below?
int size = 5;
int[][] m = new int[size][size];
int count = 1;
for (int i = 0; i < size; ++i)
for (int j = size - i - 1; j < size; ++j)
m[i][j] = count++;
You may populate the matrix as suggested in saka1029's answer above and then print it using formatted output:
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
System.out.printf(" %2d ", m[i][j]);
}
System.out.print('\n');
}
Or, it is possible to keep "normal" matrix, and change only its output:
public static void main(String []args){
int m[][] = new int[5][5];
int count = 1;
// keeping initial array as is
for (int i=0; i<m.length; i++)
for(int j=0; j<i+1; j++)
m[i][j] = count++;
for (int i = 0; i < m.length; i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < m[i].length; j++) {
if (m[i][j] > 0) {
sb.append(String.format(" %2d ", m[i][j]));
} else {
sb.insert(0, String.format(" %2d ", m[i][j]));
}
}
System.out.println(sb.toString());
}
}
Output in both cases is identical:
0 0 0 0 1
0 0 0 2 3
0 0 4 5 6
0 7 8 9 10
11 12 13 14 15

Creating a matrix from a text file - Java

I have this text file:
2
2
12
13
23
24
49
59
69
79
the first two numbers should be the rows and columns of the matrix, which is 2x2 in this case. My issue that I'm trying to get around is finding a way to include a second 2D array that holds the second matrix.
my code:
Scanner fileInput = new Scanner(new File("input1.txt"));
int n1 = fileInput.nextInt();
int n2 = fileInput.nextInt();
System.out.print("matrix is " + n1 + "x" + n2 +"\n");
int [][] firstMatrix = new int [n1][n2];
int [][] secondMatrix = new int [n1][n2];
for(int i = 0; i < n1; ++i)
{
for(int j = 0; j < n2; ++j)
{
if(fileInput.hasNextInt())
{
firstMatrix[i][j] = fileInput.nextInt();
}
}
}
System.out.println("Matrices: ");
for(int i = 0; i < n1; i++)
{
for(int j = 0; j < n2; j++)
{
System.out.println(firstMatrix[i][j]);
}
}
it only prints the following:
12
13
23
24
How do I make it read the next four lines of integers from the file? It would also be helpful to understand how I can make it look something like this:
12 13
23 24
EDIT: This approach seemed to help with the last question:
for(int i=0; i<n1; i++)
{
for(int j=0; j<n2; j++)
{
System.out.print(firstMatrix[i][j] + " " );
//System.out.print(secondMatrix[i][j] + " ");
}
System.out.println();
}
The only problem I'm facing now is being able to include the four other integers and turn them into a matrix.
You can group them to 1 array:
int matrixNumb = 2; // number of matrix
int [][][] matrix = new int [matrixNumb][n1][n2];
for (int h = 0; h < matrixNumb; h++)
{
for(int i = 0; i < n1; ++i)
{
for(int j = 0; j < n2; ++j)
{
if(fileInput.hasNextInt())
{
matrix [h][i][j] = fileInput.nextInt(); // read from file
}
}
}
}
System.out.println("Matrices: ");
for (int h = 0; h < matrixNumb; h++)
{
for(int i = 0; i < n1; i++)
{
for(int j = 0; j < n2; j++)
{
System.out.print(matrix[h][i][j]);
System.out.print("\t"); //How do you want to separate columns?
}
System.out.print("\r\n"); //How do you want to separate rows?
}
System.out.println(); //How do u want to print next matrix?
}
I have not compiled or run it, but hope it help.
You can just read data for the two arrays from file sequentially, like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class App {
private static void readMatrix(final Scanner scanner, final int[][] matrix) {
for (int i = 0; i < matrix.length; ++i) {
for (int j = 0; j < matrix[i].length; ++j) {
if (scanner.hasNextInt()) {
matrix[i][j] = scanner.nextInt();
}
}
}
}
private static void displayMatrix(final int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(final String... args) throws FileNotFoundException {
final Scanner scanner = new Scanner(new File("input.txt"));
final int n1 = scanner.nextInt();
final int n2 = scanner.nextInt();
System.out.print(String.format("The matrix is %d x %d \n", n1, n2));
final int[][] firstMatrix = new int[n1][n2];
final int[][] secondMatrix = new int[n1][n2];
System.out.println("Reading data to first matrix");
readMatrix(scanner, firstMatrix);
System.out.println("Reading data to second matrix");
readMatrix(scanner, secondMatrix);
System.out.println("First Matrix");
displayMatrix(firstMatrix);
System.out.println("Second Matrix");
displayMatrix(secondMatrix);
}
}
for(int i = 0; i < n1*n1; i++)
{
for(int j = 0; j < n2*n2; j++)
{
if(fileInput.hasNextInt())
{
if(i < n1){
firstMatrix[i][j] = fileInput.nextInt();
}
else
{
secondMatrix[i][j] = fileInput.nextInt();
}
}
}
}
You have two matrix of size n*n so you can do like this:

Array Index out of bounds exception, when I run this, I am not able to figure out why. I am not able to view the sorted array [duplicate]

This question already has answers here:
What is a stack trace, and how can I use it to debug my application errors?
(7 answers)
Closed 7 years ago.
import java.util.Scanner;
public class Sort {
public void Countsort(int a[], int b[], int k) throws ArrayIndexOutOfBoundsException {
int[] c = new int[k + 1];
for (int i = 0; i < k; i++) {
c[i] = 0;
}
for (int i = 0; i <= a.length; i++) {
c[a[i]] = c[a[i]] + 1;
}
for (int i = 1; i <= k; i++) {
c[i] = c[i] + c[i - 1];
}
for (int i = a.length; i <= 1; i--) {
b[c[a[i]]] = a[i];
c[a[i]] = c[a[i]] - 1;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num;
int[] temp = new int[10000];
int i = 0;
while (sc.hasNextInt()) {
num = sc.nextInt();
temp[i] = num;
i++;
if (num == -1) {
break;
}
}
int A[] = new int[i];
// just a check
for (i = 0; i < temp.length; i++) {
System.out.println("temp values:" + temp[i]);
}
// just a check ends
for (int j = 0; j < A.length; j++) {
A[j] = temp[j];
System.out.println("tem copied vals:" + A[j]);
}
// a check for gthat a has temp values..
int[] B = new int[A.length];
new Sort().Countsort(A, B, 100);
for (i = 0; i < B.length; i++) {
System.out.println("Run count #" + i + " : " + B[i]);
}
}
}
First of all your while loop should be
while (sc.hasNextInt()) {
num = sc.nextInt();
if (num == -1) {
break;
}
// so that you can stop -1 to be stored
temp[i] = num;
i++;
}
Next thing is your loop
for (int i = 0; i < a.length; i++) { // always less than length of the array
c[a[i]] = c[a[i]] + 1;
}

Cannot get the addition to output [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Everything is good, but i just cant get the addition to show up? When I run the program it is blank when it comes to the addition of the matrixes part. Thanks in advance. BtW does anyone know how I would make this display right column justified?
public static void displayMatrixes(int[][] matrix1, int[][] matrix2, int[][] resultsMatrix) {
System.out.println("This is how i want it to output");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(matrix2[i][j]+ " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print(resultsMatrix[i][j]+ " ");
}
System.out.println();
}
)
This is my code
import java.util.Scanner;
public class MatrixAdd
{
public static void main(String arg[])
{
Scanner input = new Scanner(System.in);
int a[][]= new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0 ; i < 3 ; i++){
for (int j = 0; j<3 ; j++){
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
int[][] resultingMatrix = addMatrix(a, b);
}
public static int[][] addMatrix(int[][] a, int[][] b){
int[][] result = new int[a.length][a[0].length];
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++){
result[i][j]=a[i][j] + b[i][j];
}
}
for (int i = 0; i < a.length; i++) {
char plus = '+';
for (int j = 0; j < a[0].length; j++) {
System.out.print(" " + a[i][j]);
}
if (i == a.length / 2)
System.out.print(" " + plus + " ");
else {
System.out.print(" ");
}
for (int j = 0; j < b[0].length; j++) {
System.out.print(" " + b[i][j]);
}
if (i == a.length / 2)
System.out.print(" = ");
else {
System.out.print(" ");
}
for (int j = 0; j < result[0].length; j++) {
System.out.print(" " + " " + result[i][j]);
}
System.out.println();
}
return result;
}//end of add matrices
}//end of class
I doubt that the given program compiles. In this line: int[][] resultsMatrix = displayMatrixes(a, b); you are expecting an int[][], but in your method displayMatrixes you are not returning anything. You are also expecting a 3rd parameter which you are not passing.
Also, the displayMatrixes method has no return value, which since you are returning something at the end, you must have. Try it again like so:
public static void main(String arg[]) {
Scanner input = new Scanner(System.in);
int a[][] = new int[3][3];
int b[][] = new int[3][3];
int row, column;
System.out.println("\nEnter Matrix A: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
a[i][j] = input.nextInt();
}
}
System.out.println("\nEnter Matrix B: \n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
b[i][j] = input.nextInt();
}
}
System.out.println("\nMatrix A + Matrix B = Matrix C: \n");
displayMatrixes(a, b);
}
public static void displayMatrixes(int[][] a, int[][] b) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print("+ ");
for (int j = 0; j < 3; j++) {
System.out.print(b[i][j] + " ");
}
System.out.print("= ");
for (int j = 0; j < 3; j++) {
System.out.print((a[i][j] + b[i][j]) + " ");
}
System.out.println();
}
}
}
printf with The "%3d" specifier means a minimum width of three spaces, which, by default, will be right-justified.
for your right alignment question you can at http://alvinalexander.com/programming/printf-format-cheat-sheet

Reverse the rows of a 2d array

Yesterday I asked a very similar question and I kind of messed up with asking it.
I need to pass an array to a method and inside of that method I need to swap the rows around so if it's
1 2 3
3 2 1
2 1 3
it needs to be
3 2 1
1 2 3
3 1 2
With the code I have right now it swaps the last column to the first column spot correctly then it puts the column that's supposed to be last.
3 1 2
1 3 2
3 2 1
Also, it needs to stay a void because I need to be modifying the original array so I can't set it as a temp array but I can use a temp integer to store.
Here is the code I have right now that's sort of working
public static void reverseRows(int[][] inTwoDArray)
{
for (int row = 0; row < inTwoDArray.length; row++)
{
for (int col = 0; col < inTwoDArray[row].length; col++)
{
int tempHolder = inTwoDArray[row][col];
inTwoDArray[row][col] = inTwoDArray[row][inTwoDArray[0].length - 1];
inTwoDArray[row][inTwoDArray[0].length - 1] = tempHolder;
}
}
}
any help would be great, I'm running out of hair to pull out! Thanks!
First, how to reverse a single 1-D array:
for(int i = 0; i < array.length / 2; i++) {
int temp = array[i];
array[i] = array[array.length - i - 1];
array[array.length - i - 1] = temp;
}
Note that you must stop in half of your array or you would swap it twice (it would be the same one you started with).
Then put it in another for loop:
for(int j = 0; j < array.length; j++){
for(int i = 0; i < array[j].length / 2; i++) {
int temp = array[j][i];
array[j][i] = array[j][array[j].length - i - 1];
array[j][array[j].length - i - 1] = temp;
}
}
Another approach would be to use some library method such as from ArrayUtils#reverse():
ArrayUtils.reverse(array);
And then again put into a cycle:
for(int i = 0; i < array.length; i++){
ArrayUtils.reverse(array[i]);
}
I guess this the easiest approach, tried and tested
For instance, you have
1 2
3 4
and you want
2 1
4 3
You can reverse the loop, without any extra space or inbuilt function.
Solution:
for(int i =0;i<arr.length;i++) //arr.length=no of rows
{
for(int j = arr[i].length-1;j>=0;j--)//arr[i].length=no of col in a ith row
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
Not sure if I didn't confuse what array stores the rows and which one the columns.... but this should work (long time since I've done Java last, so be nice to me when spotting any errors please ^^):
public static void reverseRows(int[][] array)
{
for (int i = 0 ; i < array.length ; i++) { // for each row...
int[] reversed = new int[array[i].length]; // ... create a temporary array that will hold the reversed inner one ...
for(int j = 0 ; j < array[i].length ; j++) { // ... and for each column ...
reversed[reversed.length - 1 - j] = array[i][j]; // ... insert the current element at the mirrored position of our temporary array
}
array[i] = reversed; // finally use the reversed array as new row.
}
}
Java Code :-
import java.util.Scanner;
public class Rev_Two_D {
static int col;
static int row;
static int[][] trans_arr = new int[col][row];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
row = m;
int n = sc.nextInt();
col = n;
int[][] arr = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
arr[i][j] = sc.nextInt();
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
for (int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr[j].length / 2; i++) {
int temp = arr[j][i];
arr[j][i] = arr[j][arr[j].length - i - 1];
arr[j][arr[j].length - i - 1] = temp;
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Reverse of two D array - Print your two D array in reverse order
public void reverse(){
int row = 3;
int col = 3;
int[][] arr = new int[row][col];
int k=0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++,k++) {
arr[i][j] = k;
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int i = arr.length -1; i >=0 ; i--) {
for (int j = arr.length -1; j >=0 ; j--) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
int [][] a={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a.length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
System.out.println("***************************");
for(int i=0 ; i<a.length;i++)
{
for(int j=a.length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
}
Reverse 2 D Array
public static void main(String[] args) {
int a[][] = {{1,2,3},
{4,5,6},
{8,9,10,12,15}
};
for(int i=0 ; i<a.length;i++)
{
for(int j=0 ; j<a[i].length;j++)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}
for(int i=0 ; i<a.length;i++)
{
for(int j=a[i].length-1 ; j>=0;j--)
{
System.out.print(a[i][j]+",");
}
System.out.println();
}

Categories

Resources