I have a list containing a set of numbers in ascending order. I have another set of numbers containing a few elements.
I need to check the difference between elements in a list such that they are present in a set and if the difference is 5 or more. I need to delete all the numbers higher than it. Example:
list contains {1,5,7,8,12,17,18}
set= {7,12,21}
I run a loop in a list pointing two elements. In the first 1 and 5. Since both of them are not in the set no need to calculate the difference.
We continue the same process till 7 and 8. Here, I need to check the difference between 7,8 but since 8 is not in the set, I need to do increments such that the difference between 12 and 7 is calculated. If the difference is 5 or more I need to delete all elements from the list which are higher than the number from set. i.e 7
In this case elements deleted from list are {8,12,17,18}. Only numbers below the number from the set are deleted with a condition that at least two numbers from the set are in the list and their gap is at least 5.
Here is the sample code I have written so far
for (int i=1;i<list.size();i ){
if(set.contains(list[i]) && set.contains(list[i 1]))
This checks only successive values and doesn't move ahead. How to make this dynamic?
CodePudding user response:
Please find the below code, and in the final if block you can put the code to do print, remove etc on the element.
import java.util.ArrayList;
import java.util.List;
import java.util.*;
class HelloWorld {
public static void main(String[] args) {
List<Integer> ScoreList = new ArrayList<Integer>();
ScoreList.add(1);
ScoreList.add(5);
ScoreList.add(7);
ScoreList.add(12);
ScoreList.add(17);
ScoreList.add(18);
ScoreList.add(21);
ScoreList.add(31);
ScoreList.add(41);
Set<Integer> a = new HashSet<Integer>();
a.add(7);
a.add(12);
a.add(21);
for(int i=0; i<ScoreList.size(); i )
{
for(int j=0;j<ScoreList.size();j )
{
if(a.contains(ScoreList.get(i)) && a.contains(ScoreList.get(j)))
{
if(ScoreList.get(j) - ScoreList.get(i) >5)
{
System.out.println(ScoreList.get(i) " ");
// Add your code here to remove and add it to another list.etc.
}
}
}
}
}
}