how to delete null values/elements from an array - java

need help again. sorry. how can i remove the null values from my array? here is what i got so far.
int unikCount = 0;
String c = " ";
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length; j++) {
if (tempAry[i].equals(tempAry[j])) {
unikCount++;
}
if (unikCount > 1) {
tempAry[j] = c;
unikCount = 1;
}
}
unikCount = 0;
}
for (i = 0; i < a.length; i++) {
if (tempAry[i] != c) {
unikCount++;
}
}
System.out.println(unikCount);
for (int i = 0; i < a.length; i++) {
for (int j = 1; j < a.length; j++) {
if (tempAry[i].equals(tempAry[j])) {
if (tempAry[i] == c) {
count++;
if (tempAry[j] != c) {
count++;
tempAry[j] = tempAry[i];
}
}
}
}
}
count = 0;
for (int i = 0; i < a.length; i++) {
System.out.println(tempAry[i]);
}
*the remove part is after the "System.out.println(unikCount)". thanks for the upcoming help. by the way, cant use hash and arraylist.

You can check for null like this:
if ( null == someObject )
{
// do things
}
There is no way to remove an element from an array and have it shrink automatically. You'll have to use a temporary array to hold values, create an array of a new size and transfer all those items.
A more effective way would be to use a List.

Look at your logic (with proper indentation):
if(tempAry[i].equals(tempAry[j])) {
if(tempAry[i] == c) {
count++;
if(tempAry[j] != c) {
count++;
tempAry[j] = tempAry[i];
}
}
}
It does not make any sense. Why would you check for tempAry[j] != c inside if(tempAry[i] == c) ???
Did you mean to use if...else instead?

int j = 0;
Object[] temp = new Object[a.length];
for (int i = 0; i < a.length; i++) {
if (a[i] != null) {
temp[j++] = a[i];
}
}
Object[] newA = new Object[j];
System.arraycopy(temp, 0, newA, 0, j);
If the array is an array of, eg, String, you'd of course change "Object" to "String". And if by "null" one means an empty String, then the if test would be changed appropriately.

Related

[Java]Why does the initial for loop starts with index i=0 post the break in else condition

I am trying to implement a solution to merge two sorted arrays to a single sorted array.
I tried to implement a code but it does not work. The issue that I am seeing here is after my outer for loop reaches the limit of array2.length(), it still gets started from i=0. Can someone please help explain whats wrong in this piece of code?
List<Integer> mergedArray = new ArrayList<>();
int counter = 0;
public List<Integer> getMergedArray(List<Integer> array1, List<Integer> array2) {
for (int i = 0; i < array1.size(); i++) {
for (int j = counter; j < array2.size(); j++) {
if (array1.get(i) > array2.get(j)) {
mergedArray.add(array2.get(j));
counter++;
} else {
mergedArray.add(array1.get(i));
System.out.println("i " +i);
break;
}
}
}
return mergedArray;
}
One problem I see with the code is when the two arrays do not have same length. In either case of (array1.length > array2.length or reverse) the remaining elements of longer array will not be processed. So if you add a more code at end of this the loops to deal with that case, this might work well!
public List<Integer> getMergedArray(List<Integer> array1, List<Integer> array2) {
List<Integer> mergedArray = new ArrayList<>();
int counter = 0, i = 0, j = 0;
for (i = 0; i < array1.size(); i++) {
for (j = counter; j < array2.size(); j++) {
if (array1.get(i) > array2.get(j)) {
mergedArray.add(array2.get(j));
counter++;
} else {
mergedArray.add(array1.get(i));
System.out.println("i " +i);
break;
}
}
}
// More code here
if (j==array2.size()){//copy rest of array1 into mergedArray}
if (i==array1.size()){//copy rest of array2 into mergedArray}
return mergedArray;
}
I think you called the same method twice, without resetting the counter or the previous mergedArray.
You should declare those inside the method.
Additionally, after reaching the end of array1, you should check if there are remaining elements in array2, and vice-versa:
public List<Integer> getMergedArray(List<Integer> array1, List<Integer> array2) {
List<Integer> mergedArray = new ArrayList<>();
int counter = 0;
for (int i = 0; i < array1.size(); i++) {
for (int j = counter; j < array2.size(); j++) {
if (array1.get(i) > array2.get(j)) {
mergedArray.add(array2.get(j));
counter++;
} else {
mergedArray.add(array1.get(i));
System.out.println("i " +i);
break;
}
}
if(counter >= array2.size()) {
mergedArray.add(array1.get(i));
}
}
for (int j = counter; j < array2.size(); j++) {
mergedArray.add(array2.get(j));
}
return mergedArray;
}
I think it works but problem is that you don't handle case when inner array size is equal or bigger than size of outer array. I rewrote your method (in way I think it`s right). Hope you'll find it useful.
public List<Integer> getMergedArray(List<Integer> array1, List<Integer> array2) {
List<Integer> mergedArray = new ArrayList<>();
int index1 = 0;
int index2 = 0;
for (int i = 0; i < array1.size() + array2.size(); i++) {
Integer num1 = null;
Integer num2 = null;
if (index1 < array1.size()) {
num1 = array1.get(index1);
}
if (index2 < array2.size()) {
num2 = array2.get(index2);
}
if (num1 != null && num2 != null) {
if (num1 < num2) {
mergedArray.add(num1);
++index1;
} else {
mergedArray.add(num2);
++index2;
}
} else if (num1 != null) {
mergedArray.add(num1);
++index1;
} else {
mergedArray.add(num2);
++index2;
}
}
return mergedArray;
}
If your array2 has all the element less then array1[i]
in this case your logic also fails because your inner loop condition always fail
you can do this way
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2) {
if (arry1[i] <= arry2[j]) {
TempArry[k] = arry1[i];
i++;
}
else {
TempArry[k] = arry2[j];
j++;
}
k++;
}
/* Copy remaining elements of array1[] if any */
while (i < n1) {
TempArry[k] = array1[i];
i++;
k++;
}

Remove duplicate characters from a string without using additional buffer

I am working on an interview question where I need to remove duplicate characters from the String without using additional buffer.
Below is the code I have but it's not giving right output for this string "aabbab". Is there anything wrong in below code?
private static void removeDuplicates(char[] str) {
if (str == null)
return;
int len = str.length;
if (len < 2)
return;
int tail = 1;
for (int i = 1; i < len; ++i) {
int j;
for (j = 0; j < tail; ++j) {
if (str[i] == str[j])
break;
}
if (j == tail) {
str[tail] = str[i];
++tail;
}
}
str[tail] = 0;
}
I am not able to figure out what is wrong in the above code after debugging.
It needs to do like this
if (str == null)
return;
int len = str.length;
if (len < 2)
return;
for(int i = 0; i <len; i++) {
for(int j = i+1; j<len; j++) {
if(str[i] == str[j]) {
str[j] = 0;
}
}
}
But the result will look like this a[space]b[space][space][space] because we just set the character to 0.
This question's time complexity is O(n^2).
But if your input char array has some restrict, such as char array is between 'a' and 'z'. It has O(n) method to solve.
The idea of that is use bits of one variable to save charactor appeared.
void removeDuplicate(char s[])
{
int len = strlen(s);
if(len < 2) return;
int check = 0, p = 0;
for(int i=0; i < len; ++i)
{
int v = (int)(s[i]-'a');
if((check & (1 << v))==0)
{
s[p++] = s[i];
check |= (1 << v);
}
}
s[p] = '\0';
}
ps. This code is from other website.
So basically we will mark the duplicates first with some special characters and then we need to remove those special characters. Time complexity would be O(n^2).
char[] str = "aabbabcdcd".toCharArray();
int len = str.length;
if (len < 2)
return;
Step-1, Mark the positions with some special characters like 0 or $
for (int i = 0; i < len-1; ++i) {
for(int j=i+1;j<len;j++)
{
if(str[i]==str[j])
{
str[j]=0; //<---mark the positions
}
}
}
Output: a b cd
Step-2, We need to remove those inner black space
int j;
for(int i=1;i<len-1;i++)
{
if(str[i]==0)
{
for(j=i+1;j<len;j++)
{
if(str[j]!=0)
{
break;
}
}
if(j!=len) //<-----replace with blank
{
str[i] = str[j];
str[j]=0;
}
}
}
Output: abcd

value of array changes for no reason JAVA

The contents of arr[] change somehow so when I try to print the contents of the returned array from the method it says null.
This method takes a text file path from the user and puts every individual word into an array and compares it with a dictionary array (book) and the ones that aren't in the dictionary are supposed to be returned in dif[].
int d = arr.length-compare(book, arr);
int l = 0;
int bi = 0;
String[] dif = new String[d];
if (d >= 1) {
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < book.length; a++) {
if (book[a].equalsIgnoreCase(arr[i])) {
//IF I TRY TO PRINT ARR[I] HERE IT HAS A VALUE
bi = 1;
}
}
if (bi != 1) {
dif[l] = arr[i];
//HERE ARR[I] IS NULL
System.out.println(arr[i]);
l = l + 1;
}
}
return dif;
}
else {
return null;}
}
for (int i = 0; i < arr.length; i++) {
for (int a = 0; a < book.length; a++) {
if (book[a].equalsIgnoreCase(arr[i])) {
//IF I TRY TO PRINT ARR[I] HERE IT HAS A VALUE
bi = 1;
}
}
if (bi != 1) {
dif[l] = arr[i];
//HERE ARR[I] IS NULL
System.out.println(arr[i]);
l = l + 1;
}
}
You never reset the value of bi, so as soon as there is one entry in arr that is equal to one entry in book all subsequent values in arr will be outputted which might include null.

Create a new array containing the index of every occurrance of a target value

I'm trying to make a method that creates a new array containing the index of every occurrence of a target value. I have to use 2 loops for this. The first counts how many times the target occurs. Then create the new array, to hold this many indexes. Then the second loop puts the indexes into the new array.
I've written the code below, but it throws java lang Array Out Of Bound Exception:5, on the line result [ i ] = f [ i ] ;
public class FindAll {
public FindAll() {
int a[] = {7, 8, 9, 9, 8, 7};
print(findAll(a, 7));
print(findAll(a, 2));
}
public void print(int p[]) {
System.out.print("{");
int i;
for (i = 0; i < p.length - 1; ++i) {
System.out.print(p[i] + ", ");
}
System.out.print(p[i]);
System.out.print("}");
}
public int[] findAll(int f[], int target) {
int count = 0;
for (int i = 0; i < f.length; ++i) {
if (f[i] == target) {
count++;
}
}
int result[] = new int[count];
for (int i = 0; i < f.length; ++i) {
if (f[i] == target) {
result[i] = f[i];
}
}
return result;
}
}
Try this
int result[] = new int[count];
int index = 0;
for (int i = 0; i < f.length; i++)
{
if (f[i] == target){
result[index] = f[i];
index++;
}
}
Replace the findAll function with this
public int[] findAll(int f[], int target) {
int count = 0;
for (int i = 0; i < f.length; ++i) {
if (f[i] == target)
count++;
}
if(count == 0) return null;
int result[] = new int[count];
for (int i = 0, curr = 0; i < f.length; ++i) {
if (f[i] == target)
result[curr++] = i;
// Here you have to store the index not the value
}
return result;
}
Add these lines to print method to avoid an exception when the array is null
if(p == null || p.length == 0){
System.out.println("P is null or empty");
return;
}
It will work fine!
The result array you are creating is the size of the number of occurrences of the target, not the size of the original array.
public int[] findAll(int f[], int target)
{
int count = 0;
for (int i = 0; i < f.length; ++i)
{
if (f[i] == target)
count++;
}
int result[] = new int[count]; // This is the size of number of occurrences of target
for (int i = 0; i < f.length; ++i) // 'i' will go up to size of original array
{
if (f[i] == target)
result[i] = f[i]; // You are trying to put the element of the original array in to the same index of your result!?
}
return result;
}
Instead, you need to be adding, for each target element, it's index:
int resultIndex = 0;
for (int i = 0; i < f.length; i++) {
if ( f[i] == target ) {
result[n] = i;
n++;
}
}

How to check array for possible divisors?

Creating the array, I am letting the user choose the length:
StartNum = scan.nextInt();
int[] NumBox = new int[StartNum];
for (int i = 1; i < NumBox.length+1; i++)
{NumBox[i - 1] = i;}
NumBox[0]=0;
Assuming there are other methods that can change cells in NumBox to 0, how would I use a for loop to check each cells in the array for any divisor? If there are no divisors for the cell in the array, it will then become a 0. For example, if the array is [0,2,0,4,0,6,7,8,9] 9,2 and 7 would become a 0.
The code below is what I tired but didn't get far.
boolean NoDiv=false;
for (int a=1; a < NumBox.length+1; a++)
{
a++
for (int check=1; a < NumBox.length+1; check++)
{
if (NumBox[a-1]% check == 0 && NumBox[a-1] !=0)
{
NumBox[a-1] = 0;
}
}
}
for (int i = 0; i < NumBox.length; i++) {
if (NumBox[i] == 0) continue;
boolean hasDivisor = false;
for (int j = 0; j < i; j++) {
if (NumBox[j] == 0) continue;
if (NumBox[i] % NumBox[j] == 0) {
hasDivisor = true;
break;
}
}
if (!hasDivisor) NumBox[i] = 0;
}

Categories