Win a copy of Java Challengers this week in the Java in General forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Paul Clapham
• Ron McLeod
• paul wheaton
• Devaka Cooray
Sheriffs:
• Jeanne Boyarsky
• Tim Cooke
• Liutauras Vilda
Saloon Keepers:
• Tim Moores
• Tim Holloway
• Stephan van Hulst
• Carey Brown
• Piet Souris
Bartenders:
• salvin francis
• Mikalai Zaikin
• Himai Minh

# How to do this HackerRank question - 2D array ?

Ranch Hand
Posts: 744
• Number of slices to send:
Optional 'thank-you' note:
I have problem in getting hang on how to make the array read every hour glass as it moves thru the grid of 6 x 6.

Day 11: 2D Arrays
Objective
Today, we're building on our knowledge of Arrays by adding another dimension. Check out the Tutorial
tab for learning materials and an instructional video!
Context
Given a 2D Array , :
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We define an hourglass in to be a subset of values with indices falling in this pattern in 's graphical
representation:
a b c
d
e f g
There are hourglasses in , and an hourglass sum is the sum of an hourglass' values.
Calculate the hourglass sum for every hourglass in , then print the maximum hourglass sum.
Input Format
There are lines of input, where each line contains space-separated integers describing 2D Array ;
every value in will be in the inclusive range of to .
Constraints
Output Format
Print the largest (maximum) hourglass sum found in .
Sample Input
1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0
Sample Output
19
Explanation
contains the following hourglasses:
1 1 1 1 1 0 1 0 0 0 0 0
1 0 0 0
1 1 1 1 1 0 1 0 0 0 0 0
0 1 0 1 0 0 0 0 0 0 0 0
1 1 0 0
0 0 2 0 2 4 2 4 4 4 4 0
1 1 1 1 1 0 1 0 0 0 0 0
0 2 4 4
0 0 0 0 0 2 0 2 0 2 0 0
0 0 2 0 2 4 2 4 4 4 4 0
0 0 2 0
0 0 1 0 1 2 1 2 4 2 4 0
The hourglass with the maximum sum ( ) is:
2 4 4
2
1 2 4

And what I have attempted so far:

I am aslo very confused how to use the scanner thing....

Hope someone can point out my mistake and gives me some tips how to do this question.
Tks.

Saloon Keeper
Posts: 8095
71
• Number of slices to send:
Optional 'thank-you' note:
First thing I would do is create a method that does nothing but read and load a 2D array and return it. You should not need all that skip stuff you've got. Only when you've gotten that to work correctly would I attempt the next step of processing the arrays.

There doesn't seem to be anything in the requirements that states that the input will be a 6x6 array-of-arrays. Is there a requirement that states all rows will be the same length?

Your 'i' and 'j' loops go completely from left to right and top to bottom without taking the size of the hour glass into account. For example, if 'i' is array[0].size-1 then the hour glass falls outside of the array bounds.

Carey Brown
Saloon Keeper
Posts: 8095
71
• Number of slices to send:
Optional 'thank-you' note:
Note that the formatting had been stripped out of the requirements. The hour glass pattern is:

Rancher
Posts: 961
23
• Number of slices to send:
Optional 'thank-you' note:
tangara,

I would think the fist thing you need to figure out is:  how do you want to model the outliers for your hourglass patter?  if you look at (n, 1) you see that the hourglass would not fit in the matrix, as is true on all (k, n) entries in the array.  How do you handle them?  do you assume a spherical world and count from the far side of the matrix, or do you make special scanning for them, or do you just exclude them?

This is a problem whenever you try to overlay scanning patterns onto a flat sample set.

Les

tangara goh
Ranch Hand
Posts: 744
• Number of slices to send:
Optional 'thank-you' note:

Carey Brown wrote:Note that the formatting had been stripped out of the requirements. The hour glass pattern is:

Yes. Carey.  My problem is that the question has stated a bigger grid - with 6 x 6.  So, my problem is how to make it perform the iteration over the figure you just pointed out and then move on the same iteration over and then compare the sum of each hour glass comparision.

Anyway, I already spent 2 weeks (so long right) on this question and I check out the tutorial on you tube.
Great that I did so because I thought that we are not allowed to write LeetCode kind of method and then this scanner thing really I just can't get the hang of it.

So, there is this nick white you tube his explanation is really good.
But, he is using BufferWriter and I have to see another one that uses Scanner class.

Still, when I run the code on HackerRank site, it is giving me error.

Can you let me know what is wrong with that line - System.out.println(temp);  why it is giving me error - Solution.java:42: error: <identifier> expected
System.out.println(temp);

not sure what is identifier...

And any other errors you can spot ...

Thank you guys.

Saloon Keeper
Posts: 4380
163
• Number of slices to send:
Optional 'thank-you' note:
First of all: knowing HR a little, you only need to implement the 'hourGlassSum' method, with a given 2D array as input. So you don't have to worry about reading in that 2D array, it is done for you.

Look at the line where you calculate the sum of an hourglass: are the indices correct? You should only have one term with arr[i + 1].

And finally: in line 38 you calculate the hourGlassSum. But look at line 42. What variable should you print there?

Carey Brown
Saloon Keeper
Posts: 8095
71
• Number of slices to send:
Optional 'thank-you' note:
I still see the magic number '6', and now a new magic number '4', where did they come from? I don't see them in the requirements.

Piet Souris
Saloon Keeper
Posts: 4380
163
• Number of slices to send:
Optional 'thank-you' note:
The 6x6 is given. But as I said, OP must ony implement the hourGlassSum method.

See here: exercise

tangara goh
Ranch Hand
Posts: 744
• Number of slices to send:
Optional 'thank-you' note:

Carey Brown wrote:I still see the magic number '6', and now a new magic number '4', where did they come from? I don't see them in the requirements.

I put in 6 because I do not want to specify the row and column and 4 because the 2 is the offset.  This is of course not good coding practice but I just want to see if the whole thing works or not.

tangara goh
Ranch Hand
Posts: 744
• Number of slices to send:
Optional 'thank-you' note:

Piet Souris wrote:The 6x6 is given. But as I said, OP must ony implement the hourGlassSum method.

See here: exercise

I noticed the arrays the array[row][column] some of them in the hourGlassSum method is wrong.  But, I really doubt I can do it if given this kind of questions again. cos I can't remember the row and column thing if I were to have to take a coding test in an interview.

Still I did not pass test 3 and 7.

Hope someone can tell me what have I been missing.
Tks.

Piet Souris
Saloon Keeper
Posts: 4380
163
• Number of slices to send:
Optional 'thank-you' note:
Why do you have that static variable 'temp'? Ditch it, because it is not needed. You can return 'max', and print 'result'. Maybe one of the tests had only zeros as input, in which case you now return the static value of temp.

Piet Souris
Saloon Keeper
Posts: 4380
163
• Number of slices to send:
Optional 'thank-you' note:
Forgot to mention: if negative elements are allowed in the array, then starting with 'sum = 0' and 'max = 0' may not be ideal.

Ranch Hand
Posts: 80
3
• 1
• Number of slices to send:
Optional 'thank-you' note:
May I throw in: There's no such thing as multi-dimensional arrays - at least not in Java.

Well - that's not a 2D array - it's just an array of int (or bool?) arrays.

In Java, if you declare an array such as String[][][] this only tells the compiler: "Hey, compiler, look, this is an array of String[][] - and that one level deeper it's an array of String[] - and at the lowest level it's an array of String" - but that doesn't mean it's a "three dimensional" array - it only means it's an array of arrays of String arrays. That's it.

A "multi dimensional" array would mean each "dimension" has a fixed size - that's not how arrays work in Java. If you have a String array you basically have an array of char arrays (or more precise: an array of CharSequences implemented and backed up by simple char arrays). Does that mean you can only have Strings with the same size in that array? No! You can have a 3 char String right next to a 300 String - it doesn't matter. Let us go up one level: Does any lower level array has to contain the same number of Strings? Nope - one sub-array can only contain 3 Strings - the next one maybe 30. I guess you get the point.

The closest a "multi dimensional array" in Java comes to a "List of Lists" with no fixed sizes in the lower levels. It just doesn't matter how many entries one list has and it doesn't matter if several lists contain different numbers of entries - you can still collect them together in an upper-level list (as long as the types match). The same is true for arrays. And as, at least to my knowledge, ArrayList is one of most used List implementation many rely on how arrays work every day - no matter if using arrays directly or hide them away in an ArrayList.

Carey Brown
Saloon Keeper
Posts: 8095
71
• Number of slices to send:
Optional 'thank-you' note:

Piet Souris wrote:Forgot to mention: if negative elements are allowed in the array, then starting with 'sum = 0' and 'max = 0' may not be ideal.

Sum=0 should be OK but max should be max=Integer.MIN_VALUE.

tangara goh
Ranch Hand
Posts: 744
• Number of slices to send:
Optional 'thank-you' note:

Carey Brown wrote:

Piet Souris wrote:Forgot to mention: if negative elements are allowed in the array, then starting with 'sum = 0' and 'max = 0' may not be ideal.

Sum=0 should be OK but max should be max=Integer.MIN_VALUE.

Hi guys,

I changed some code, as the you tube video guy said have to take into consideration of the constraint - -63 but after I put that in it is not giving me the right output 19.

Hope you guys can help me spot my mistakes.

Carey Brown
Saloon Keeper
Posts: 8095
71
• 1
• Number of slices to send:
Optional 'thank-you' note:
I thought you were supposed to return the greatest sum, like this? The comments on this code were twofold: 1) all you need is the max variable, get rid of temp, and 2) initialize max to Integer.MIN_VALUE (I think that's how it's spelled).

tangara goh
Ranch Hand
Posts: 744
• Number of slices to send:
Optional 'thank-you' note:
It works !!! Now I got all the tests passed.  Thanks.
But, I do not understand why using initialize max to Integer.MIN_VALUE instead of initialize max to 0 will work ? (My lack of CS degree...sob sob)

Piet Souris
Saloon Keeper
Posts: 4380
163
• Number of slices to send:
Optional 'thank-you' note:
I think one of the constraints is that -9 <= array elements <= ?.

If you have an array filled with -9s, then all your sums will be -63. Setting max to 0 initially will therefore never adjust max (since no sum > max), and so you return 0. Initializing max to MIN_VALUE (or -63) fixes that..

Carey Brown
Saloon Keeper
Posts: 8095
71
• 1
• Number of slices to send:
Optional 'thank-you' note:
The reason for MIN_VALUE is that your problem allows negative values. In a worst case, lets say that ALL the values were negative. If you had initialized max to zero then none of the sums would ever be greater than zero so max wouldn't get set properly. By setting max to MIN_VALUE then any sum must be greater than max the first time round the loop.

Marshal
Posts: 72657
317
• Number of slices to send:
Optional 'thank-you' note:
An alternative is to set max to the first element in the array; that works very badly if you happen to pass a 0‑length array

Piet Souris
Saloon Keeper
Posts: 4380
163
• Number of slices to send:
Optional 'thank-you' note:
Don't worry: that 2D array (of arrays) is guaranteed 6x6

 Don't get me started about those stupid light bulbs.