-3

Say, if I have a 2D array:

int[][] s = {{1, 4, 5, 10, 11}, {2, 6, 8}, {3, 9, 12}, {7}}; 

and I want to write a method that makes sure the next row has a shorter length than the rest of the array how would I go about doing so?

Basically how would I write a method that returns true if no row is longer than a preceding row, and false otherwise?

Here is my logic even though I'm far off, just don't understand logically how to go about it I guess.

 public static boolean rowDecrease(int[][] t){
     //result empty array here
     for (int j = 0; j < t.length; j++) {
      for (int i = 0; i< t[i].length; i++) { // Sum of Columns
        if (t[i].length>result){
          result = t[i].length;
          return false;
        }
        if (t[i].length<result){
          result = t[i].length;
          return true;
        }


        }

      }

3 Answers3

0

I think that a code similar to this would resolve your question:

boolean resultado = true;

for(int i = 1; i < s.length; i++){
    if(s[i].length >= s[i-1].length) return false;
}

return true;
Wakachopo
  • 149
  • 7
0

Please make an attempt or present a problem with existing code before posting in the future. We'll have to start sending you invoices otherwise.

public boolean shorterThanTheRest(int[][] s){
    int shortestLength = s[0].length + 1;
    for(int i = 0; i < s.length; i++)
        if(s[i].length < shortestLength)
            shortestLength = s[i].length;
        else
            return false;
     return true;
}
Zulfe
  • 820
  • 7
  • 25
  • Buddy, couldn't this have been somewhat simpler? Like, maybe at each index `i`, check if the length of the previous index `i-1` is greater than or equal. If not, return `false`. Return `true` outside the loop. – Debosmit Ray Apr 07 '16 at 06:55
  • @DebosmitRay I realized that after I had posted it; however, since another user posted the more simple method you described, I left my answer up just to show that it can be approached differently. But yes, since the criteria is to determine if the length of rows is continuously decreasing, your method is best. – Zulfe Apr 07 '16 at 06:58
  • Haha, I just saw that post. I see what you are saying, @Zulfe. :) – Debosmit Ray Apr 07 '16 at 07:00
0

You could do this using Java Stream:

int[][] s = {{1, 4, 5, 10, 11}, {2, 6, 8}, {3, 9, 12}, {7}};
List<Integer> S = Arrays.stream(s).map(i->i.length).collect(Collectors.toList());
boolean is = IntStream.range(0, S.size()).skip(1).allMatch(i->S.get(i)<=S.get(i-1));

I hope it helps.

Gyanendra Dwivedi
  • 5,511
  • 2
  • 27
  • 53
joel314
  • 1,060
  • 1
  • 8
  • 22