Comparing one arraylist to another and deleting extra items java - java

In this method I am trying to compare all the elements in one arraylist to all the elements in another. Then, if an element in the first arraylist does not equal any element in the second arraylist, delete that element. Something is wrong in either the comparison step or the deletion step, but I am not sure which. Any help would be greatly appreciated.
If you want clarification, don't hesitate to ask.
public static ArrayList<Integer> compareArrayandList(ArrayList<Integer>compare, ArrayList<Integer>array2) {
int[] counter = new int[compare.size()];
for (int x: counter) {
x = 0;
}
for (int i = 0; i < compare.size(); i++) {
counter[i] = 0;
for (int number: array2) {
if (compare.get(i) ==number) {
counter[i]++;
}
}
}
for (int i=0; i<counter.length;i++) {
if (counter[i]==0) {
compare.remove(new Integer(i));
}
}
return compare;
}
EDIT: (courtesy of Memento Mori)
The reason your code is not working is that the positions in your ArrayList are changing when you remove an element. Lets say you removed element 3. Now element 3 is different than it was before.

public class Test {
public static ArrayList<Integer> compareArrayandList(ArrayList<Integer>compare, ArrayList<Integer>array2) {
ArrayList<Integer> a3 = new ArrayList<Integer>();
for (Integer a : compare)
{
if(array2.contains(a))
a3.add(a);
}
System.out.println(a3);
return a3;
}
public static void main(String[] args) {
ArrayList<Integer> a1=new ArrayList<Integer>();
ArrayList<Integer> a2=new ArrayList<Integer>();
a1.add(1);
a1.add(5);
a1.add(3);
a2.add(3);
a2.add(4);
a2.add(5);
a2.add(6);
Test test=new Test();
test.compareArrayandList(a1,a2);
}
}

You are not doing what you really want to do here. You remove the element(s) which its value is i from the compare array instead of the element at position i which is not find in the second for loop.
for (int i=0; i<counter.length;i++) {
if (counter[i]==0) {
//compare.remove(new Integer(i)); // problem is here!
// remove element at index i not element equals to i
compare.remove(i);
}
}

You don't need your counter array. You can do the comparison in one step if you use an iterator. I believe this should work:
public static ArrayList<Integer> compareArrayandList(ArrayList<Integer>compare, ArrayList<Integer>array2) {
ListIterator<Integer> iter = compare.listIterator(compare.size());
while (iter.hasPrevious()){
Integer a = new Integer(iter.previous());
for (int number: array2) {
if (a==number) iter.remove();
}
}
return compare;
}
EDIT: The reason your code is not working is that the positions in your ArrayList are changing when you remove an element. Lets say you removed element 3. Now element 3 is different than it was before.

ListUtils.sum(Arrays.asList(firstarray),Arrays.asList(secondarray))

Related

Java - printing values of HashSet

I have a simple program here which is meant to find all permutations of a set of letters, or a set of words. From what I can see the program does work in finding the number of permutations there are, however it will only print blank lines in place of where the possible permutations should be.
(Note, UI.println() works in every other case in printing outlines, but for some reason will not work here :( )
I included my method here which should do as I've described, as well as a method that should be able to print out the permutations.
Would anyone have any ideas on what I have done wrong here?
public class Permutations {
public List<List<String>> findPermutations(Set<String> items){
Set<String> copyOfItems = new HashSet<String>(items); // a copy of the set of items that can be modified
List<List<String>> ans = new ArrayList<List<String>>(); // where we will collect the answer
counter=0;
//suggested approach:
extendPermutation(copyOfItems, new Stack<String>(), ans);
return ans;
}
public void extendPermutation(Set<String> remainingItems, Stack<String> permutationSoFar, List<List<String>> allPermutations){
/*# YOUR CODE HERE */
Set<String> alternateSet = new HashSet<String>(remainingItems);
if (remainingItems.isEmpty()) {
allPermutations.add(permutationSoFar);
this.counter = counter + 1;
}
for (String str : remainingItems) {
alternateSet.remove(str);
permutationSoFar.push(str);
extendPermutation(alternateSet,permutationSoFar,allPermutations);
permutationSoFar.pop();
}
}
public void setupGUI(){
UI.addButton("A B C D E", ()->{printAll(findPermutations(Set.of("A","B","C","D","E")));});
UI.addTextField("Letters", (String v)->{printAll(findPermutations(makeSetOfLetters(v)));});
UI.addTextField("Words", (String v)->{printAll(findPermutations(makeSetOfWords(v)));});
UI.addButton("Quit", UI::quit);
UI.setDivider(1.0);
}
public void printAll(List<List<String>> permutations){
UI.clearText();
for (int i=0; i<permutations.size(); i++){
for (String str : permutations.get(i)){UI.print(str+" ");}
UI.println();
}
UI.println("----------------------");
UI.printf("%d items:\n", permutations.get(0).size());
UI.printf("%,d permutations:\n", counter);
UI.println("----------------------");
}
public Set<String> makeSetOfLetters(String str){
Set<String> ans = new HashSet<String>();
for (int i=0; i<str.length(); i++){
if (str.charAt(i)!=' '){
ans.add(""+str.charAt(i));
}
}
return Collections.unmodifiableSet(ans);
}
public Set<String> makeSetOfWords(String str){
Set<String> ans = new HashSet<String>();
for (String v : str.split(" ")){ans.add(v);}
return Collections.unmodifiableSet(ans);
}
// Counter for the number of complete permutations found
private long counter = 0;
public void reportCounter(){
if ((counter<<54)==0) {UI.printMessage((counter>10000000)?((counter>>>20)+"M"):((counter>>>10)+"K"));}
}
// Main
public static void main(String[] arguments) {
Permutations p = new Permutations();
p.setupGUI();
}
}
Your code
permutationSoFar.push(str);
extendPermutation(alternateSet, permutationSoFar, allPermutations);
permutationSoFar.pop();
You first add an item to the permutationSoFar,
then you add a refrence (not a deep copy) the permutationSoFar to your allPermutations, only to pop permutationSoFar. Making sure that your permutationSoFar never contains any elements.
When you print the list of permutationSoFars, the allPermutations, you print an list of empty lists.
Just glancing over your problem, this will likely solve the issue:
allPermutations.add(List.copyOf(permutationSoFar));
But, to be blunt, it is like the rest of your code, not the cleanest solution.

Remove all the odd numbers in an ArrayList

I already wrote code to remove all the odd numbers in an ArrayList.
import java.util.*;
public class Odd {
public static void main (String [] args) {
ArrayList <Integer> mylist = new ArrayList<>(Arrays.asList(1, 2, 4, 6, 7));
System.out.println(odd(mylist));
}
public static int odd(ArrayList<Integer> list) {
if (list.isEmpty()) { throw new Error(); }
int a = list.get(0);
List<Integer> toRemove = new ArrayList<>();
for (int si : list) {
if (si % 2 != 0) { toRemove.add(si); }
}
list.removeAll(toRemove);
return a;
}
}
But somehow the result is always 1.Can someone point out what is my mistake?Thank you in advance
There are two problems with your code:
(1) You need to return the list object (contains Integers) after the removal of odd numbers
(2) In order to return the list, you need to change the method signature from int to List<Integer> (as return type):
You can refer the below code with comments:
//change the method signature to return List<Integer>
public static List<Integer> odd(ArrayList<Integer> list) {
if (list.isEmpty()) { throw new Error(); }
List<Integer> toRemove = new ArrayList<>();
for (int si : list) {
if (si % 2 != 0) { toRemove.add(si); }
}
list.removeAll(toRemove);
return list;//return list, not int
}
Check this line:
int a=list.get(0);
You are reading only the first element of the list, which is 1, and not iterating through it.
Use either an iterator (for each, for example) or a regular for loop (using the item count from list).
As other people have indicated, the problem is that you're returning this:
int a = list.get(0);
Thus, you'll always get the first item in the list, regardless of what you do to it after you retrieve it.
Getting rid of a completely and just returning list will fix that issue.

How to check to see which value of a list is highest another another list

This is my situation: I have list A of values. I also have list B which contains a hierarchy of ranks. The first being of the highest, last being of the lowest. List A will contain one, some, or all of the values from list B. I want to see which value from list A is of the highest degree (or lowest index) on list B. How would I do this best?
Just in case its still unclear, this is an example:
List A: Merchant, Peasant, Queen
List B: King, Queen, Knight, Merchant, Peasant
I'd want the method to spit out Queen in this case
Assuming List B is already sorted from Top Rank -> Bottom rank, one arbitary way you could solve it is with
public static void main (String[] args) throws Exception {
String[] firstList = { "Merchant", "Peasant", "Queen" };
String[] secondList = { "King", "Queen", "Knight", "Merchant", "Peasant" };
for (String highRank : secondList) {
for (String lowRank : firstList) {
if (highRank.equalsIgnoreCase(lowRank)) {
System.out.println(highRank);
return;
}
}
}
}
What you are describing is called a "partial ordering", and the proper way to implement the behavior you're looking for in Java is with a Comparator that defines the ordering; something like:
public class PartialOrdering<T> implements Comparator<T> {
private final Map<T, Integer> listPositions = new HashMap<>();
public PartialOrdering(List<T> elements) {
for (int i = 0; i < elements.size(); i++) {
listPositions.put(elements.get(i), i);
}
}
public int compare(T a, T b) {
Integer aPos = listPositions.get(a);
Integer bPos = listPositions.get(b);
if (aPos == null || bPos == null) {
throw new IllegalArgumentException(
"PartialOrdering can only compare elements it's aware of.");
}
return Integer.compare(aPos, bPos);
}
}
You can then simply call Collections.max() to find the largest value in your first list.
This is much more efficient than either of the other answers, which are both O(n^2) and don't handle unknown elements coherently (they assume we have a total ordering).
Even better than implementing your own PartialOrdering, however, is to use Guava's Ordering class, which provides an efficient partial ordering and a number of other useful tools. With Guava all you need to do is:
// Or store the result of Ordering.explicit() if you need to reuse it
Ordering.explicit(listB).max(listA);
I think this might work give it a Try:
function int getHighest(List<String> listA, List<String> listB)
{
int index = 0;
int max = 100;
int tmpMax = 0;
for(String test:lista)
{
for(int i =0;i<listb.size();++i)
{
if(list.get(i).equals(test))
{
tmpMax = index;
}
}
if(tmpMax < max) max = tmpMax;
++index;
}
return max;
}

Comparing int to arraylist of integer

I have an int element and I would like to know if this int is higher than all the integers of an Arraylist ?
Example :
int a ; // Contain an int (i.e 51 or 54 or 989...etc)
ArrayList<Integer> list = new ArrayList<Integer>(); // contain a list of Integers
My purpose is to know if a is higher than any number in the arraylist.
Thanks in advance
Sorting is complete overkill. You just need to compare your value to the highest value in the list. Here's a way to do this with existing library functions:
if (a > Collections.max(list)) {
//a is higher than anything in list
}
Note:
This carries a caveat of always going through the whole list even if the very first element is larger than a. But it's a tradeoff you're usually willing to make because the code reads so nice. If you really want the early exit, you can roll your own approach like in Austin's answer, or in Java 8, it would look something like this:
if ( list.stream().allMatch(element -> a > element) ) {
//...a is higher than anything in list
}
you can just iterate the array to see if any other value is higher..
int a = _whateverInt ; // Contain an int (i.e 51 or 54 or 989...etc)
ArrayList<Integer> list = new ArrayList<Integer>();
boolean isHigher = true;
for(int i = 0; i < list.size() && isHigher; i ++)
{
isHigher = a > list.get(i);
}
Solution 1:
public class Test {
public static void main(String[] args) {
int a = 150;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(50);
arrayList.add(100);
arrayList.add(30);
System.out.println(a > Collections.max(arrayList));
}
}
Solution 2:
public class Test {
public static void main(String[] args) {
int a = 150;
ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(50);
arrayList.add(100);
arrayList.add(30);
Collections.sort(arrayList);
System.out.println(a > arrayList.get(arrayList.size() - 1));
}
}
int a;
ArrayList<Integer> list = new ArrayList<Integer>();
int max = Collections.max(list);
if(a>max)
{
//this is what you want
}
Hope you find this useful...
edit: oops someone already answered the same trick :(
private boolean isLargest(int a, ArrayList<Integer> list)
{
ArrayList<Integer> sortedList = Collections.sort(list);
if(a > sortedList.get(0))
return true;
return false;
}
It is not efficient, but this approach leaves the ordering in the original list in-tact.

reversing an integer listarray using recursion in java

Would appreciate any help with this. Am first year programming student and this is a homework assignment to look at recursion.
1. we had to build an arraylist recursively (done below and working for smallest problem and then higher)
2. test it using a harness (also below)
3. we then have to make a clone copy of the array list (which I think is working) and write a method to recursively reverse the arraylist and include it in the ListMethodRunner test; this is where I am stuck. I have included my code below which is brining up an error on 'list = reverseList(list.remove(0));' in the reverseList Method. Any suggestions where Im going wrong?
//List Methods
import java.util.*;
public class ListMethods
{
//new method that produces an array list of integers (tempList) based on input of int n
public static ArrayList<Integer> makeList(int n)
{
ArrayList<Integer> tempList = null;
if (n <= 0) // The smallest list we can make
{
tempList = new ArrayList<Integer>(); // ceate the list tempList
return tempList; //return blank list for this if statement
}
else // All other size lists are created here
{
tempList = makeList(n-1); //recursively go through each variation of n from top down, when reach 0 will create the list
tempList.add(n); // program will then come back up through the variations adding each value as it goes
}
return tempList; //return the tempList population with all the variations
}
//create a copy of the values in the array list (tlist) and put it in (list)- used in next method
public static ArrayList<Integer> deepClone(ArrayList<Integer> tList)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for (Integer i : tList)
{
list.add(new Integer(i));
}
return list;
}
//method that creates arraylist
public static ArrayList<Integer> reverseList(ArrayList<Integer> tList)
{
ArrayList<Integer> list = ListMethods.deepClone(tList);
if (list.size()<=1) // The list is empty or has one element
{
return list;// Return the list as is – no need to reverse!
}
else
{
list = reverseList(list.remove(0)); //recurse through each smaller list
//removing first value until get to 1 and will create list above
list.add(0);
// Use the solution to a smaller version of the problem
// to solve the general problem
}
return list;
}
}
//List Methods Runner
import java.util.ArrayList;
public class ListMethodsRunner
{
public static void main(String[] args)
{
ArrayList<Integer> tempList = ListMethods.makeList(100);
if (tempList.size() == 0)
{
System.out.println("The list is empty");
}
else
{
for (Integer i : tempList)
{
System.out.println(i);
}
}
}
}
Replace
list = reverseList(list.remove(0))
With
list.remove(0);
list = reverseList(list);
ArrayList::remove(int) returns the element that was removed from the list. (type Integer in this case)
reverseList needs an ArrayList<Integer> as parameter. Ergo the error.
You also have to store the element before inserting it again. Your code should look like this:
Integer num = list.remove(0);
list = reverseList(list);
list.add(num);

Categories