Loop runs 2 times, then Array index out of bounds exception - java

I'm making a class that deletes an element at a specific position in an Integer array. It runs perfectly the first 2 times, but then for some reason it decides that the ArrayIndexOutOfBoundsException should be thrown.
my code:
public class Arraydeletion {
public static int[] delete (int[] a, int delValPos){
int[] newArray = new int[a.length-1];
for (int i = 0; i < newArray.length; i++) {
if(a[i]!=a[delValPos]){ //<--- ArrayIndexOutOfBoundsException points here
newArray[i] = a[i];
}
else if(a[i] == a[delValPos]){
newArray[i] = a[delValPos+=1];
}
}
return newArray;
}
}

You never check that delValPos is a valid index within the input array a. Your method must validate it before doing anything else, and throw an exception if an invalid delValPos is supplied.
Working code would look like this :
public class Arraydeletion {
public static int[] delete (int[] a, int delValPos){
if (delValPos < 0 || delValPos >= a.length)
throw new SomeException(); // TODO decide which exception to throw
int[] newArray = new int[a.length-1];
int index = 0;
for (int i = 0; i < a.length; i++) {
if (i!=delValPos) {
newArray[index] = a[i];
index++;
}
}
return newArray;
}
}
This makes the code much simpler. It copies all the elements except a[delValPos] to the output array. Note that you can't use the same index i for reading elements from the input array and writing elements to the output array, because after you pass the deleted element, each i'th element in the input array would be written to the (i-1)'th place in the output array.

I tested your code and i retrieve outOfBoundException only if delValPos == a.length, so you can check this before loop.
However your code is pretty strange, it seems you want to clone an array except for one element in a certain position, if so this will work better:
public static int[] delete (int[] a, int delValPos){
int delValPos = 0;
int[] a = {1,2,3,4,5,6,7,8,9};
int[] newA = new int[a.length - 1];
if(a.length > delValPos) {
for(int i = 0 ; i < newA.length ; i++) {
if(delValPos < i && delValPos != 0) {
newA[i] = a[i];
}
else
newA[i] = a[i + 1];
}
}
return newA;
}

Related

Remove an Element in Array on Leet code. I am getting an error of getting incompatible types and I dont know whats wrong

Here is the question:
Given an integer array nums and an integer val, remove all
occurrences of val in nums in place. The relative order of the
elements may be changed.
Since it is impossible to change the length of the array in some
languages, you must instead have the result be placed in the first
part of the array nums.
More formally, if there are k elements after removing the duplicates,
then the first k elements of nums should hold the final result. It
does not matter what you leave beyond the first k elements.
Return k after placing the final result in the first k slots of
nums.
Do not allocate extra space for another array. You must do this by
modifying the input array in-place with O(1) extra memory.
I've tried to remove the given target val by shifting the value to the end of the array index by iteration of nums.length-1 every time the val is found in the given array. I just want to know what's wrong with my approach.
Below is the code I've tried:
class Solution {
public int removeElement(int[] nums, int val) {
for (int i = 0; i < nums.length; i++) {
if (val == nums[i]) {
for (int j = i; j < nums.length - 1; j++) {
nums[j + 1] = nums[j];
}
break;
}
}
return nums;
}
}
Your algorithm correctly would be the following. The error was returning the array, but that was changed in-situ. You should have returned the new reduced length.
public int removeElement(int[] nums, int val) {
int k = nums.length;
for (int i = 0; i < k; i++) {
if (val == nums[i]) {
--k;
//for (int j = i; i < k; j++) {
// nums[j] = nums[j + 1];
//}
System.arraycopy(nums, i+1, nums, i, k-i);
--i; // Check the new nums[i] too
}
}
return k;
}
The for-j loop can be replaced with System.arraycopy (which handles overlapping of the same array too).
Or:
public int removeElement(int[] nums, int val) {
int k = 0;
for (int i = 0; i < n; i++) {
if (val != nums[i]) {
nums[k] = nums[i];
++k;
}
}
return k;
}
This is my code in leetcode. Hope will help you
class Solution {
public int removeElement(int[] nums, int val) {
ArrayList<Integer> list = new ArrayList<>();
for(int i=0;i<nums.length;i++){
if(nums[i]!=val){
list.add(nums[i]);
}
}
for(int i=0;i<list.size();i++){
nums[i]= list.get(i);
}
return list.size();
}
}

How to return an array with the indexes of a certain int from another array

I'm a beginner Java student and I have been trying to write a method that lists all indexes of a certain int within an array. What I've done so far is store the value of that int at its corresponding index within another array but the best I can do is set the values of all other indexes that are not equal to the original int to -1.
I think I need to store the value i within the array and delete all the -1s but I don't know how to do this. By the way, these values are -1 because all my arrays in this program contain ints that are between 0-100. What would I do if possible ints within this array could be any number?
Also surely there is an easier or more efficient way of doing this.
public static int[] maxValueIndex(int[] arr, int targetValue, int x) {
int[] maxValue = new int[x];
for (int i = 0; i < arr.length; i++) {
if (arr[i] == targetValue) {
maxValue[i] = arr[i];
} else {
maxValue[i] = -1;
}
}
return maxValue;
}
If I understood your query correctly then you want an array with all the indices i such that arr[i]==targetValue. We can achieve this efficiently using any dynamic data structure. Like, use an ArrayList and keep adding all the desired indices one by one then convert the List to an array and return it.
Something like this:
List<Integer> index = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == targetValue)
index.add( i );
}
int[] maxValue = index.stream().mapToInt(Integer::intValue).toArray();
return maxValue;
If it is required to use arrays only to resolve this task, it may take two passes to create a compacted array containing only valid indexes:
Find the number of matches, and then create and fill a compact array
public static int[] getTargetIndexes(int targetValue, int ... arr) {
int n = arr.length;
int targetCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == targetValue) {
targetCount++;
}
}
int[] indexes = new int[targetCount];
for (int i = 0, j = 0; j <targetCount && i < n; i++) {
if (arr[i] == targetValue) {
indexes[j++] = i;
}
}
return indexes;
}
Create an array of the same length, fill it and then compact by using Arrays.copyOf:
public static int[] getTargetIndexes(int targetValue, int ... arr) {
int n = arr.length;
int[] indexes = new int[n];
int targetCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == targetValue) {
indexes[i] = i;
targetCount++;
} else {
indexes[i] = -1;
}
}
for (int i = 0, j = 0; j < targetCount && i < n; i++) {
if (indexes[i] > -1) {
indexes[j++] = i;
}
}
return Arrays.copyOf(indexes, targetCount); // truncate bad indexes
}
Also, the signature of the method uses vararg to pass the input array as a sequence of int -- the vararg argument int ... arr should be the last one then.
If Stream API can be used, the task may be resolved conveniently in a declarative way:
public static int[] getTargetIndexes(int targetValue, int ... arr) {
return IntStream.range(0, arr.length) // get stream of indexes
.filter(i -> arr[i] == targetValue) // keep only matching indexes
.toArray(); // build output array
}

remove object from an array java

My practice problem says to"this method returns an array that has the elements of the specified
// array of Objects, with the Object at the specified index removed.
// the returned array should be smaller by one and have all elements
// in the same relative location to each other. YOU MAY NOT USE
// A LIST :)
Object[] remove(int index, Object[] arr){"
I have come up with this so far, and I'm not entirely sure it works. Can you guys please take a look and give me some feedback on how to fix it so I can do this "remove" properly.
public static remove(int index, Object[] arr){
int counter = 0;
int temp = 2;
int[] arr = {1, 2, 3, 4};
int[] second = new int[arr.length-1];
for(int i=0; i< arr.length;i++){
if(i != temp){
second[counter] = arr[i];
counter ++;
}
//return second;
}
public static Object[] remove(int index, Object[] array) {
Object[] newArray = new Object[array.length - 1];
for (int i = 0; i < array.length; i++) {
if (index > i) {
newArray[i] = array[i];
} else if(index < i) {
newArray[i - 1] = array[i];
}
}
return newArray;
}
You would have to copy over all elements, besides for the one at index, into a new array and return that.

How do I shift array elements up one position in java?

I am working on a java assignment where I need to delete an integer element in an array and shift the below elements up on space to keep them in order. The array is currently random integers in descending order. I am not allowed to use array.copy because I will need to collect array usage information as part of the assignment. I have tried a ton of different ways of doing this but cannot seem to get it working.
public static void deletionArray(int anArray[], int positionToDelete) {
for (int j = anArray[positionToDelete] - 1; j < anArray.length; j++) {
System.out.println("j is " + j);
anArray[j] = anArray[j + 1];
}
displayArray(anArray);
}
You're iterating until anArray.length (exclusive), but inside the loop, you're accessing anArray[j + 1], which will thus be equal to anArray[anArray.length] at the last iteration, which will cause an ArrayIndexOutOfBoundsException.
Iterate until anArray.length - 1 (exclusive), and decide what should be stored in the last element of the array instead of its previous value.
You're also starting at anArray[positionToDelete] - 1, instead of starting at positionToDelete.
You have two bugs there.
Since this is an assignment, I won't give a complete answer - just a hint. Your loop definition is wrong. Think about this: what happens on the first and on the last iteration of the loop? Imagine a 5-element array (numbered 0 to 4, as per Java rules), and work out the values of variables over iterations of the loop when you're erasing element number, say, 2.
Use System.arraycopy faster than a loop:
public static void deletionArray( int anArray[], int positionToDelete) {
System.arraycopy(anArray, positionToDelete + 1, anArray,
positionToDelete, anArray.length - positionToDelete - 1);
//anArray[length-1]=0; //you may clear the last element
}
public static int[] deletionArray(int anArray[], int positionToDelete) {
if (anArray.length == 0) {
throw new IlligalArgumentException("Error");
}
int[] ret = new int[anArray.length - 1];
int j = 0;
for (int i = 0; i < anArray.length; ++i) {
if (i != positionToDelete) {
ret[j] = anArray[i];
++j;
}
}
return ret;
}
Why do we reserve a new array?
Because if don't, we would use C\C++-style array: an array and a "used length" of it.
public static int deletionArray(int anArray[], int positionToDelete, int n) {
if (n == 0) {
throw new IlligalArgumentException("Error");
}
for (int i = positionToDelete; i < n - 1; ++i) {
anArray[i] = anArray[i + 1];
}
return n - 1; // the new length
}
How's this ? Please note the comment, I don't think you can delete an element in an array, just replace it with something else, this may be useful : Removing an element from an Array (Java)
Updated with 'JB Nizet' comment :
public class Driver {
public static void main (String args []){
int intArray[] = { 1,3,5,6,7,8};
int updatedArray[] = deletionArray(intArray , 3);
for (int j = 0; j < updatedArray.length; j++) {
System.out.println(updatedArray[j]);
}
}
public static int[] deletionArray(int anArray[], int positionToDelete) {
boolean isTrue = false;
for (int j = positionToDelete; j < anArray.length - 1; j++) {
if(j == positionToDelete || isTrue){
isTrue = true;
anArray[j] = anArray[j + 1];
}
}
anArray[anArray.length-1] = 0; //decide what value this should be or create a new array with just the array elements of length -> anArray.length-2
return anArray;
}
}

Creating a New Reverse Java Array

CodingBat > Java > Array-1 > reverse3:
Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.
public int[] reverse3(int[] nums) {
int[] values = new int[3];
for (int i = 0; i <= nums.length - 1; i++) {
for (int j = nums.length-1; j >= 0; j--) {
values[i] = nums[j];
}
}
return values;
}
I can't get this to work properly, usually the last int in the array, becomes every single int in the new array
You don't want a two-level loop. Just have one loop:
for(int i = 0, j = nums.length - 1; i < nums.length; i++,j--) {
values[i] = nums[j];
}
or, alternately, just don't track j sepearately, and do this:
for(int i = 0; i < nums.length; i++) {
values[i] = nums[nums.length - 1 - i];
}
Unless this is a homework, why not just use Apache ArrayUtils'
ArrayUtils.reverse(nums)
Never re-invent the wheel :)
The length of the input int[] is fixed at 3? Then it doesn't get any simpler than this.
public int[] reverse3(int[] nums) {
return new int[] { nums[2], nums[1], nums[0] };
}
See also:
CodingBat/Java/Array-1/reverse3
Note that Array-1 is "Basic array problems -- no loops." You can use a loop if you want, but it's designed NOT to be solved using loops.
Firstly, while creating new array give it size of old array.
Next, when you're reversing an array, you don't need two loops, just one:
int length = oldArray.length
for(int i = 0; i < length; i++)
{
newArray[length-i-1] = oldArray[i]
}
You only want a single loop, but with indices going both ways:
public int[] reverse(int[] nums) {
int[] back = new int[nums.length];
int i,j;
for (i=0,j=nums.length-1 ; i<nums.length ; i++,j--)
back[i] = nums[j];
return back;
}
public int[] reverse3(int[] nums) {
int rotate[]={nums[2],nums[1],nums[0]};
return rotate;
}
This code gives correct output:-
public int[] reverse3(int[] nums) {
int[] myArray=new int[3];
myArray[0]=nums[2];
myArray[1]=nums[1];
myArray[2]=nums[0];
return myArray;
}
I got this with Python.. So you can get the idea behind it
def reverse3(nums):
num = []
for i in range(len(nums)):
num.append(nums[len(nums) - i - 1])
return num
In your code, for each value of i, you are setting target array elements at i to value in "nums" at j. That is how you end up with same value for all the elements at the end of all iterations.
First of all, very bad logic to have two loops for a simple swap algorithm such as :
public static void reverse(int[] b) {
int left = 0; // index of leftmost element
int right = b.length-1; // index of rightmost element
while (left < right) {
// exchange the left and right elements
int temp = b[left];
b[left] = b[right];
b[right] = temp;
// move the bounds toward the center
left++;
right--;
}
}//endmethod reverse
or simplified:
for (int left=0, int right=b.length-1; left<right; left++, right--) {
// exchange the first and last
int temp = b[left]; b[left] = b[right]; b[right] = temp;
}
Why go through all this pain, why dont you trust Java's built-in APIs and do something like
public static Object[] reverse(Object[] array)
{
List<Object> list = Arrays.asList(array);
Collections.reverse(list);
return list.toArray();
}
public int[] reverse3(int[] nums) {
int[] values = new int[nums.length];
for(int i=0; i<nums.length; i++) {
values[nums.length - (i + 1)]=nums[i];
}
return values;
}

Categories

Resources