How can I cut a section of an array in java

I have to write a method in java, where having in input an array “a” of numbers and a number “x” returns an array of elements which follows the last occorence of “x ” in “a”. For example with input {0,1,2,3,4,5,6,7,8,9} and x=6 the method must return {7,8,9} meanwhile with {4,1,4,2} and x =4 the method must return {2} and if the x is not in “a” then it must return empty array {} (or array with 0 length)

so far we haven’t study classes or objects .here an example of another program we made so far

boolean arrayIncluso( int[] s,int[] t ) {

boolean flag=true;
for(int i=0;i< s.length;i++){
    int c1 = 0 ;
int c2 = 0 ;
    for(int j=0;j< s.length;j++){
        if(s[i] == s[j]){
            c1 ++;
        }
    }

    for(int j=0;j< t.length;j++){
        if(s[i] == t[j]){
            c2 ++;
        }
    }

    if(c1 > c2)

    flag= false; 
}
return flag;
}

can someone explain to me why this

t[i-idx-1 ] = s[i];

instead of this

     for(int j=0;j<t.length;j++){
     t[j]=a[i];
}
return t;

Answer

You can split the problem into two parts:

  1. Find last index of the character x. This can be done using an easy for loop.

    int idx = -1;
    for (int i = 0; i < s.length; i++) { 
        if (s[i] == x) idx = i;
    }
    
  2. After you found this index, create a new array starting from this element. It can be done with a second (not nested) for loop, or you can use Arrays.copyOfRange()

    //make sure idx != -1
    int[] t = new int[s.length - idx - 1];
    for (int i = idx+1; i < s.length; i++)
        t[i-idx-1 ] = s[i];
    System.out.println(Arrays.toString(t)); //print to make sure it's all fine
    

OR

    t = Arrays.copyOfRange(s, idx+1, s.length);
    System.out.println(Arrays.toString(t));

Leave a Reply

Your email address will not be published. Required fields are marked *