I'm practicing what are pretty basic java array exercises and I'm having a hard time wrapping my head around how to insert an element into the beginning of an array and then shift the remaining elements to the right. So if the array hasn't gone over its max size, inserting a z in front of array, j, a, v, a would make for z, j, a, v, a.
I know how to do this with array lists, I'm just having a difficult time getting the logic correct with arrays. This is what I have so far:
public void addFront(char ch)
{
for(int i = 1; i < data.length-1; i++){
char temp = data[i - 1];
data[i] = temp;
}
data[0] = ch;
}
It seems like I need a temporary variable but I'm not using it correctly in this instance. Any input would be appreciated!
Let's take a look at what your current loop is doing. It is copying the character from position i - 1 to the current position. But the next loop will copy it from (current) i to (current) i + 1. It will just copy the first character over every position in the array except for the last position.
You must iterate backwards through the array, so that one shift doesn't accidentally use the result of the previous shift.
Start at index data.length - 1, and copy from position i - 1 to position i, making sure that the last iteration is when i is 1.
Additionally, a temp variable isn't needed. You can copy the value directly, i.e.
data[i] = data[i - 1];
Start at the back end of the array.
If you move element 0 to element 1, then element 1 to element 2... well you already copied element 0 to element 1.... so now you'll just copy element 0 over the entire array.
Start at the back end of the array shifting everything to the right, then after you're done with that, insert the new element at the front.
public void addFront(char ch) {
for(int i = data.length-1; i > 0; --i) {
data[i] = data[i-1];
}
data[0] = ch;
}
You don't need a temporary variable for an insert, as described this should work...
public void addFront(char ch)
{
for(int i = data.length - 1; i > 0; i--){ // start at the end.
data[i] = data[i-1]; // move every element up 1... that is set the current
// element to the prior element.
}
for (int i = data.length - 1; i >= 0; i--) {
if (data[i] == null) { // find the first blank...
data[i] = ch; // set the initial value.
break;
}
}
}
Related
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;
This is probably a noobish question but, i have been working on this project and couldn't get it to work. I got frustrated and experimented around and got it to work somehow. The change i made was i added a -1 to numOfItem.
I would really appreciate if someone could explain to me why this worked. My head is not really reading the code properly i believe. I am under the impression that if i am removing an item on the last index, it should throw an error.
for (int j = i; j < numOfItem - 1; j++)
This code belongs to a nested for loop in this method:
//Removes only a single instance of the specified item.
//If the item doesnt exist in the bag, it returns false
public boolean remove(Object item) {
for (int i = 0; i < numOfItem; i++) {
if (stuff[i].equals(item)) {
for (int j = i; j < numOfItem - 1; j++)
stuff[j] = stuff[j + 1];
stuff[numOfItem - 1] = null;
numOfItem--;
return true;
}
}
return false;
}
numOfItem is set to 0, when an object bag is initialized, as to signify there are 0 items in the bag, however the bag is given a max capacity (user input) when initialized. If any more info is needed, please let me know. Thanks in advance.
Your code it trying to remove an element from an array if it is found using the following steps:
Step 1 :
Find the element.
Step 2 :
a) If not found, return false;
b) If found, shift all the elements to the left from the index where the element is found.
c) Set the last index of array as null.
In the Step 2 b) shift is done by:
for(int j = i; j < numOfItem - 1; j++)
stuff[j] = stuff[j + 1];
In this above code, you need to iterate for loop till second last index only, because the last index needs to be set as null to decrement the array size after deleting the element. If you try to iterate on last index, then stuff[j+1] will throw ArrayIndexOutOfBoundException. Thats why numOfItem -1 works.
I am assuming you are referring to the line stuff[numOfItem - 1] = null If this is the case then the answer is simple. Array indexing starts at 0, not 1 therefore if you have 50 items in your array (numOfItem = 50) then the indexing will be 0, 1, 2, 3...49 There is not 50th value as index 0 is technically the 1st value in the array. Therefore if you wrote stuff[numOfItem] = null you would be trying to access the 50th index in the array however, the largest index in the array is 49 since it starts at 0, not 1.
This question already has answers here:
Understanding this removeAll java method with arrayList
(3 answers)
Closed 6 years ago.
This methods duty is to remove all occurrences of the value toRemove from the arrayList. The remaining elements should just be shifted toward the beginning of the list. (the size will not change.) All "extra" elements at the end (however many occurrences of toRemove were in the list) should just be filled with 0. The method has no return value, and if the list has no elements, it should just have no effect.
Cannot use remove() and removeAll() from the ArrayList class.
The method signature is:
public static void removeAll(ArrayList<Integer> list, int toRemove);
The solution:
public static void removeAll(ArrayList<Integer> list, int toRemove) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i) = toRemove) {
for (int j = i + 1; j < list.size(); j++) {
list.set(j - 1, list.get(j));
}
list.set(list.size() - 1, 0);
i--;
}
}
I understand the first for loop and the if statement well. Because one would want to iterate through the entire arrayList one-by-one and for each index with a number present in the arrayList check if it is, in fact the toRemovee integer. After this point I become lost.
Why another for loop?
Why are we taking the previous loops variable and adding 1 to it?
why within this second loop are we using the parameters "list" and using a set method?
why j - 1?
why list.get(j)?
Why after this second loop is over is there the line:
list.set(list. sise () - 1, 0) ?
why the i--?
There are a lot of moving parts and I would like to understand the logic.
Thank you
Firstly the if statement is assignment operation which isn't correct. You need to change the = to ==. I have explained each step in the code -
public static void removeAll(ArrayList<Integer> list, int toRemove) {
//start with the first number in the list until the end searching for toRemove's
for (int i = 0; i < list.size(); i++) {
//if the value at i is the one we want to remove then we want to shift
if (list.get(i) == toRemove) {
//start at the index to the right until the end
//for every element we want to shift it the element to its left (i == j - 1)
for (int j = i + 1; j < list.size(); j++) {
//change every value to whatever was to the right of it
//this will overwrite all values starting at the index where we found toRemove
list.set(j - 1, list.get(j));
}
//now that everything is shifted to the left, set the last element to a 0
list.set(list.size() - 1, 0);
//decrement to adjust for the newly shifted elements
// this accounts for the case where we have two toRemoves in a row
i--;
}
}
}
By the end of this function any value that matches toRemove is "removed" by shifting the arraylist to the left everytime the value is found and the last element will be set to 0.
Example
removeAll([1,2,3,4,5,5,6,7,8,5,9,5], 5)
Output
[1,2,3,4,6,7,8,5,9,0,0,0]
Please see the following to learn details (from minute 5:50 or 5:57)
https://www.youtube.com/watch?v=qTdRJLmnhQM
You need the second for loop ,to take all elements after the element you’ve removed it and shift it over one to the left so basically it’s filling up the space that is left empty from removing it so this is what this is doing.
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.
public static void moveRight (int a[], int n){
int aux;
for(int i = 1; i<n; i--){
aux = a[i];
a[i]= a [i];
}
}
I been trying with this code but it doesn't work.
When printing the contents of an array, the left starts with the lowest values. If you move the values down the indexes you could say this is to the left. For moving the values up by index you need to start at the end and work down.
// Move one up
for (int i = a.length - 1; i > 0; i--)
a[i] = a[i-1];
// Move one down
for (int i = 0; i < a.length-1; i++)
a[i] = a[i+1];
Note: This is likely to be inefficent compare with using arraycopy which is designed for bulk array copies.
// Move one up
System.arraycopy(a, 0, a, 1, a.length-1);
// Move one down
System.arraycopy(a, 1, a, 0, a.length-1);
First, the loop variable is supposed to be going up. so change i-- to i++. Then, if I correctly understand what you're trying to do, you need a[i] = a[i-1] in the loop body. instead of a[i] = a[i] (which does nothing). Also, you don't need aux.
It's not clear what, if anything, you want to happen to a[0] when everything moves to the right. That should take place after the loop exits. (If you want the last element to move to the first element position, then I retract my comment about tmp; you'll need to store that last element somewhere so it's available after the array element gets overwritten. But it only needs to be stashed once, before the loop starts.)
One other comment: n must never be more than a.length or the loop will throw an exception. If n is always equal to a.length, then you can dispense with the argument and just use a.length in the method.