Home > Software design >  How to create new array without elements in certain range?
How to create new array without elements in certain range?

Time:03-17

So I have a first and last variable which is the starting and ending markers that I want to get rid of. So the starting input for example would be [5, 10, 15, 20, 25] And say first = 1 and last = 3. The would mean that the elements 10, 15, and 20 would not be included in the new array since they are at the indexes between 1-3, inclusive, so that new array without those nums would be the output. Here's what I have so far:

int [] newArr = new int[arr.length - (last - first) - 1];
for (int i = 0; i < newArr.length; i  ) {
     if (i < first || i > last) {
          newArr[i] = arr[i];
     }
} 

They're just changing to 0's, and for some reason I can't think of what to do next.

CodePudding user response:

The simplest approach is probably just to keep track of a separate index for where you are inserting elements into the new array.

int [] newArr = new int[arr.length - (last - first) - 1];
for (int i = 0, j = 0; i < arr.length; i  ) {
     if (i < first || i > last) {
          newArr[j  ] = arr[i];
     }
} 

CodePudding user response:

    int [] newArr = new int[arr.length - (last - first) - 1];
    
    int count = 0;
    
    for (int i = 0; i < arr.length; i  ) {
         if (i < first || i > last) {
              newArr[count] = arr[i];
              count  ;
         }
         
    }

The code you posted isn't working because newArr can't use i as the array index. Easiest way is to introduce a new count variable for this.

CodePudding user response:

Arrays.copyOfRange

The utility class Arrays can help with your chore. The copyOfRange method gives you a subset of elements.

int[] inputs = { 5 , 10 , 15 , 20 , 25 };
int first = 1, last = 3; // Inclusive (fully-closed).

int[] leading = Arrays.copyOfRange( inputs , 0 , first );
int[] trailing = Arrays.copyOfRange( inputs , last   1 , inputs.length );

Dump to console.

System.out.println( "leading = "   Arrays.toString( leading ) );
System.out.println( "trailing = "   Arrays.toString( trailing ) );

leading = [5]

trailing = [25]

You could concatenate these two arrays in various ways.

My own choice in modern Java would use streams (IntStream) for brevity. If doing much of this, you might want to compare alternatives for performance.

int[] result =
        IntStream.concat(
                        Arrays.stream( leading ) ,
                        Arrays.stream( trailing )
                )
                .toArray();

Dump to console.

System.out.println( "result = "   Arrays.toString( result ) );

result = [5, 25]

  •  Tags:  
  • java
  • Related