Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How can I remove all occurrences of an integer, say, 17 in this example from a given array in java?
I tried setting entries to (Integer) null though it doesn't work.
Input array: [0,6,0,17,1,9,17,8,4]
Output array: [0,6,0,1,9,8,4]
for(int i =0;i<ansa.length;i++){
if(ansa[i]==17)
{
ansa[i]=(Integer)null;
}
}
This results in
Exception in thread "main" java.lang.NullPointerException
int[] array = { 0,6,0,17,1,9,17,8,4 };
int[] filtered = Arrays.stream(array).filter(i -> i != 17).toArray();
System.out.println(Arrays.toString(filtered));
:-)
Try this one.
Integer[] array ={0,6,0,17,1,9,17,8,4};
List<Integer> list = new ArrayList<Integer>( Arrays.asList(array ));
list.removeAll(Arrays.asList(17 ));
array =list.toArray(new Integer[0]);
System.out.println(Arrays.toString(array));
I tried setting entries to (Integer) null though it doesn't work.
Of course it doesn't, because the size of the array isn't changed. In order to do this, some of the defined java collections (in particular, the ArrayList and Iterator classes) can provide you of a better approach.
In pseudocode:
Turn array into a List
Iterate over its elements
If the element is the given number
Remove it
Return the List as an Array
You can fill in the blanks, just remember that you can't actually remove an element from an array, because its size is static.
Note: I'm going for the educational approach.
This seems to work - although I suspect people will post better/more efficient solutions.
public void test() {
int[] before = new int[] {0,6,0,17,1,9,17,8,4};
int[] after = remove(before, 17);
System.out.println("Before: "+Arrays.toString(before));
System.out.println("Aftre: "+Arrays.toString(after));
}
private int[] remove(int[] before, int remove) {
// Work out how long it must be.
int keep = 0;
for ( int i = 0; i < before.length; i++ ) {
if(before[i] != remove) {
keep += 1;
}
}
// Make the new one
int[] after = new int[keep];
// Fill it in.
for ( int i = 0, j = 0; i < before.length; i++ ) {
if(before[i] != remove) {
after[j++] = before[i];
}
}
return after;
}
Thats one possible solution:
int[] array1 = new int[]{0,6,0,17,1,9,17,8,4};
ArrayList<Integer> result = new ArrayList<Integer>();
boolean flag = true;
for(int i = 0; i < array1.length; i++) {
for(int j = 0; j < array1.length; j++) {
if(array1[i]==array1[j]&&i!=j) {
flag = false;
}
}
if(flag) {
result.add(array1[i]);
}
else{
flag = true;
}
}
System.out.println(result);
I think, if you don't want to use an ArrayList, you will have to count how many 17 are in the array and create a new one with ansa.length-count fields
You cannot remove items from an array you are currently using a for loop to cycle through. At the moment you are getting to the end of your array and looking for the next value even though you deleted it. The array length indicator (ansa.length) does not auto update as you are thinking.
You should use List and an iterator to cycle through the list.
You can use then use the .remove function
You are almost done!!
Integer[] ansa = new Integer[] { 0, 6, 0, 17, 1, 9, 17, 8, 4 };
for (int i = 0; i < ansa.length; i++) {
if (ansa[i] == 17) {
ansa[i] = (Integer) null;
}
}
for (Integer integer : ansa) {
System.out.print(integer+","); //0,6,0,null,1,9,null,8,4,
}
You are facing issue, Because you declared primitive I guess like,
int[] ansa = new int[] // Primitive
Related
I am trying to get pass a coding challenge. The goal is to remove duplicate (after a defined 'n-th' time) from the array.
For example,
int[] arr;
arr = new int[] {1, 2, 2, 3, 3, 3, 4, 5, 5};
arr = tester(arr,1);//return 1,4. anything having more then 1 occurrence is removed from the //array
I have 2 questions here.
I understand that although java is mainly call by value,
more detail: https://stackoverflow.com/questions/12757841/are-arrays-passed-by-value-or-passed-by-reference-in-java#:~:text=Longer%20answer%3A,object%20that%20the%20caller%20sees.
and
Is Java "pass-by-reference" or "pass-by-value"?
.
so am I not able to modify/return the value of arr without re-assigning it as I need to use the "new" keyword later on.
example:
I am not able to do the following:
tester(arr,1) //return the original value, as the method has a "new" when converting the
//arraylist into array. There seems to be no work around for this as well..
I am also only passing 2 out of 10 test case in the coding challenge, I am not very sure why. I have also attempted to error handle with string inputs, or length=0 or null, to no success. (or implemented it in hashmap for sake of time complexity)
It does not seem like my logic has an issue, I am just not sure what are the test case as it is hidden.
I believe part of the challenge requires me to return it in the original array, meaning changing the value of arr itself, but i cant find a way to do it without using the new keyword.
Any ideas anyone?
public static int[] tester(int[] data, int n)
{
ArrayList<Integer> storeNon_dup = new ArrayList<Integer>();
//nested for loop to run through the array
//store in arrayList if criteria valid
for(int i = 0; i < data.length; i++)
{
int counter = 0;
for(int j = 0; j< data.length; j++)
{
if(data[i] == data[j])
{
counter++;
}
}
//if not duplicate in n-th occurence, add to list
if(counter<=n)
{
storeNon_dup.add(data[i]);
}
}
//convert arraylist to array
int[] container = new int[storeNon_dup.size()];
for(int i = 0; i<storeNon_dup.size(); i++)
{
container[i] = storeNon_dup.get(i);
}
return container;
}
Alternate solution by using HashMap.
public static List tester(int[] data, int n) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i=0; i<data.length; i++) {
if(map.containsKey(data[i])) {
map.put(data[i], map.get(data[i])+1);
}else {
map.put(data[i], 1);
}
}
List lst = new ArrayList<Integer>();
for(Integer key : map.keySet()) {
if(map.get(key)<=n) {
lst.add(key);
}
}
return lst;
}
This question already has answers here:
Trying to find all occurrences of an object in Arraylist, in java
(6 answers)
Closed 3 years ago.
Assumed
ArrayList<Integer> list = Arrays.asList(new Integer[] {1,2,3,4,5,6,1,8,9});
Find second occurence
I want to get the index of the second finding of the (multiple) contained element "1" but list.indexOf(1) will always return 0 (as it's the first finding).
Performance
I want to do this without using loops like for or while.
Since I need it for a game, using loops wouldn't be efficient at all.
EDIT: Is there any way to get "indexOf" some element without iterator ?
You cannot do this without iterating.
indexOf iterates, for example.
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
Same is valid for lastIndexOf.
As you can see no Iterator<Integer> is used at all, if that is what worries you.
And, btw, this isn't a performance concern.
Do you have arrays with millions of elements? If you have, consider changing data structure type.
If you are very much concerned about performance, use a HashMap<Integer, List<Integer>>. Then if your want n'th occurence of an element m, you can do map.get(m).get(n). Your map contains elements and their corresponding indexes.
Once your map is built, the time complexity for your query would be O(1)
Example:
public static void main(String[] args){
int[] a = {1, 2, 1, 3, 4, 1};
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
for(int i = 0; i < a.length; i++){
if(map.containsKey(a[i])){
map.get(a[i]).add(i);
}else{
map.put(a[i], new ArrayList<Integer>());
map.get(a[i]).add(i);
}
}
// second index of 1. Note that index starts from 0.
System.out.println(map.get(1).get(1));
}
Result:
2
list.subList(list.indexOf(1) + 1, list.size()).indexOf(1)
list.indexOf(1, list.indexOf(1) + 1);
The first parameter 1 being the object to be searched.
The second parameter list.indexOf(1) + 1 being the starting index for the search.
Can I re-declare an Array that is already declared?
So I am trying to go through a LinkedList and get every index which includes "null" as an Element and add those indexes to an array of ints.
The problem I have is : The array is already declared as:
int[] solution = new int[0];
Can i redeclare it once again like lets say:
int newSize = 10;
solution = [newSize];
Does that work?
int k = 0;
int counter = 0;
if(!isEmpty())
{
for(int j = 0 ; j < size(); j++)
{
if(current.getContent().equals(null))
{
counter++;
}
}
result = new int[counter];
for(int i = 0 ; i < size(); i++)
{
if(current.getContent().equals(null))
{
result[k++] = i ;
}
}
}
I tried printing out the elements of Result but all i get is well... an empty array.
Short answer (as mentionned on java documentation => link)
The length of an array is established when the array is created. After creation, its length is fixed.
Some more details:
When you use :
int[] solution = new int[0]
you create an array that can hold 0 element and ask "solution" to refert to it.
If later on your code you use solution = new int[10] you will create an array that can hold 10 elements and ask "solution" to refer this new array.
The previous array still exists somewhere in the memory.
Search for "java memory management" if you want a full explanation.
This question already has answers here:
What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?
(5 answers)
Closed 8 years ago.
I cannot see anything wrong with my code:-
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
int[] A = new int[] {2, 1, 1, 2, 3, 1};
ArrayList<Integer> foundNumbers = new ArrayList<>();
int distinct = 0;
for(int i = 0; i < A.length-1; i++) {
if(foundNumbers.get(i-1) == null) {
foundNumbers.set((i-1), A[i]);
distinct++;
}
}
System.out.println(distinct);
}
}
I want to check if the value of Array element i has already been assigned to ArrayList element i-1, then increment the distinct variable and print how many distinct values are in the array.
Here's the exception when I change the value of i to 1:-
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
at tdd.Main.main(Main.java:19)
The list is completely empty. You haven't put anything in it, yet you're trying to read elements from it with the foundNumbers.get call, so any index will be out of bounds.
To add unique elements from A to the list, get and set are simply the wrong list methods to call, use contains and add if that's what you want to do:
for (int x : A) {
if (!foundNumbers.contains(x))
foundNumbers.add(x);
}
Here is the same logic as above written in a more verbose fashion that might make it easier to understand what is involved:
for (int i = 0; i < A.length; i++) {
boolean found = false;
for (int j = 0; j < foundNumbers.size(); j++) {
if (A[i] == foundNumbers.get(j)) {
found = true;
break;
}
}
if (!found) {
foundNumbers.add(A[i]);
}
}
You don't need the separate distinct variable, since it is simply foundNumbers.size().
Although this works, a List is not very efficient for eliminating duplicates if the count of elements is large, since every contains call requires another loop through the contents of the list. A Set automatically prevent duplicates and internally structures its contents in a way that makes it efficient to do so:
Set<Integer> distinct = new TreeSet<>();
for (int x : A) distinct.add(x);
System.out.println(distinct); // [1, 2, 3]
for(int i = 0; i < A.length-1; i++) {
if(foundNumbers.get(i-1) == null) {
In the first iteration of that loop, i will be set to zero, so the second line is doing .get(-1).
There are multiple issues:
when i is 0, you try to get i-1=-1th element which is not valid
Even when you fix this, since you dont have elements in list, you will still get IndexOutOfBoundsException, since you havent stored any elements yet and your list is empty.
Your loop should be:
for (int i = 0; i < A.length - 1; i++) {
if (foundNumbers.size() > i && foundNumbers.get(i) == null) {//or better you use contains method of list like foundNumbers.contains(someNumber);
foundNumbers.add(A[i]);
distinct++;
}
}
class ArrayApp{
public static void main(final String[] args){
long [] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
for(i=0;i<arr;i++) {
System.out.println(arr[i]);
}
}
}
I get this error,
ArrayApp.java:10: operator < cannot be applied to int,long[]
for(i=0;i<arr;i++) {
^
You need to use the size of the array, which would be arr.length.
for (int i = 0; i < arr.length; ++i)
As of Java 1.5, you can also use the for each loop if you just need access to the array data.
for ( long l : arr )
{
System.out.println(l);
}
arr is an object of long[] , you can't compare int with it.
Try arr.length
Alternatively You should go for
for(long item:arr){
System.out.println(item);
}
You want arr.length
The question has to be seen in the context of a previous question!
From this former question I remember that you actually have a logical array inside a physical array. The last element of the logical array is not arr.length but 2, because you've "added" two values to the logical array.
In this case, you can't use array.length for the iteration but again need another variable that store the actual position of "the last value" (1, in your case):
long[] arr;
arr= new long[100];
int i;
arr[0]=112;
arr[1]=111;
int nElem = 2; // you added 2 values to your "logical" array
for(i=0; i<=nElem; i++) {
System.out.println(arr[i]);
}
Note - I guess, you're actually learning the Java language and/or programming. Later on you'll find it much easier to not use arrays for this task but List objects. An equaivalent with List will look like this:
List<Integer> values = new ArrayList<Integer>();
values.add(112);
values.add(111);
for (Integer value:values)
System.out.println(value);
Long arr = new Long[100];
arr[0]=112;
arr[1]=111;
for(int i=0;i<arr.length;i++) {
if (arr[i] != null ) {
System.out.println(arr[i]);
}
}
if you want to show only those which are filled.
You can solve your problem using one line of code:
Arrays.asList(arr).toString().replace("[", "").replace("]", "").replace(", ", "\n");
See http://java.dzone.com/articles/useful-abuse for more similar tricks.