Note that there are some explanatory texts on larger screens.

plurals
  1. POjava- "-1" position
    primarykey
    data
    text
    <p>I have this question:</p> <p>The method accepts an integer array as its input and returns a new array which is a permutation of the input array. The method fix34 rearranges the input array such that every 3 is immediately followed by a 4 (e.g. if there is a 3 at position i, there will be a 4 at position i+1). The method keeps the original positions of the 3s but may move any other number, moving the minimal amount of numbers. Assumptions regarding the input: </p> <ul> <li>The array contains the same number of 3's and 4's (for every 3 there is a 4)</li> <li>There are no two consecutive 3s in the array</li> <li>The matching 4 for a 3 at some position i is at position j where j > i </li> </ul> <p>ok, so this is what I wrote:</p> <pre><code>public class Fix34 { public static void main(String[] args){ int [] args1 ={3,1,2,3,5,4,4}; int[] args11=fix34(args1); for (int i = 0; i&lt;=args11.length-1;i++ ){ System.out.print(args11[i]+" ");}} public static int pos (int[] arr){ int i= arr.length-1; while (arr[i]!=4){ i=-1; } return i; } public static int[] fix34(int[] nums){ for(int i = 0; i&lt;=nums.length-1; i++){ if (nums[i] == 3){ nums[pos(nums)]=nums[i+1]; nums[i+1]=4; } } return nums; } } </code></pre> <p>when I insert arrays such {3,2,1,4} it works, but with the array as written in the code, it gives me the error message:</p> <pre><code>Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at Fix34.pos(Fix34.java:15) at Fix34.fix34(Fix34.java:25) at Fix34.main(Fix34.java:6) </code></pre> <p>how come the arrays gets to -1 position?!</p> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload