Mike
Mike

Reputation: 2339

Getting the min and max of sections of an array

I have a 2 dimensional array of strings and I would like to find the max of every 13 elements.

The array is array[String date][String price1][String price2]. I would like the max of price1 0-12, then price1 1-13, then price1 2-14, etc

{1,2,3,4,5,6,7,8,9,10,9,8,11,6,5,4,3,2,1}

the first list of 13 {1,2,3,4,5,6,7,8,9,10,9,8,7} would return 10

the second list of 13 {2,3,4,5,6,7,8,9,10,9,8,7,11} would return 11

the third list of 13 {3,4,5,6,7,8,9,10,9,8,7,11,6} would return 11 etc

edit sorry that was a bit confusing, the array is a 2 dimensional array of strings, the first column being dates, and the second and third being doubles. I would like to find the max of the 2nd column and the min of the 3rd.

here is what i had gotten:

    String str = "";

    for(int ii = 1 ; ii < array.length ; ii++){
        str = str+array[ii][2]+",";

        if(ii==13){

            str = Math.max(str.substring(0, str.lastIndexOf(',', str.lastIndexOf(',') - 1)));

            System.out.println(str);
        }
    }

Upvotes: 1

Views: 407

Answers (2)

gtiwari333
gtiwari333

Reputation: 25156

Here is my solution(If you are dealing with integer array).

BUT you are saying [String date][String price1][String price2] at first and

later you gave example : the first list of 13 {1,2,3,4,5,6,7,8,9,10,9,8,7} would return 10 the second list of 13 {2,3,4,5,6,7,8,9,10,9,8,7,11} would return 11 the third list of 13 {3,4,5,6,7,8,9,10,9,8,7,11,6} would return 11 etc Please be clear about that.

CODE:

public class SO_MinMaxArrayGroups {
    public static void main(String[] args) {
        int arr[] = new int[] { 1, 2, -3, 4, 5, 6, 17, 13, 14, 14, 14, 12, 1, 2, 2, 4, 3, 4,1, 2, 3, 4, 5, 6, 12, 13, -14, 14, 14, 12, 1, 2, 2, 4, 3, 4,1,4,7 };
        for (int i = 0; i < 3; i++) {
            int max = arr[13*i];
            int min = arr[13*i];
            for (int j = i * 13; j < (i + 1) * 13; j++) {
                //System.out.println("Checking :" + arr[j]);
                if (arr[j] > max) {
                    max = arr[j];
                }
                if (arr[j] < min) {
                    min = arr[j];
                }
            }
            System.out.println("Secion :"+(i+1)+"  Max : " + max + " Min : " + min);
        }
    }
}

Result:

Secion :1  Max : 17 Min : -3
Secion :2  Max : 13 Min : 1
Secion :3  Max : 14 Min : -14

Upvotes: 1

aishwarya
aishwarya

Reputation: 1986

if you are dealing with numbers, the array shouldn't be storing strings (comparison gets tricky between 1,11 and 2 ( '2' > '11' ) :-)

you can copy ranges into another array and create a treeset out of the ranges, which can be used to extract the min and max numbers.

HTH!

Upvotes: 0

Related Questions