Understanding the logic of this remove method in Java - java

The job of this method is to remove the value toRemove from the array. The remaining elements should just be shifted toward the beginning of the array. (The array's size will not change.) Since the array will now have one fewer element, the position of the last element should just be filled with 0. If there is more than one occurrence of toRemove in the array, only the first occurrence should be removed. The method has no return value, and if the array has no elements, it should just have no effect.
The solution:
public static void remove(int[] arr, int toRemove) {
boolean done = false;
int position = 0;
for(int pos = 0; pos < arr.length; pos++) {
if(!done && arr[pos] == toRemove) {
done = true;
position = pos;
}
if(done) {
for(int i = position + 1; i < arr.length; i++) {
arr[i - 1] = arr[i];
}
arr[arr.length -1] = 0;
}
}
}
I am not following how this algorithm works. The use of boolean confuses me, I feel I don't fully understand what the primitive data type does, I know that it holds two things either true or false, and false by default. But what does that really mean? I don't understand boolean.
I understand why would want an int placeholder for the index of where the toRemove value was found. I understand we would want to use a for-loop to iterate one-by-one the indices and their respective values and pinpoint where exactly toRemove is found. I understand we would want a check point conditional to see if at some arbitrary index the toRemove value exists, andd therefore:
if(arr[pos] = toRemove) // then bingo we've found him
I don't understand the boolean !done, booleans confuse me.
why after this check point is there done = true? and then after that another check if(done)? and why another for loop for(int i = position + 1; i < arr.length; i++) and after that for loop the line arr[i - 1] = arr[i];? and finally at the end arr[arr.length-1] = 0 and position = pos;
I understand when we want to access a particular indicies value we write variablenameOfArr then the [] and put it inside the box. I am having difficulty putting this all together.
Thank you

In this case, the boolean done seems to control whether a value has already been removed or not. It begins the algorithm as false, as nothing has been removed yet.
The first if statement tests to see if the value of done is false. In if statements, instead of saying if(done == false), this can be simplified to if(!done). So, this if statement simply tests to see if a value has been found yet or not.
done is then set to true once a value has been removed, so that no future values will be removed.
Finally, the second if statement tests to see if a value has been removed or not. Like the first if statement, if(done == true) can be simplified to if(done).
I hope this helps, comment with any further questions if they arise.

public static void remove(int[] arr, int toRemove) {
boolean done = false; //This boolean is used to determine when the element has been found
int position = 0;
for(int pos = 0; pos < arr.length; pos++) { //Iterating through the array
//if we aren't already done, (!done = NOT DONE) and we have found the position to remove, then enter this logic
if(!done && arr[pos] == toRemove) {
done = true; //since we found the position to remove, set done to true
position = pos; //Save the index of the one that was removed
}
if(done) { //if we are done, enter this logic
//This loop starts above the index where removed, and iterates to the top
for(int i = position + 1; i < arr.length; i++) {
arr[i - 1] = arr[i]; //This shifts each element down one
}
arr[arr.length -1] = 0; //This sets the empty slot at the top of the array to 0
}
}
}

The boolean is indeed not necessary since it is always true when if(!done && arr[pos] == toRemove) is true.
Besides, it makes no sense to go on the outer loop when you have removed an element as 1) the state of the array is nice : the inner loop has shifted the elements after the removed element to their left and 2) you cannot perform two removals.
By the way the position variable is also not required. You can use the pos variable directly as it is read only used.
This code :
for(int pos = 0; pos < arr.length; pos++) {
if(!done && arr[pos] == toRemove) {
done = true;
position = pos;
}
if(done) {
for(int i = position + 1; i < arr.length; i++) {
arr[i - 1] = arr[i];
}
arr[arr.length -1] = 0;
}
}
could be replaced by this without using the boolean and you could also exist the method after the array elements were shifted :
for(int pos = 0; pos < arr.length; pos++) {
if(arr[pos] == toRemove) {
for(int i = pos + 1; i < arr.length; i++) {
arr[i - 1] = arr[i];
}
arr[arr.length -1] = 0;
return;
}
}

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

String indexOf method is not working for first character in the String

I am implementing a code for counting number of occurrences for all the characters in a String. I have used indexOf() method to check occurrences. But it's not working for the first character.
The following code works fine for all characters except the first character.
public static void main(String[] args) {
String str = "simultaneously";
int[] count = new int[str.length()]; //counter array
for (int i = 0; i < count.length; i++) { //initializing counters
count[i] = 0;
}
for (int i = 0; i < str.length(); i++) {
int index = -1;
char c = str.charAt(i);
while (1 > 0) {
if (str.indexOf(c,index) > 0) { //This is not working for
//the first characters
index = str.indexOf(c, index) + 1;
count[i]++;
} else {
break;
}
}
}
for (int i = 0; i < count.length; i++) {
System.out.println(str.charAt(i) + " occurs " + count[i] + " times");
}
}
Index for arrays in java starts from 0.
Change the condition from
if (str.indexOf(c,index) > 0) {
to
if (str.indexOf(c,index) >= 0) {
And also, the for-loop to initialize the counter is redundant, by default, all the values in the int array is initialized to 0.
str.indexOf(c,index) would return 0 for the first character, but your condition checks whether str.indexOf(c,index) > 0. Change it to str.indexOf(c,index) >= 0.
There is some thing else you need to know
str.indexOf(c,index)
will search for the character c from the index 'index' which is -1 in your case for the first character that is it will never find this because starting point of string is 0
also change your condition as following
str.indexOf(c,index) >= 0
The index of arrays and Strings (which are array of characters) always start at 0 in Java.
You also want to check position 0, so include >=.
if (str.indexOf(c,index) >= 0) {
Also, using breaks can sometimes be confusing.
In your code, your while-loop is an infinite True and then you break out of it when necessary.
Take a look at this code below. It serves the same purpose that you want to accomplish.
It is much cleaner and clearer as it removes the break from the whileloop and you simply check to see if the statement is True at the beginning of the while-loop rather than inside it.
for (int i = 0; i < str.length(); i++) {
int index = 0;
char c = str.charAt(i);
while (str.indexOf(c,index) >= 0) {
index = str.indexOf(c, index) + 1;
count[i]++;
}
}

counting number of unique elements

Hi so I am supposed to count the number of unique elements after an array sort excluding duplicates but i'm getting the wrong output.
In in = new In(args[0]);
int[] whitelist = in.readAllInts();
Arrays.sort(whitelist);
int count = 0;
for (int i = 0; i < whitelist.length; i++) {
if (whitelist[i] == whitelist[count]) {
count++;
}
}
while (!StdIn.isEmpty()) {
int key = StdIn.readInt();
rank(key, whitelist);
}
System.out.println(count);
}
}
expected output: java InstrumentedBinarySearch tinyW.txt < tinyT.txt
65
got: 16
Did i count the number of duplicates or something?
int flag = 0;
int count = 0;
for (int i = 0; i < whitelist.length; i++) //Element to be checked for
{
for (int j=0; j< whitelist.length ; j++) //Loop that goes through the whole array
{
if (whitelist[i] == whitelist[j]) //checks if there are duplicates
{
flag++; // count
}
}
if( flag==1) //There should be only 1 instance of the element in the array and that is the element itself
{
System.out.println(whitelist[i]); //displays unique element
count++; // Keeps count
}
}
This algorithm counts how many different unique numbers there are in the array. A number appearing more than once will only count for 1. I am assuming this is what you mean, as opposed to "numbers which appear exactly once".
There is a more trivial way to do it, as proposed in another answer, but it requires a nested for-loop and therefore executes in quadratic complexity. My algorithm below attempts to solve the problem in linear time proportional to the array size.
int uniquesFound = 0;
// Assume that array is sorted, so duplicates would be next to another.
// If we find duplicates, such as 12223, we will only count its last instance (i.e. the last '2')
for (int i = 0; i < whitelist.length; i++) {
// If we are at the last element, we know we can count it
if (i != whitelist.length - 1) {
if (whitelist[i] != whitelist[i+1]) {
uniquesFound++;
}
else {
// Nothing! If they are the same, move to the next step element
}
} else {
uniquesFound++;
}
}
For instance, given the array:
{1,2,3} this will yield 3 because there are 3 unique numbers
{1,2,3,3,3,4,4,4,5} this will yield 5 because there are still 5 unique numbers
First let's take a look at your loop:
for (int i = 0; i < whitelist.length; i++) {
if (whitelist[i] == whitelist[count]) {
count++;
}
}
You should be comparing consecutive elements in the list, like whitelist[0] == whitelist[1]?, whitelist[1] == whitelist[2]?, whitelist[3] == whitelist[4]?, etc. Doing whitelist[i] == whitelist[count] makes no sense in this context.
Now you have two options:
a. Increment your counter when you find two consecutive elements that are equal and subtract the result from the total size of the array:
for (int i = 0; i < whitelist.length - 1; i++) {
if (whitelist[i] == whitelist[i + 1]) {
count++;
}
}
int result = whitelist.length - count;
b. Change the condition to count the transitions between consecutive elements that are not equal. Since you are counting the number of transitions, you need to add 1 to count in the end to get the number of unique elements in the array:
for (int i = 0; i < whitelist.length - 1; i++) {
if (whitelist[i] != whitelist[i + 1]) {
count++;
}
}
int result = count + 1;
Note that, in both cases, we loop only until whitelist.length - 1, so that whitelist[i + 1] does not go out of bounds.

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

Magic Square Java program

//Kevin Clement
//Week3A Magic Squares
Hey all, doing an introductory assignment to 2dimensional arrays. Below is the code I have done which is pretty much done.
My problem I get is I'm not entirely sure how to print out the array, as well as getting everything to run right with a test method. I get an error out of bounds at the line msq[order][order] = 1;
I apologize if my formatting of question is wrong, still not used to this site. Any help would be great. Thanks!
import java.util.*;
class Magic
{
private int order;
int msq[ ][ ];
public Magic(int size)
{
if(size < 1 || size % 2 == 0)
{
System.out.print("Order out of range");
order = 3;
}
msq = new int[order][order];
Build();
Display();
}
public void Build()
{
int row = 0;
int col =0;
msq[order][order] = 1;
for(int k = 1; k <= order * order; k++)
{
msq[row][col] = k;
if(row == 0 && col == order -1)
row++;
else if(row == 0)
{
row = order - 1;
col++;
}
else if(msq[row - 1][col + 1] != 0)
row++;
else if(msq[row -1][col + 1] == 0)
{
row--;
col++;
}
if(col == order - 1)
{
col = 0;
row--;
}
}
}
public void Display()
{
for(int i = 0; i < order; i++)
{
for(int k = 0; k < order; k++)
{
System.out.println(msq[i][k] + " ");
}
}
}
}
I get an error out of bounds at the line msq[order][order] = 1;
msq = new int[order][order];
// ..
msq[order][order] = 1;
If array size is n, then you need to access the elements from 0 to n-1. There is no nth index. In your case there is no order, order index. It is only from 0 to order-1 and is the reason for array index out of bounds exception.
What is the reason for this condition in the constructor?:
if(size < 1 || size % 2 == 0)
{
System.out.print("Order out of range");
order = 3;
}
Note that whenever you use a size input that doesn't satisfy the if clause, the variable order is not initialized and defaults to 0. As a result the 2d array has size zero and throws the out of bounds error. If you are trying to use 3 as a default value, then u want to move the line:
order = 3;
before the if block.
Other things to consider:
1. make the order variable final since u don't plan on changing it. Eclipse IDE would warn you about the situation described above if you do so.
or
2. If you are going to default to 3 for the value of order initialize it as such.
private int order = 3
Also you might consider printing a message saying order defaults to three when the condition is not satisfied.
To print a matrix of integers in Java
for (int i = 0; i < order; i++) {
for (int k = 0; k < order; k++) {
System.out.printf("%6d", msq[i][k]);
}
System.out.println();
}
The second part of your question is answered by Mahesh.
msq[order][(order] = 1;
--> here is a syntax error. You have an '('.
You get end of bound error because array start from 0 not 1 (which is a mistake every beginner makes) therefore change it to msq[order-1][order-1] = 1;
The answer above is the correct way to print out the array.

Categories

Resources