I'm trying to add the functionality to remove an item from an array via method call but am running into the problem posted in the title.
Heres the instructions:
Write a new method for the ArrayIntList class called remove that takes an integer index and that removes the value at the given index, shifting subsequent values to the left. For example, if a variable called list stores the following values:
[3, 19, 42, 7, -3, 4]
after making this method call:
"list.remove(1);"
would remove 3 from the array (not this is not specific to just the first value of the array
I tried to implement doing this:
public void remove(int index) {
int target = index;
int[] elementDataCopy = new int[size];
size = elementData.length;
if (index < 0 || index >= size) {
throw new IllegalArgumentException("invalid index");
}
//loop through each value until the index given is == to loop value
//create a copy of elementData where length is one less and value at
//index given is not present
//each time something is removed, the tracked values decrease by one
size--;
for(int i = 0; i < elementData.length + 2; i++){
if (elementData[i] == target){
continue;
}else{
elementDataCopy[i] = elementData[i];
}
}
}
``
but get this error:
Failed: Index 12 out of bounds for length 12
with the numbers differing depending on what input is.
note that elementData is an array of ints and index is an int that is pointing at a point in said array
all help is appreciated, pretty sure this is something basic
Try it like this. The big mistake is using i for both source and destination indices. Use a separate one (k here) for destination. Only increment the destination index when the copy is made. Once done,
reassign the elementDataCopy to elementData.
int k = 0;
for(int i = 0; i < elementData.length; i++) {
if (i == index) { // skip the one to "delete"
continue;
}
elementDataCopy[k++] = elementData[i];
}
elementData = elementDataCopy;
Related
First I created a random array then I decided to create another array to save the number except the highest. I got the prob when printing the array removed the highest number. I assume the issue when assigning item in b but I can't figure out. Please help :<
public static int[] deleteHighestNum(int a[]) {
int b[] = new int[a.length - 1];
for (int i = 0, j = 0; i < a.length; i++) {
if (a[i] > a[j]) {
b[j++] = a[j];
}
}
return b;
you first create a copy of the array with the .clone() method. This will be the second array you created. then you create an int x or something of this sort and set it equal to 0.
start now by iterating the array. if the number is greater then your int, replace the int.
once it is done, make another loop, that checks each value of your second array and if a number is equal to your int, delete it. done.
I am working on a homework assignment involving array sorting methods, we are given the methods, and I'm having a little trouble understanding how this insertion sort method functions. More specifically, the role the two variables passed to the method play.
As I understand, the Key variable describes the index of the array that you'd like to place your inserted number in and the item is the number itself. Within main, I simply request the user to enter two numbers and pass them to the method, one for the key and the other for the item. Here is the given code for this segment:
public final void insertion(double Key, double Item)
{
if (arraySize == 0)
{
arr[0] = Item;
}
/* find the position for inserting the given item */
int position = 0;
while (position < arraySize & Key > arr[position])
{
position++;
}
for (int i = arraySize; i > position; i--)
{
arr[i] = arr[i - 1];
}
arr[position] = Item;
arraySize = arraySize + 1;
}
However, when I pass doubles to the method as I have explained, I get an error stating that index (array length) is out of bounds for length (array length).
Clearly, I am misunderstanding the purpose or structure of this method and I can't figure it out. Any help would be appreciated. I know this is a very simple problem.
EDIT: Here is how I initialize my array, the given code is in a separate class from my main method:
public static double[] arr;
private int arraySize;
public sortedArrayAccess(int scale)
{
arr = new double[scale];
arraySize = arr.length;
}
Within my main method:
System.out.print("Enter an array size: ");
int d = sc.nextInt();
sortedArrayAccess test = new sortedArrayAccess(d);
for(int i=0;i<test.arr.length;i++)
{
System.out.print("Enter a number for index " + i + ": ");
double c = sc.nextDouble();
test.arr[i] = c;
}
How do you initialize ‘arr’ variable?
Anyway the problem is that when you create the array - you should specify initial capacity. And every time when you add the element into array you are about to increase it.
When you try to ask for for a cell of array indexed i if array capacity is less then I - you’ll be given the arrayOutOfBoundsException.
Your problem is here:
if (arraySize == 0)
{
arr[0] = Item;
}
You are assigning the Item to the first element in the array. But the array size must be empty as stated by the if (arraySize == 0)
So you have two options:
adjust the size of the array (by creating a new one)
or return an error
if (arraySize == 0)
{
arr[0] = Item;
}
As you know, in computer science, indices starts from 0. Which means arr[0] here is the first slot of your array. if arraySize is 0, there is no such index arr[0]. Your code tries to insert the Item to zero sized array. This causes Index out of bound exception.
By the way, If it is a sorting algorithm for the values, "Key" variable is not required. You can delete it. But if it is required, you should sort the elements by their key values.
For example if we have:
element 1 -> key= 101 , value= 6
element 2 -> key= 201 , value= 9
element 3 -> key= 301 , value= 2
you should not sort them as element 3 < element 1 < element 2
you should sort them like: element 1 < element 2 < element 3 in order to their key values.
In other words, if you want to sort them by their values, passing key values as a parameter is meaningless.
The purpose of this method is to return the position (subscript index) of the largest element in the array (not its value, but its position). If the same maximum value appears more than once in the array, then it should return the position of the first or earliest on. If the array has no elements it should just return -1.
The solution:
public static int maxPos(int[] arr) {
int pos = 0;
if(arr.length > 0 ) {
for(int i = 0; i < arr.length; i++) {
if(arr[i] > arr[pos]) {
pos = i;
} else {
pos = - 1;
}
}
return pos;
}
I understand setting up a dummy variable "pos" to represent the index position of the maximum value of the array. And having the check point with if(arr.length > 0) then proceed. And the for-loop to sift through the entire array checking one-by-one which index has the greatest number value and after each iteration either re-assigning dummy variable or carrying onward.
The part where I get lost is when using things within the array [ ]'s, it throws me off. I don't think anywhere else in java there is such notation. For example with arrayList wouldn't that just be nameOfAL . get();
So the equivalent of that for an array is using the []'s?
I am a bit confused by arr[i] > arr[pos].
Is this to say when we are at the i'th index in the for-loop, we can then use arr[] and put something within that box, and when we do it outputs the value of that index. So anytime we put something within that array box it's always going to output an index position? is that the purpose of putting things inside the [] box? it will output the value of whatever is put inside it's brackets.
the next part that confuses me is why pos = i?
I understand if the if-statement fails then the else is - 1. but why return pos; after each iteration?
Thank you
Your posted code contains a few bugs, you should start with pos at -1 (instead of resetting it when a given value isn't greater then the current max). Also, I would check for null. Then you can start your loop with the second element. Something like,
public static int maxPos(int[] arr) {
int pos = -1; // <-- indicates no elements.
if (arr != null && arr.length > 0) {
pos = 0; // <-- there is at least one element.
for (int i = 1; i < arr.length; i++) {
if (arr[i] > arr[pos]) {
pos = i; // <-- update the max position
}
}
}
return pos;
}
First, so what you're putting in the square braces are variables named i and pos that hold the values of the numerical positions you're accessing in the array. It's like the get method of the arrayList class like that.
It's not returning pos until it finishes the for loop. In general it's returning pos because that's the index of the largest number, which is the point of the program. I think you're just missing a bracket somewhere, you have 5 {'s and 4 }'s.
I'm fairly new to java so I would like to keep it simple, and I figure I would have to take the first value of the array then compare it to each following value and if the value is larger smaller than the first, replace the value with it, but I don't know how to get index from that.
For an unstructured, unsorted array the best you can do, assuming you are only going to find the minimum value once, is a simple iteration over all elements (O(n) complexity), like so:
public int findMinIdx(int[] numbers) {
if (numbers == null || numbers.length == 0) return -1; // Saves time for empty array
// As pointed out by ZouZou, you can save an iteration by assuming the first index is the smallest
int minVal = numbers[0] // Keeps a running count of the smallest value so far
int minIdx = 0; // Will store the index of minVal
for(int idx=1; idx<numbers.length; idx++) {
if(numbers[idx] < minVal) {
minVal = numbers[idx];
minIdx = idx;
}
}
return minIdx;
}
Also, in the case of a tie for minimum value, this method will return the index of the first case of that value it found. If you want it to be the last case, simply change numbers[idx] < minVal to numbers[idx] <= minVal.
Here is with Java 8
public static int findMinIdx(int[] numbers) {
OptionalInt minimun = IntStream.of(numbers).min();
return IntStream.of(numbers).boxed().collect(toList()).indexOf(minimun.getAsInt());
}
Never cared about run time optimization, was just looking for a solution!, this worked and this would help you too, finding the index of the lowest values in an array.
// array[] -> Received the array in question as an parameter
// index -> stores the index of the lowest value
// in for loop, i is important to complete all the comparison in the function
// When it finds a lower value between the two, it does not change the index
// When it finds a lower value it changes it's index to that index
// If array has same value more than once, it will provide index to that values last occurrence
// Correct me if you find anything not working in this example...
//...
private static int index_of_minimum_value(int[] array) {
int index = 0;
for (int i = 1; i < array.length; i++) {
if ((array[i - 1] < array[i]) && ([index] > array[i - 1])) index = i - 1;
else if (array[index] > array[i]) index = i;
}
return index;
}
Here's what the layout is
index num
0 [10]
1 [20]
2 [30]
(Add 35 here)
3 [40] Move elements down
4 [50]
5 [60]
6 [70]
then my method is this
public static void method(int[] num, int index, int addnum)
{
}
How can i add 35 in there?
Tried this:
public static void method(int[] num, int index, int addnum)
{
int index = 10;
for(int k = num.length k>3; k++)
{
Num[k]=num[k++]
}
Num[3] = 35;
As this is something you should accomplish yourself, I will only provide the method to implement it, not the code:
If you would set the number at position index, you would overwrite the value that was there previously. So what you need to do is move every element one position towards the end of the array starting from index: num[x] becomes num[x+1], etc.
You will find out that you need to do this in reverse order, otherwise you will fill your array with the value in num[index].
During this process you will need to decide what to do with the last entry of the array (num[num.length - 1]):
You could just overwrite it, discarding the value
You could return it from your function
You could throw an exception if it is non-zero
You could create a new array that is 1 entry larger than the current array instead to keep all values
etc.
After this, you have duplicated num[index]: the value is present in num[index+1], too, as you have moved it away.
Now it is possible to write the new value at the desired position without overriding an existing value.
EDIT
You have several errors in your code:
You increment k, you need to decrement it (k--, not k++)
You modify k again in your loop body: it is updated twice in each cycle
If you start with k = num.length, you will try to write at num[num.length + 1], which is not possible
Very crudely, you want to do something like this:
public static void(int[] num, int index, int addnum)
{
// initialize new array with size of current array plus room for new element
int[] newArray = new int[num.length + 1];
// loop until we reach point of insertion of new element
// copy the value from the same position in old array over to
// same position in new array
for(int i = 0; i < index; i++)
{
newArray[i] = num[i];
}
i = i + 1; // move to position to insert new value
newArray[i] = addnum; // insert the value
// loop until you reach the length of the old array
while(i < num.length)
{
newArray[i] = num[i-1];
}
// finally copy last value over
newArray[i + 1] = num[i];
}
You need to
allocate a new array with room for one new element.
int[] newArray = new int[oldArray.length + 1];
Copy over all elements and leave room for the one to insert.
for (int i = 0; i < newArray.length - 1; i++)
newArray[i < insertIndex ? i : i + 1] = oldArray[i];
Insert 35 in the empty spot.
newArray[insertIndex] = numberToInsert;
Note that it's not possible to do in a method like this:
public static void method(int[] num, int index, int addnum)
^^^^
since you can't change the length of num.
You need to allocate a new array, which means that need to return the new array:
public static int[] method(int[] num, int index, int addnum)
^^^^^
and then call the method like this:
myArr = method(myArr, 3, 35);
Since this very closely resembles homework what you need to realize is that you cannot dynamically increase the size of an array. So in your function:
public static void(int[] num, int index, int addnum)
{
int[] temp = new int[num.length *2];
for(int i = 0; i < index; i++)
copy num[i] into temp[i]
insert addnum into temp[index]
fill temp with remaining num values
}
That pseudocode above should get you started.
What you're looking for is an insertion sort.
It's classwork, so it's up to you to figure out the proper code.
Well, you can't unless there is "extra space" in your array, and then you can shift all elements [starting from index] one element to the right, and add 35 [num] to the relevant place.
[what actually happen is that the last element is discarded out].
However - a better solution will probably be to use an ArrayList, and use the method myArrayList.add(index,element)
How about this?
public class test {
public static void main(String[] arg) throws IOException
{
int[] myarray={1,2,3,5,6};//4 is missing we are going to add 4
int[] temp_myarray=myarray;//take a temp array
myarray=addElement(myarray,0);//increase length of myarray and add any value(I take 0) to the end
for(int i=0;i<myarray.length;i++)
{ if(i==3) //becaues I want to add the value 4 in 4th place
myarray[i]=4;
else if(i>3)
myarray[i]=temp_myarray[i-1];
else
myarray[i]=temp_myarray[i];
}
for(int i=0;i<myarray.length;i++)
System.out.print(myarray[i]);//Print new array
}
static int[] addElement(int[] arr, int elem) {
arr = Arrays.copyOf(arr, arr.length + 1);
arr[arr.length - 1] = elem;
return arr;
}
}