public E remove(int index) How to remove index from an array? - java

ok I have this code that someone helped with me
public void add(int index, E element)
if (index < 0 || index >= mList.length){
throw new IndexOutOfBoundsException(); // check if index is ok.
}
Object[] temp = new Object[mList.length + 1]; // create the new array into temp.
for (int i = 0, j = 0; j < temp.length; ++i, ++j){ // loop into the array by comparing the first array to the second array's index i&j
if ( i == index ) { // check if i is valid
temp[index] = element; // insert element into the array
--i; // decrement original array to cancel out j temp array
} else {
temp[j] = mList[i]; //
}
}
mList = temp;
}
Now I need to
public E remove(int index)
Do I need to create a temp array again?
I know there are two arrays, do I just do a for loop on the current array which is temp?

If you want to do it in a way similar to your add, then yes, you need a temp array.
public E remove(int index) {
Object[] temp = new Object[mList.length + 1];
for (int i = 0; j < mList.length; ++i) {
if(i<index) temp[i]=mList[i];
if(i>index) temp[i-1]=mList[i];
//N.B. not added if i == index
}
mList = temp;
}
To sum it up, you don't remove the element from the array, you just don't add it to the new one.
If you want a better solution, you should take a look at System.arraycopy() and Arrays.copyOf(). Give it a try and if you have difficulties don't shy away from asking.
If you are not forced to use arrays, I'd suggest you use Collections. For instance a List would suit your needs very well.

Related

How to delete an element in a fixed array [duplicate]

This question already has answers here:
How do I remove objects from an array in Java?
(20 answers)
Closed 1 year ago.
I am currently working on a delete method on a fixed array. Here is the implementation of the delete method below. What it does in the first for-loop is it gets the index if the data has a match on the array. For the next if and for-loop, its supposed to move the contents of the index if for example, the element deleted is at the 2nd or 3rd index of an array of length 5. It returns true, if the element has been successfully deleted in the array and false if not.
public boolean delete(E data) {
int index = -1;
int size = list.length;
for (int i = 0; i < list.length; i++) { // for getting what index in the array
if (data == list[i]) { // is the element in if there is a match
index = i;
}
}
if (index > -1) { // for swapping the index when
final int newArraySize; // the element is deleted in the
if ((newArraySize = size - 1) > index) { // between first-2nd to the last
for (int x = 0; x < list.length; x++) { // index in the array.
if (list[x] == null) {
for (int y = 0; y < x; y++) {
// move items
list[y] = list[y+1];
}
}
}
}
list[size = newArraySize] = null;
return true;
}
return false;
}
When I try running it, it doesn't delete the element. I'm having problems with the implementation of the swapping index part. I need help.
Your solution has time complexity of O(nxn). Instead you can start from the index of element being removed and swap all elements from index of element being removed.
for (int i = index; i < list.length - 1; i++) {
list[i] = list[i + 1];
}
But above solution might retain same size of the array and have repeat elements.
I will suggest using two array solutions, it adds bit of space complexity but effectively removes element and reduces the array size. Also you need to return this updated array.
int[] copy = new int[list.length - 1];
for (int i = 0, j = 0; i < list.length; i++) {
if (i != index) {
copy[j++] = list[i];
}
}

Print reverse in linkedlist

I want to write function Print Reverse of LinkedList in Java. I write like this but it doesn't work. Compiler warn that NullPointerException.
void ReversePrint(Node head) {
int[] array = null;
int i = 0;
Node tmp;
for (tmp = head; tmp != null; tmp = tmp.next) {
array[i] = tmp.data;
i++;
}
for(int j = i; j >= 0; j--){
System.out.println(array[j]);
}
}
You get the NullPointerException because the variable array is null:
int[] array = null;
You need to initialize it first with a value before you are using it here:
array[i] = tmp.data;
For example with a statement like this:
int[] array = new int[size];
Where size should probably be the size of your LinkedList. If you, for whatever reason, don't know the size, you can use the class ArrayList which realizes arrays with dynamic size (it guesses a size and if your exceeding it, it will re-allocate a bigger array and copy everything over and so on).
Here's a version using said ArrayList:
// Method names should start with a lower-case letter
void reversePrint(Node head) {
// Initialize an empty ArrayList
ArrayList<Integer> dataList = new ArrayList<>();
int i = 0;
Node tmp;
for (tmp = head; tmp != null; tmp = tmp.next) {
// Set the element at position i of the ArrayList
dataList.set(i, tmp.data);
i++;
}
// See next comment
i--;
for(int j = i; j >= 0; j--){
// Get the element at position j of ArrayList and print it
System.out.println(dataList.get(j));
}
}
Note that you will also encounter an IndexOutOfBoundException since your i is 1 to big when reaching the print-loop. This is because you increased it also in the last iteration of your first loop:
// Suppose last iteration, i is (list.size() - 1) then
for (tmp = head; tmp != null; tmp = tmp.next) {
array[i] = tmp.data;
// i is now list.size()
i++;
}
You need one i-- between the loops or int j = i - 1 in your loop initialization.
If you are realizing a doubly-linked list instead of only a single-linked list then note that you do not need to story values in an array first. You then can directly print the values by starting at tail and following tmp.prev pointers.
The simplest way to do this is with a recursive method:
void ReversePrint(Node node) {
if (node != null) {
ReversePrint(node.next);
System.out.println(node.data);
}
}

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.

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

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;
}

Duplicates in a sorted java array

I have to write a method that takes an array of ints that is already sorted in numerical order then remove all the duplicate numbers and return an array of just the numbers that have no duplicates. That array must then be printed out so I can't have any null pointer exceptions. The method has to be in O(n) time, can't use vectors or hashes. This is what I have so far but it only has the first couple numbers in order without duplicates and then just puts the duplicates in the back of the array. I can't create a temporary array because it gives me null pointer exceptions.
public static int[] noDups(int[] myArray) {
int j = 0;
for (int i = 1; i < myArray.length; i++) {
if (myArray[i] != myArray[j]) {
j++;
myArray[j] = myArray[i];
}
}
return myArray;
}
Since this seems to be homework I don't want to give you the exact code, but here's what to do:
Do a first run through of the array to see how many duplicates there are
Create a new array of size (oldSize - duplicates)
Do another run through of the array to put the unique values in the new array
Since the array is sorted, you can just check if array[n] == array[n+1]. If not, then it isn't a duplicate. Be careful about your array bounds when checking n+1.
edit: because this involves two run throughs it will run in O(2n) -> O(n) time.
Tested and works (assuming the array is ordered already)
public static int[] noDups(int[] myArray) {
int dups = 0; // represents number of duplicate numbers
for (int i = 1; i < myArray.length; i++)
{
// if number in array after current number in array is the same
if (myArray[i] == myArray[i - 1])
dups++; // add one to number of duplicates
}
// create return array (with no duplicates)
// and subtract the number of duplicates from the original size (no NPEs)
int[] returnArray = new int[myArray.length - dups];
returnArray[0] = myArray[0]; // set the first positions equal to each other
// because it's not iterated over in the loop
int count = 1; // element count for the return array
for (int i = 1; i < myArray.length; i++)
{
// if current number in original array is not the same as the one before
if (myArray[i] != myArray[i-1])
{
returnArray[count] = myArray[i]; // add the number to the return array
count++; // continue to next element in the return array
}
}
return returnArray; // return the ordered, unique array
}
My previous answer to this problem with used an Integer List.
Not creating a new array will surely result in nulls all over the initial array. Therefore create a new array for storing the unique values from the initial array.
How do you check for unique values? Here's the pseudo code
uniq = null
loop(1..arraysize)
if (array[current] == uniq) skip
else store array[current] in next free index of new array; uniq = array[current]
end loop
Also as others mentioned get the array size by initial scan of array
uniq = null
count = 0
loop(1..arraysize)
if (array[current] == uniq) skip
else uniq = array[current] and count++
end loop
create new array of size count
public static int[] findDups(int[] myArray) {
int numOfDups = 0;
for (int i = 0; i < myArray.length-1; i++) {
if (myArray[i] == myArray[i+1]) {
numOfDups++;
}
}
int[] noDupArray = new int[myArray.length-numOfDups];
int last = 0;
int x = 0;
for (int i = 0; i < myArray.length; i++) {
if(last!=myArray[i]) {
last = myArray[i];
noDupArray[x++] = last;
}
}
return noDupArray;
}
public int[] noDups(int[] arr){
int j = 0;
// copy the items without the dups to res
int[] res = new int[arr.length];
for(int i=0; i<arr.length-2; i++){
if(arr[i] != arr[i+1]){
res[j] = arr[i];
j++;
}
}
// copy the last element
res[j]=arr[arr.length-1];
j++;
// now move the result into a compact array (exact size)
int[] ans = new int[j];
for(int i=0; i<j; i++){
ans[i] = res[i];
}
return ans;
}
First loop is O(n) and so is the second loop - which totals in O(n) as requested.

Categories

Resources