开发者

bin 2D arrays in java

I have an interes开发者_JS百科ting problem. I have an 2D array of say n elements. i want to create a function that "bins" the array elements according to a number. Given

String [][] theArray = 
            {
             {"word1", "3.5"},
             {"word2", "2.4"},
             {"word3", "1.2"},
             {"word4", "0.5"},
             {"word5", "0.2"}
            };

If the "binning" number were 1 then theArray would be the same. If the "binning" number were 2 then theArray would become

newArray ={{"word1 word2", "5.9"},{"word3 word4", "1.7"},{"word5", "0.2"}}

Notice that the first element of each subarray is the concatenation of the first elements of the original array. The second element of each subarray is the addition of the second elements of the original array.

Also, if the mod of theArray.length/"binning" number is greater than 0 the number of elements of the new array should be (theArray.length/"binning" number)+1. The last element should be the binning of the remaining elements.

I tried to do something like this

public String [][] binArray(String [][]theArray, int theBinningNumber)
{
 //here i would do some nested loops, but to be honest with you guys, all my trials were
 //far from succesful
}

Thanks so much for your help


Please have a look at this sample,

public static void main(String []args)
   {
   String [][] theArray = 
            {
             {"word1", "3.5"},
             {"word2", "2.4"},
             {"word3", "1.2"},
             {"word4", "0.5"},
             {"word5", "0.2"}
            };

    String newArray[][]=binArray(theArray,2);
    for(String []ar : newArray)
     {
       System.out.println(ar[0] + " " + ar[1]);
     }
   }

   public static String [][]binArray(String [][]theArray,int theBinningNumber)
   {
    //Determine the size (length) of new array
    int newSize=theArray.length/theBinningNumber;
    if(theArray.length % theBinningNumber !=0)
       {
       newSize++;
       }

     //Define new array 
     String [][]newArray=new String[newSize][];
     int theNewIndex=0;

     for(int index=0;index<theArray.length;index+=theBinningNumber)
      {
          String []ar=new String[] {"",""};  
          double value=0;
          for(int binIndex=index;
                   binIndex<(index+theBinningNumber) 
                            && binIndex<theArray.length;
                                            binIndex++)
           {
               value = value + Double.parseDouble(theArray[binIndex][1]);
               ar[0]=ar[0] + " " + theArray[binIndex][0];
               ar[1]=String.valueOf(value);
            }
          newArray[theNewIndex++]=ar;
       }
      return newArray;        
   }  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜