3

In my code, I get an output of an array but it displays some unwanted zeros after getting the array, Can you explain a way to avoid getting these unwanted zeros.

 static int[] cutTheSticks(int[] arr) {
 int min,i,j,count=0;
 int []arr2=Arrays.copyOf(arr,arr.length);
 int []temp =Arrays.copyOf(arr,arr.length);


    for(i=0;i<arr.length;i++){
        Arrays.sort(arr2);
        min= arr2[0];
        for(j=0;j<arr.length;j++){

            if(temp[j]>0){
                count++;
            }
            temp[j]=temp[j]-min;

        }
        int []res = new int [arr.length];
        while(count!=0) {
            res[i] = count;
            count = 0;

    }
    return res;



  }
Pulsara Sandeepa
  • 915
  • 10
  • 25
  • Check this https://stackoverflow.com/questions/14984664/remove-trailing-zero-in-java – Trishul Singh Choudhary Feb 27 '20 at 03:11
  • Could you be a bit more precise about which zeros are unwanted? An example showing the input, actual result and desired result would be helpful. – Kevin Anderson Feb 27 '20 at 03:15
  • If I input 6 integers as input 5 4 4 2 2 8, I want the output like 6 4 2 1 but I get the output as 6 4 2 1 0 0, It always displays extra zeros as result array size equals to the input number. – Pulsara Sandeepa Feb 27 '20 at 03:25
  • You are doing this wrong. You keep using (and thus sorting) the original array. But you are taking cuts from a copy. You are supposed to re-sort to calculate the new smallest stick so you can apply that to subsequent cuts. Also, this would be much easier to do using `Lists`. But if you can't I recommend you write some helper methods to manipulate the array(s). – WJS Feb 27 '20 at 03:34
  • Never put more information into comments, always update your question instead. So that it includes that "expected" vs "actual" output right from the start! – GhostCat Feb 27 '20 at 12:59

1 Answers1

2

You can figure the "size" of res without its trailing zeros with:

int rlen = res.length;
while (res[rlen-1] == 0) {
    --rlen;
}

If you wish, you can then use the calculated "effective length" rlen to reallocate the res array at the correct size:

res = Arrays.copyOf(res, rlen);

Or just use rlen instead of res.length when you need to know the "correct" size of res.

Draken
  • 3,134
  • 13
  • 34
  • 54
Kevin Anderson
  • 4,568
  • 3
  • 13
  • 21