Comparing int to arraylist of integer - java

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.

Related

Getting wrong answer while trying to solve Best sum problem using Dynamic programming

Trying to solve the best sum problem but I'm not getting the right answer using DP but if I remove the memoization part of this code then I'm getting the right answer.
I'm attaching the output screenshots:
PS: Please do not judge my code I'm trying to learn DP and I know that this code is not the best.
public class BestSum {
public static void main(String[] args) {
int[] arr = { 2, 3, 4, 5 };
int num = 10;
Map<Integer, List<Integer>> map = new HashMap<>();
List<Integer> list = rec(arr, num, map);
System.out.println(list);
}
static List<Integer> rec(int[] arr, int n, Map<Integer, List<Integer>> map) {
if (n == 0) {
return new ArrayList<>();
}
if (n < 0) {
return null;
}
if (map.containsKey(n)) {
return map.get(n);
}
List<Integer> sCombo = null;
for (int i : arr) {
int rem = n - i;
List<Integer> t = rec(arr, rem, map);
if (t != null) {
List<Integer> list = new ArrayList<>();
t.add(i);
list.addAll(t);
if (sCombo == null || list.size() < sCombo.size()) {
sCombo = list;
}
}
}
map.put(n, sCombo);
return map.get(n);
}
}
list.add(i); // write this instead of t.add(i).
a little mistake in the code nothing else.
just small mistake i.e....
you directly inserting sCombo into the Map. the values in sCombo array was changing while recursion every time at the same time the same sCombo array values in the map also changing because there have only one block of memory for each sCombo array that means when ever we edit that sCombo array it will effects the previous result....
example:- you assigned the list to sCombo
sCombo=list;
when ever the list gets changes then the sCombo also changed
just clone() the object you get correct result like this......

random elements from a list DURING the addition

There are 20 names in my code.
my function has 2 options to add elements to a list I've:
1.
Inserting all the 20 names to the list:
public void addNames() {
list.add("name1");
list.add("name2");
...
list.add("name20");
}
2.
Adding only 5 random names(from the 20 names) to the list. For doing it, I thought about 2 ways. What's the best way to random 5 names from the 20? maybe you have a better way.
A.
Using a random set of indices (each value will be between 0 to 19 because there are 20 names) and before the 'add' I'll check if adding them or not by some counter:
public void addNames() {
// adding 5 random indices between 0 to 19 to the set
Set<Integer> set = new HashSet<Integer>();
Random r = new Random();
Set<Integer> indices = new HashSet<>(numRandomNames); //==5
for (int i = 0; i < numRandomNames; ++i) {
int index = r.nextInt(numNames - 0); //==19
indices.add(index);
}
int counter = 0;
if (indices.contains(counter)) {
list.add("name1");
}
counter++;
if (indices.contains(counter)) {
list.add("name2");
}
counter++;
if (indices.contains(counter)) {
list.add("name3");
}
...
}
B.
RandomList that extends List and overrides the 'add' function to do the same as 'A.' does BUT the override 'add' will decide whether adding the value inside the function so my function will look the same as 1. with the override 'add' function
Do you think about a better solution? if not, then which one is better? (A or B?). I just saw that people recommends not to extend the java collection but I think it's the best solution from these 2 solutions.
NOTE
====
my code can have 10000 names or more even so I don't want to add all the 10,000 names to this\other list and then random 5 of them to other list. I prefer to do it DURING the addition in order to avoid many places of the list while I don't really need them.
EDIT
an answer to ProgrammerTrond:
I'm not sure I'll do it but what I asked me to show is my suggestion of 2.B:
public class RandomList<Integer> implements List<Integer> {
private int addCallsCounter;
private Set<Integer> setIndices = null;
public RandomList(final int numElements, final int maxVal, final int minVal) {
addCallsCounter = 0;
setIndices = new HashSet<Integer>(numElements);
Random r = new Random();
while (setIndices.size() < numElements) {
int index = r.nextInt(maxVal - minVal + 1) + minVal;
if (setIndices.contains(index) == false) {
setIndices.add(index);
}
}
}
#Override
public boolean add(Integer object) {
if (setIndices.contains(addCallsCounter++)) {
this.add(object);
return true;
}
return false;
}
}
and from my code I'll do so:
RandomList randList = new RandomList(5);
randList.add("name1");
randList.add("name2");
randList.add("name3");
...
randList.add("name19");
randList.add("name20");
but my problem is that I need to implement MANY abstract methods of List pfff. RandomList cann't be abstract too because then it won't be able to be instantiated.
try this:
List<Integer> index = new ArrayList<>();
List<String> five_names = new ArrsyList<>();
List<String> allnames = new ArrayList<>();
store five random values
for(int i = 0;i < 5;i++){
int index_no = getrandomNumber();
index.add(index_no);
five_names.add(allnames.get(index_no));
}
getRandomNumber method:
public int getRandomNumber(){
Random rnd = new Random();
int x = rnd.nextInt(20);
if(index.contains(x)){
return getRandomNumber();
}else{
return x
}
}
Why not like this? You don't need the random index list in your list implementation. Didn't you just want a method that would add to a list 5 random names drawn from a set of available names?
import java.util.*;
public class ListAdding {
private static List<String> allNames = Arrays.asList("name1", "name2", "name3", "name4", "name5", "name6", "name7");
public static void main(String[] args) {
new Temp().test();
}
void test() {
List<String> list = new ArrayList<>();
list.add("Bernie");
addFiveRandom(list);
for (int i = 0; i < list.size(); i++) {
System.out.println(i + ": " + list.get(i));
}
// Example: 0: Bernie
// 1: name2
// 2: name3
// 3: name6
// and so on
}
void addFiveRandom(List<String> toBeAddedTo) {
List<Integer> indices = new ArrayList<>();
while (indices.size() < 5) {
int newIndex = new Random().nextInt(5);
if (!indices.contains(newIndex))
indices.add(newIndex);
}
for (Integer index : indices) {
toBeAddedTo.add(allNames.get(index));
}
}
}

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

Finding duplicate random numbers in an ArrayList

public class LotteryNumbers {
private ArrayList <Integer> numbers;
public LotteryNumbers() {
this.numbers = new ArrayList <Integer> ();
this.drawNumbers();
}
public ArrayList <Integer> numbers() {
return this.numbers;
}
public void drawNumbers() {
Random random = new Random ();
int counter = 0;
while (counter < 7) {
this.numbers.add(random.nextInt(39) + 1);
counter++;
}
}
This is a class used for printing 7 numbers from 1..39.
It does that job but the problem is I want the 7 random numbers to be different.
How do I check if an arrayList contains the same number since it is random?
Thanks for reading.
You could try using the contains() method from the ArrayList numbers:
public void drawNumbers()
{
Random random = new Random();
int counter = 0;
int choice;
while (counter < 7) {
choice = random.nextInt(39) + 1;
if (numbers.contains(choice)) {
continue;
}
numbers.add(choice);
counter++;
}
}
From Java Docs:
public boolean contains(Object o): Returns true if this list contains
the specified element.
So, if the ArrayList already contains the choice (randomly generated), it will continue to the next iteration (counter won't be increased) and choose another random number. If it doesn't contains the choice, it will add it to the array and increase counter.
This can also be done by this way (without using continue)
if (!numbers.contains(choice)) {
numbers.add(choice);
counter++;
}
How do I check if an ArrayList contains the same number since it is random?
Like this (example):
public void drawNumbers() {
Random random = new Random ();
int counter = 0;
while (counter < 7) {
int newNumber = random.nextInt(39) + 1;
if (! numbers.contains(newNumber)) {
this.numbers.add(newNumber);
counter++;
}
}
}
You could use contains as as the earlier responses suggest, however contains on an array list in inefficient with O(n) complexity. One of the comments by #TheLostMind suggest using a Set, the best Set implementation to use in this instance is BitSet, note it does not confirm to the java.util.Set interface specification.
public class LotteryNumbers {
private final int[] numbers = new int[7]
public LotteryNumbers() {
this.drawNumbers();
}
public int[] numbers() {
return this.numbers;
}
public void drawNumbers() {
BitSet selected = new BitSet(40);
Random random = new Random ();
int counter = 0;
while (counter < 7) {
int num = random.nextInt(39) + 1;
if(!selected.get(num)) {
selected.flip(num);
numbers[counter++] = num;
}
}
}
This implementation, tho unlikely, does not guarantee that you will always get a result.
You could also put your numbers in a list and use COllections.shuffle and get the first 7 occurences.
You do not need to check if duplicate...
ArrayList list = new ArrayList();
list.add(1);
list.add(2);
....
Collections.shuffle(list);
loop and get your numbers...
int num = Integer.intValue(list.get(i));

Comparing one arraylist to another and deleting extra items 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))

Categories