Improve this nested loop to work better in Mastermind - java

ArrayList<Integer> co = new ArrayList<Integer>();
ArrayList<Integer> gu = new ArrayList<Integer>();
System.out.println(code.size());
System.out.println(guess1.size());
for(int b = 0; b < code.size(); b++) {
for (int i = 0; i < guess1.size(); i++){
if(guess1.get(i).equals(code.get(b)) && (i == b) && ((Arrays.asList(co).contains((b))))&&(!(Arrays.asList(gu).contains(i)))){
co.add(b);
gu.add(i);
hintboard.add(Hints.B);`enter code here`
System.out.println(guess1);
System.out.println(co);
System.out.println(gu);
}else if(guess1.get(i).equals(code.get(b)) && (!(Arrays.asList(co).contains((b))))&&(!(Arrays.asList(gu).contains(i)))){
co.add(b);
gu.add(i);
hintboard.add(Hints.W);
//System.out.println(hintboard);
What I am trying to do here is that, check if i is equal to b at the same position and make sure the index is not present in arrayList of co and gu. however the statement is true every time even though the first index of b is added in co and the index of i is added to gu.

Im not sure if i understood your whole problem, but here it goes anyways:
Your problem is that you use:
Arrays.asList(co).contains((b))
First of all the parentheses around b is unnecessary/useless so you should remove them.
And the reason it doesnt work is that Arrays.asList will create a list with all the elements passed into it. The intended use would be something like this:
Arrays.asList(1, 2, 3);
Which will return the list:
[1, 2, 3]
Your code puts a list in to a list so the output would be something like this:
[[YOUR, LIST, ITEMS]]
and your code of Arrays.asList(co).contains((b)) will do a test similar to this psudo-code:
[[1, 2, 3]].contains(2)
This will always return false since the main list does not contain 2 it only contains a sublist [1, 2, 3] It would work if you did this Arrays.asList(co).get(0).contains((b)) as .get(0) would return the first sublist, but this only correct a mistake you created, so the correct way to write the line in the first place would be:
co.contains(b)
I can not tell you if your code works as a whole, after this fix, as there is many ways to play mastermind, and i am not sure of the rules you play by. Also I do not fully understand the full process of your code, only the concept. Anyways here is your corrected code (Hope this helped you understand):
ArrayList<Integer> co = new ArrayList<Integer>();
ArrayList<Integer> gu = new ArrayList<Integer>();
System.out.println(code.size());
System.out.println(guess1.size());
for(int b = 0; b < code.size(); b++) {
for (int i = 0; i < guess1.size(); i++) {
if (guess1.get(i).equals(code.get(b)) && (i == b) && co.contains(b) && !gu.contains(i)) {
co.add(b);
gu.add(i);
hintboard.add(Hints.B);
System.out.println(guess1);
System.out.println(co);
System.out.println(gu);
} else if (guess1.get(i).equals(code.get(b)) && !co.contains(b) && !gu.contains(i)) {
co.add(b);
gu.add(i);
hintboard.add(Hints.W);
//System.out.println(hintboard);
}
}
}

Related

How to insert an integer into a sorted List in Java?

I would like to write a function insertAndSort() that will take as parameter an Integer "num" and a List of integers "list". Let's assume the List lust is already sorted.
The algorithm is supposed to work this way :
Add "num" to L and keep the List sorted after "num" has been added.
Return the sorted List.
WARNING : We do not know whether the list is sorted ASC or DESC. And that is precisely my problem !
Example :
if "num" = 4 and L = {1, 3, 5, 7}, then the final sorted List is {1, 3, 4, 5, 7}
if "num" = 4 and L = {7, 5, 3, 1}, then the final sorted List is {7, 5, 4, 3, 1}
I can not use sorting API such as Collections.sort or Collections.reverseOrder etc...
So far, I've produced this code :
public static void main(String[] args) {
int num = 4;
List<Integer> myList = Arrays.asList(1, 3, 5, 7);
List<Integer> newList = new ArrayList<Integer>();
newList = insertAndSort(myList, num);
System.out.println(newList);
}
public static List<Integer> insertAndSort(List<Integer> list, int num) {
List<Integer> listSecond = new ArrayList<Integer>(list.size()+1);
for(int i = 0; i <= list.size() ; i++) {
if(num < list.get(i)) {
if(!listSecond.contains(num)){
listSecond.add(num);
} else {
listSecond.add(list.get(i-1));
listSecond.add(list.get(i));
break;
}
} else {
listSecond.add(list.get(i));
}
}
return listSecond;
}
The problem is that this seems to be working with a single type of List: the ascending one.
When I take a sorted descending List, it does not work anymore.
Do you have any idea to make this work with both type of List ?
Thanks and Regards.
First, you need to detect the sort order in the existing list.
If the list is empty, you don’t need to care, just add your element, you cannot break any existing sort order.
If the list contains one element, I cannot tell you what to do. Options include tossing a coin and throwing an exception, but there are more.
If the list contains two or more elements, iterate through them except for the last element, each time comparing the current element with the element in the next higher index. As soon as you encounter a pair of elements that are not equal, you know the sort order. If you only encounter equal elements, all the elements in the list are equal, and again I cannot tell you what to do.
Once you’ve detected a sort order, I suggest a big if-else statement to handle the two cases separately.
You already have the code for the ascending case. Except it doesn’t always work. If I try to insert 4 into { 1, 3, 5 }, I get an ArrayIndexOutOfBoundsException. If I try with { 1, 3, 5, 7, 9 }, the 9 is lost. You should probably find a fix for that.
You should be able to handle the descending case similarly to the ascending case. Only use num > list.get(i) instead of num < list.get(i).
First, you need to check whether the list is sorted in ASC or DESC. That's easy: compare the 1st two elements look for two consecutive non-identical elements and see whether the first one is greater or the second one (thanks tom for correcting the mistake).
Now, for a list sorted in ascending order, convert list to an ArrayList. Then, add num to the ArrayList and convert it to a TreeSet, since TreeSets sort their elements in ascending order. Finally, reassign the ArrayList to hold the contents of the TreeSet and return it.
For a list sorted in descending order, first, convert the TreeSet to an ArrayList, then iterate over this ArrayList in reverse order and add the elements to a new ArrayList. Return the second ArrayList.
public List<Integer> insertAndSort(List<Integer> list, int num){
ArrayList<Integer> a = new ArrayList<Integer>(list);
a.add(new Integer(num));
TreeSet t = new TreeSet(a);
a = new ArrayList<Integer>(t);
int l = list.size();
for(int i=1; i<l; i++){
if(list.get(i) != list.get(i-1))
break;
}
if(list.get(i) > list.get(i-1)) //ASC
return a;
else{ //DESC
ArrayList<Integer> a2 = new ArrayList<Integer>();
for(int i = a.size() - 1; i >= 0; i--)
a2.add(a.get(i));
return a2;
}
}
I would proceed with something like the code below. A few remarks :
it is possible to decide sort order if and only if there is at least 1 element AND first and last elements have different values.
the line int oo = list.get(p2) - list.get(p1); compute the
difference between the last and first element (negative = DESC,
positive = ASC)
the variable ox is positive if and only if the
added element is after the element pointed by the variable p3
whatever the order.
the position is found by a binary search algorithm by choosing p3 between p1 and p2 and deciding if the element is before or after p3.
This is not fully tested bu works with the examples you gave :
// static List<Integer> list = new ArrayList<>(Arrays.asList(7, 5, 3, 1));
static List<Integer> list = new ArrayList<>(Arrays.asList(1, 3, 5, 7));
static void add(int x)
{
// fixed code below (see Ole V.V. comment)
}
static public void main(String [ ] args)
{
add(4);
for(int x: list)
System.out.println(x);
}
EDIT: to be complete (see Ole V.V. comments)
When the new element is to be inserted before the first or after the last, two simple O(1) tests may be performed ; the general case has O(log N) complexity, this is more efficient than traversing the entire list which is O(N).
Be carefull too when comparing elements to deduce sort order, there may be several equal values ; the best is to compare the first and the last elements, this is O(1) - again better than O(N).
Algorithmic complexity is an important matter (to me) and was the primary aim of my post. The code of the add function becomes :
static void add(int x)
{
int p1 = 0;
int p2 = list.size() - 1;
if(list.size() == 0 || list.get(p1) == list.get(p2))
throw new IllegalStateException("Unable to decide sort order");
int oo = list.get(p2) - list.get(p1);
if(oo * (x - list.get(p1)) <= 0) // new element is before first
list.add(0, x);
else if(oo * (x - list.get(p2)) >= 0) // new element is after last
list.add(x);
else
{
while (p1 + 1 < p2)
{
int p3 = (p1 + p2) / 2;
int ox = (x - list.get(p3)) * oo;
if(ox >= 0) // new element is after p3
p1 = p3;
if(ox <= 0) // new element is before p3
p2 = p3;
}
list.add(p2, x);
}
}
Note : there may be still some undealed side effects. If the asker is interested, I am ready to give further help - just ask.
Your code and what you say is two different things.
Based on code you made, I see that List can't contain more than one instance of same value.
If thats the case, main method should look like this:
public static void main(String[] args){
int num = 4;
List<Integer> myList = Arrays.asList(1, 3, 4, 5, 7);
List<Integer> newList;
if (!myList.contains(num)) {
newList = insertAndSort(myList, num);
} else {
newList = copyList(myList);
}
System.out.println(newList);
}
if thats not the case:
public static void main(String[] args){
int num = 4;
List<Integer> myList = Arrays.asList(1, 3, 4, 5, 7);
List<Integer> newList;
newList = insertAndSort(myList, num);
System.out.println(newList);
}
Methods that main method use:
Assuming we can only know how list is sorted by values in list, we have to decide default sort method when there is only 1 value or all values are same. I picked ASC as default. If elements can be of same value and we are certain list is sorted its best to compare lowest value in list with the highest one. With this approach we have to compare 2 elements only once.
So method to see if list is sorted DESC would look like this:
private static boolean isDesc(List<Integer> list) {
return list.get(0) > list.get(list.size() - 1);
}
If method returns true its sorted DESC. With returning false its ASC. If we want to change default value, when values don't tell us how its sorted and we want it to be DESC we would replace '>' sign with '>='
private static boolean isDesc(List<Integer> list) {
return list.get(0) >= list.get(list.size() - 1);
}
Code for as you called it insertAndSort:
public static List<Integer> insertAndSort(List<Integer> list, int num) {
List<Integer> listSecond = new ArrayList<Integer>(list.size() + 1);
boolean isDescSortOrder = isDesc(list);
if (isDescSortOrder) {
int i = 0;
while ((i < list.size()) && (list.get(i) > num)) {
listSecond.add(list.get(i));
i++;
}
listSecond.add(num);
while (i < list.size()) {
listSecond.add(list.get(i));
i++;
}
} else { // is asc sort order
int i = 0;
while ((i < list.size()) && (list.get(i) < num)) {
listSecond.add(list.get(i));
i++;
}
listSecond.add(num);
while (i < list.size()) {
listSecond.add(list.get(i));
i++;
}
}
return listSecond;
}
Depending on how its sorted code got devided into 2 blocks. As we don't know on each iteration will be right place to insert our num value its better to use while loop. Using for loop and checking everytime if num value already exists in list is counterproductive. On top of that I dunno if your application should allow same values in the list. If I assume it should, you can't add num value if it already existed in the list with for loop and checking with contains every iteration.
And just to copy the table when list already has the element and we don't want to add elements that are already incuded:
public static List<Integer> copyList(List<Integer> list) {
List<Integer> listSecond = new ArrayList<Integer>(list.size());
for (int i = 0; i < list.size(); i++) {
listSecond.add(list.get(i));
}
return listSecond;
}
Also based on good programming practices I'd recommend to name methods based on what they do.
Calling method insertAndSort is asking for trouble. If I seen it, I'd say it alters list we are giving in parameter. Then it sorts it.
So putting unsorted list in it would give us unwanted outcome.
And I'd still ask myself why does it return a List when we are inserting an item to already existing list? I'd rather name it:
public static List<Integer> copySortedWithNewValue(List<Integer> sortedList, int newValue)
Try to use PriorityQueue. This collection contains a sorted sequence of elements which could be duplicated.

Reversing and combining a list

I have the following list:
list 1= 1,2,3,4,5,6
I am trying to make a list that contains the following:
list c= 1,6,2,5,3,4
However, I cannot figure out how to do it. I know how to iterate through 6 but I don't know how to get to the last number and iterate backwards. I know a ListIterator can be used to go backwards but I still cannot figure it out.
This is what I did to add the original, I just don't understand how to iterate backwards:
public static void q(Set<String>list1)
{
Set<String>combined = new HashSet();
Iterator<String> forward = list1.iterator();
Iterator <String> backwards = list1.iterator();
for (int i=0; i<list1.size(); i++)
{
combined.add(forward.next());
//code to go backwards
}
}
This isn't to solve your problem, but rather to show you how ListIterator can be used to go backwards since you couldn't figure it out.
List<Integer> list = new ArrayList<>();
for (int n = 1; n <= 6; n++) { // Add 1, 2, ... 6 to list
list.add(n);
}
ListIterator it = list.listIterator(list.size());
while (it.hasPrevious()) {
System.out.println(it.previous());
}
The listIterator method of a List allows you to specify the index to start at as a parameter.
The hasPrevious method of the ListIterator checks if there is a previous element (self-explanitory).
The previous() method of the ListIterator returns the previous element in the list and moves the cursor position backwards.
Using ListIterator you can go forwards and backwards as you please using next() and previous() respectively.
Alternatively, using a for statement instead of using ListIterator...
for (int i = list.size() - 1; i >= 0; i--) {
System.out.println(list.get(i));
}
I am not sure if you really wanted a Set given you were talking about lists. This is the idea without explicitly using list iterators however they would behave the similarly.
How to use a list iterator: http://www.java2s.com/Tutorial/Java/0140__Collections/ListIteratorInreverseorder.htm
public static List<Integer> interleaveFrontBack(List<Integer> list) {
if (list.size() <= 2){
return new LinkedList<Integer>(list);
}
List interleaved = new LinkedList<Integer>();
int end = list.size() - 1;
int front = 0;
while (end > front){
interleaved.add(list.get(front++));
interleaved.add(list.get(end--));
}
// if odd sized list need to add last element
if (end == front){
interleaved.add(list.get(front));
}
return interleaved;
}
Simple Algo would be
1.) just use two positions , i =0 for increment and j = size-1 for decrements
2.) add elements to new list using i and j positions while traversing to the middle of the content list
Integer []aa=new Integer[]{1,2,3,4,5,6};
List<Integer> list =Arrays.asList(aa);
int n=list.size();
List<Integer> list2 =new ArrayList<>();
for (int i = 0,j=list.size()-1; i <n/2 ; i++,j--) {
list2.add(list.get(i));
list2.add(list.get(j));
}
// if(n%2!=0) list2.add(list.get(n/2)); // un-comment this , to handle
// odd list size too ,dynamism
list2.forEach(i->System.err.print(i+" "));
Output:
1 6 2 5 3 4
Assuming that you simply want to put the last element of the first list on the second index, you can do something like:
List<Integer> input = Arrays.asList(1, 2, 3, 4, 5, 6);
// create new list that initially contains first and last element of input list
List<Integer> output = new ArrayList<>(Arrays.asList(input.get(0), input.get(input.size()-1)));
// now iterate the "in between" input elements and add them to output
for (int i=1; i < input.size() -1 ; i++) {
output.add(input.get(i));
}
System.out.println("in: " + input);
System.out.println("out: " + output);
Of course, the above is just one way of doing this; there are many others
Not sure what your exactly looking for and where your code has broke. You could try:
List<Integer> intergers = new ArrayList<>();
for(int i = 1; i < 7; i++) {
if(i < 6) {
intergers.add((i-1), i);
} else {
intergers.add(1, i); //when i is 6 place it in the second index
}
}
System.out.println("List: " + intergers.toString());
With java list you can chose the index and if that index has a value the value well be pushed to the next index. It was the simplest thing I could think of. This is what it printed out:
List: [1, 6, 2, 3, 4, 5]

If condition inside nested for loop in android

I have two ArrayLists of the same model class (i.e ListA and ListB) to which I have added the same data.
Then I added some data only in the second arraylist ListB.
Now, I want to fetch only that data which is different in both ListA and ListB and store the result in a third arraylist ListC.
I tried below code. However, all elements are stored in ListC, as opposed to only those that are different:
ArrayList<C> ListC = new ArrayList<>();
for (int i = 0; i < ListA.size(); i++) {
for (int j = 0; j < ListB.size(); j++) {
if (ListA.get(i).getName() == ListB.get(j).getName()) {
Log.e("Do", "Nothing");
} else {
C c = new C(b.get(j).getName());
ListC.add(c);
}
}
}
Edited Question
ArrayList<Model> a = new ArrayList<>();
Model model = new Model();
model.setName("MaHi");
model.setAge("20");
a.add(model);
ArrayList<Model> b = new ArrayList<>();
Model model = new Model();
model.setName("MaHi");
model.setAge("20");
b.add(model);
Model model2 = new Model();
model2.setName("Ritu");
model2.setAge("21");
b.add(model2);
ArrayList<Model> c=new ArrayList<>();
now I want to fetch that data which is not in either arraylist a or arraylist b (i.e. data of model2) into arraylist of c;
The problem is that you are iterating over all combinations.
Lets say A = [1, 2, 3] and B = [1, 3, 4].
Then, your loop would compare
a=1 with b=1. Both are equal, nothing is done. That's good.
a=1 with b=3. They are not equal, so 3 is added to C. Here is your first problem: 3 actually is in A, but just not in your current iteration.
a=1 with b=4. They are not equal, so 4 is added to C. In this case, this is okay, since 4 is not in A.
a=2 with b=1. They are not equal, so 1 is added to C. However, 1 is actually in A.
and so on
Do you see how your solution does not work? You cannot compare every combination. Instead, you have to check for every element in B, if it is in A. If no, add.
This, directly translated to pseudo code, looks like
// for every element in ListB
for (int i = 0; i < ListB.length(); i++) {
B b = ListB.get(i);
// if this is not in ListA
if (!ListA.contains(b))
ListC.add(b);
}
However, here you should use the for-each loop for (B b: ListB).
And even better, simply use ListC.addAll(ListB); ListB.removeAll(ListA).
(And make sure hashCode and equals are properly written - but that is a different issue.)
Of course, this requires that the Elements in ListA and ListB are of the same type. See Jekin's answer for a solution using less standard library methods that also works with different types (as long as both implement getName(), of course).
This also resolves a second issue, as stated in the comments on your question: You cannot compare Strings with ==, but have to use the equals method. Try x = new String("a"); y = new String("a"); assert(x==y); and assert(x.equals(y));
As you have different class model(A,B) for all list, contains and remove methods might not be helpful for you, so you can use a flag contained like this:
Arraylist<C> ListC = new ArrayList<>();
for (int i = 0; i < ListB.size(); i++) {
// initially, assume that this element is not contained in ListA
boolean contained = false;
// check if this element is contained in ListA
for (int j = 0; j < ListA.size(); j++) {
if (ListA.get(i).getName().equals(ListB.get(j).getName())) {
contained = true;
}
}
// if this element is not contained once in ListA,
if (!contained) {
// add it to ListC
C c = new C();
c.setName(b.get(j).getName());
ListC.add(c);
}
}
This flag indicates, for every element in ListB, if it is contained at least once in ListA.
This ensures that each element in ListB is added at most once—your loop could add each element multiple times.
The problem is here in your code
if (ListA.get(i).getName() == ListB.get(j).getName()) {
Log.e("Do", "Nothing");
} else {
C c = new C();
c.setName(b.get(j).getName());
ListC.add(c);
}
You are using == operator to compare String values. Which is used for reference comparison not value comparison. While this may produce accurate results in many different programming languages but Java handles value comparisons differently. You need to use equals() or equalsIgnoreCase method instead of ==.
So change the line to
if (ListA.get(i).getName().equals(ListB.get(j).getName()))
Note : An == operator can sometimes produce correct results but only because the different Strings' references share the same object not because they have the same value.
Try below code
Arraylist<C> ListC = new ArrayList<>();
for (int i = 0; i < ListA.size(); i++) {
for (int j = 0; j < ListB.size(); j++) {
if (ListA.get(i).getName().equals(ListB.get(j).getName())) {
Log.e("Do", "Nothing");
} else {
C c = new C();
c.setName(b.get(j).getName());
ListC.add(c);
}
}
}
Just let me know if it doesn't resolve your need
i will definitely help you
public static void main(String arg[])
{
ArrayList<String> a=new ArrayList<>();
a.add("hello");
a.add("hi");
a.add("stack");
a.add("overflow");
a.add("empty");
a.add("world1");
ArrayList<String> b=new ArrayList<>();
b.add("hello");
b.add("hi");
b.add("stack");
b.add("overflow");
b.add("empty");
b.add("world");
ArrayList<String> c=new ArrayList<>();
int flag=0;
System.out.println(a.contains("empty"));
for (int i = 0; i < a.size(); i++) {
if(b.contains(a.get(i)))
{
}
else
{
System.out.println("haii");
c.add(a.get(i));
}
}
System.out.println(c.toString());
}
you try this example

I am trying to replaceEvens with a "0" in java, what am I doing wrong?

public static int[] replaceEvens(int[] a) {
int e[] = new int[a.length];
// TODO Insert code here
for (int i = 0; i < a.length; i++){
if( e[0]%2 == 0){
i = 0;
}
}
return e;
}
I believe this code is right but I am getting 0's for all numbers in the Array
the Array is { 5, 15, 24, 35, 2, 7, 8}
I believe your code isn't correct.
First of all, it is quite surprising you don't get an infinite loop. It is not done to mess with the loop-variable in a for-loop. If you would want to do that, use a while-loop.
Second point is that your if-statement contains e, which is up to that point not initialised, and thus only contains variables = 0.
Third point: you always check for the same value e[0], so you only check the first value of array e in every iteration
I hope this helps you enough to correct the code by yourself now...
(otherwise see the answer from beresfordt)
There's several problems;
e[] is not having any values populated in it, it is just being initialised with the length of a
you are setting i to equal zero in your if statement, you probably mean to set e[i] = 0
you are only comparing e[0] %2 == 0, you probably mean to compare e[i] % 2 ==0
putting it all together the for loop you intended to write was probably:
int e[] = a.clone();
for (int i = 0; i < a.length; i++){
if( e[i]%2 == 0){
e[i] = 0;
}
}

Why do I get an ArrayIndexOutOfBoundsException For My ArrayList [duplicate]

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

Categories

Resources