I have created the following method so as to create unique random numbers . (This unique values belong to the nodes of a tree):
static Random rand = new Random();
public static ArrayList<Node> go(int n) {
ArrayList<Node> list = new ArrayList<Node>();
ArrayList<Integer> numList = new ArrayList<Integer>();
// TODO Auto-generated method stub
for(int i = 1; i<=5; i++)
{
int number = rand.nextInt(10)+1;
if(list.size()>0 && !check(list,number))
{
i--;
continue;
}
numList.add(number);
Node node = new Node();
node.data = number;
list.add(node);
}
int w = 0;
for (Node d : list) {
System.out.println(w+": "+d.data);
w++;
}
return list;
}
private static boolean check(ArrayList<Node> list, int num) {
// TODO Auto-generated method stub
boolean b = false;
/*if(list.size()==0)
return true;
*/
for (Node node : list) {
if(node.data == num)
b = false;
else
b = true;
}
return b;
}
But it doesn’t create unique numbers and there are still duplicates in my list. Like :
0: 10
1: 1
2: 10
3: 5
4: 6
The problem is that you don't stop the for loop inside the check function if it finds a duplicated number. The loop continues and b can change back to true.
What you should do is for example:
private static boolean check(ArrayList<Node> list, int num) {
for (Node node : list) {
if(node.data == num)
return false;
}
return true;
}
Jón Trausti Arason has your answer, but...
Since you have a finite number of allowed values (integers), and since you don't want the same one picked more than once, perhaps it would be easier to just shuffle an array of the allowed values. Then you could just pick off the next value from the array and not worry about checking every time whether it's a repeat.
In your example selecting five values between one and ten, you could start with an array {1,2,3,4,5,6,7,8,9,10} and run it through a shuffle to rearrange it to something else like {3,4,7,1,10,9,5,8,2,6}. Take the first five values out of that resulting array with no worries about repeats.
In your check method, this looks a bit dodgy:
if (node.data == num)
b = false;
else
b = true
Surely once you've found a match (e.g. b = false) you want to return? Otherwise the next time around the loop b might be set to true. To simplify a bit, if you want to check whether an item is in a collection you can do list.contains(element)
You "forget" to use the numList that you've prepared.
This code should work fine:
static Random rand = new Random();
public static ArrayList<Node> go(int n) {
ArrayList<Node> list = new ArrayList<Node>();
ArrayList<Integer> numList = new ArrayList<Integer>();
for (int i = 1; i <= 5; i++) {
int number = rand.nextInt(10) + 1;
if (numList.contains(number)) {
i--;
continue;
}
numList.add(number);
Node node = new Node();
node.data = number;
list.add(node);
}
int w = 0;
for (Node d : list) {
System.out.println(w + ": " + d.data);
w++;
}
return list;
}
To illustrate on #eaj's point.
public static List<Node> go(int n) {
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 1; i <= 10; i++) numbers.add(i);
Collections.shuffle(numbers);
List<Node> nodes = new ArrayList<Node>();
for (Integer data : numbers.subList(0, 5))
nodes.add(new Node(data)); // use a constructor for Node.
for (int w = 0; w < nodes.size(); w++)
System.out.println(w + ": " + nodes.get(w).data);
return nodes;
}
Your check function is wrong. Currently, it simply returns whether the last element matches num. You want to declare true (e.g. with return true;) once you find a match.
In fact, you can do everything without b. And I'm sure you can use list's contain method instead.
You should change your check method to something like:
private static boolean check(ArrayList<Node> list, int num)
{
for (Node node : list)
if (node.data == num)
return false;
return true;
}
In this way you go over the list and return false as soon as you find an equal element. If you are able to finish the loop without returning then no duplicates are found and you can return true.
This is my solution:
import java.util.ArrayList;
import java.util.Collections;
public class comboGenerator {
public static void main(String[] args) {
ArrayList<Integer> $combo = new ArrayList<Integer>(); // init. array list combo for randomization
while ($combo.size() < 6) {
int rand = (int) (Math.random()*49+1); // make new random number 1-49
if (!$combo.contains(rand)){ // check if we have that number in array list,{
$combo.add(rand); // if there is no such number then add it to array list
Collections.sort($combo); // sort the array list small >> large
}
}
System.out.println("Random combination " + $combo);
}
}
And you CAN'T get same numbers!
Related
So I am trying to create a more time efficient stack implementation in java but I don't know how to make it work faster. Here is my code:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
int[] n = new int[0];
Scanner scan = new Scanner(System.in);
loop: while(true){
String stringy = scan.next();
switch(stringy){
case "push":
int x = scan.nextInt();
n = push(x, n);
System.out.println("ok");
break;
case "pop":
n = pop(n);
break;
case "exit":
System.out.println("bye");
break loop;
case "size":
System.out.println(n.length);
break;
case "back":
back(n);
break;
case "clear":
n = clear();
System.out.println("ok");
break;
}
}
}
static int[] push(int n, int[] x) {
int[] z = new int[x.length + 1];
for (int i = 0; i < x.length; i++){
z[i] = x[i];
}
z[x.length] = n;
return z;
}
static int[] pop(int[] x){
int z[] = new int[x.length-1];
for(int i = 0; i < z.length; i++){
z[i] = x[i];
}
System.out.println(x[x.length-1]);
return z;
}
static void back(int[] x){
System.out.println(x[x.length-1]);
}
static int[] clear(){
int x[] = new int[0];
return x;
}
}
Brief explanation:
Program takes values from scanner. And depending on a word that was entered, program proceeds with the corresponding instructions like push, pop, back... And it prints out the expected values to console with ok. Everything so far works properly as expected except the performance.
As you can see, in methods push and pop, my program creates new arrays and copies the values of the taken array which is x and adds 1 index with a pushed value or removes the popped value. This approach seems rather slow and inefficient. I couldn't find a more efficient way of doing that without picking arraylist or other classes from java library. But I have to use default integer arrays. And are there any other issues worsening the perfomance of the program?
How can I make my program work faster?
You can create member variables outside your method to keep track of the array and what is the size of it (similar to how array lists are implemented), no need to recopy the whole array everytime you need to pop/push.
You will need 2 variables, the array itself and the size (which will expand/shrink based on what you do)
You're better off creating a new class, I am gonna name it CustomStack
public class CustomStack
{
private int[] elements = new int[10]; // instantiated with a size of 10
private int size; // To track how many ints we currently have
....
}
You can now access the array and the size within the methods.
So first you need the push method, but wait there is a trick here, what if I already reached the max size of the array? (i.e: 10 numbers are already inside the array), well you need to cater for this, a known way to tackle this is create a new array with double the size of the current array and then copy all the values to the new array.
private void validateArraySize()
{
if (size == elements.length)
{
int[] temp = new int[elements.length * 2]; //double the size
System.arraycopy(elements, 0, temp, 0, elements.length); // copy the array
elements = temp; //set our member variable array to the new array
}
}
And the push method:
public void push(int n)
{
validateArraySize(); // The previos method to check if we can safely insert the value
elements[size] = n;
size++;
}
Regarding the pop method, it is very straight forward, you just need to check if there are any integers inside the array:
public int pop()
{
int valueRemoved = 0;
if (size == 0)
System.out.println("No elements found to pop");
else
{
valueRemoved = elements[size - 1]; //Get the last value
elements[size - 1] = 0; // remove the last value
size--;
}
return valueRemoved; // return removed value
}
The whole class will look like this:
public class CustomStack
{
private int[] elements = new int[10];
private int size;
public void push(int n)
{
validateArraySize();
elements[size] = n;
size++;
}
private void validateArraySize()
{
if (size == elements.length)
{
int[] temp = new int[elements.length * 2];
System.arraycopy(elements, 0, temp, 0, elements.length);
elements = temp;
}
}
public int pop()
{
int valueRemoved = 0;
if (size == 0)
System.out.println("No elements found to pop");
else
{
valueRemoved = elements[size - 1];
elements[size - 1] = 0;
size--;
}
return valueRemoved;
}
public int getSize()
{
return size;
}
public void back()
{
if (size == 0)
System.out.println("No elements found");
else
System.out.println(elements[size - 1]);
}
public void clear()
{
elements = new int[10];
}
}
Your main method will become:
public static void main(String[] args) {
CustomStack customStack = new CustomStack();
Scanner scan = new Scanner(System.in);
loop: while(true){
String stringy = scan.next();
switch(stringy){
case "push":
int x = scan.nextInt();
customStack.push(x);
System.out.println("ok");
break;
case "pop":
int val = customStack.pop();
System.out.println(val + " is popped");
break;
case "exit":
System.out.println("bye");
break loop;
case "size":
System.out.println(customStack.getSize());
break;
case "back":
customStack.back();
break;
case "clear":
customStack.clear();
System.out.println("ok");
break;
}
}
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));
}
}
}
im trying to create a B+ tree from a previous B tree implementation I create, but Im really lost here... the only difference from B to B+ im trying to implement, is storing the keys on the leaves instead of removing them.
Example:
Final B Tree
3 6 false
1 2 true
4 5 true
7 8 9 10 true
Final B+ Tree
3 6 false
1 2 true
3 4 5 true
6 7 8 9 10 true
This is what I have for a B Tree (I really didnt want to post the whole code, but explaining all of it will be harder and confusing). I would appreciate at least some ideas...
MAIN
public class BTreeTest{
public static void main(String[] args) {
Random generator = new Random();
BTree T = new BTree(3);
final int INSERTS = 50; // how many elements are inserted
final int VALUE_LIMIT = 1000; // generated integers up to VALUE_LIMIT
int[] values = new int[INSERTS]; // array can be used to print insert order
// or to test other methods
for (int i=0;i<INSERTS;i++){
int val = generator.nextInt(VALUE_LIMIT);
values[i] = val;
T.insert(val);
}
T.printNodes();
}}
B tree NODE
public class BTreeNode{
public int[] key;
public BTreeNode[] c;
boolean isLeaf;
public int n;
private int T; //Each node has at least T-1 and at most 2T-1 keys
public BTreeNode(int t){
T = t;
isLeaf = true;
key = new int[2*T-1];
c = new BTreeNode[2*T];
n=0;
}
public boolean isFull(){
return n==(2*T-1);
}
public void insert(int newKey){
// Insert new key to current node
// We make sure that the current node is not full by checking and
// splitting if necessary before descending to node
//System.out.println("inserting " + newKey); // Debugging code
int i=n-1;
if (isLeaf){
while ((i>=0)&& (newKey<key[i])) {
key[i+1] = key[i];
i--;
}
n++;
key[i+1]=newKey;
}
else{
while ((i>=0)&& (newKey<key[i])) {
i--;
}
int insertChild = i+1; // Subtree where new key must be inserted
if (c[insertChild].isFull()){
// The root of the subtree where new key will be inserted has to be split
// We promote the mediand of that root to the current node and
// update keys and references accordingly
//System.out.println("This is the full node we're going to break ");
// Debugging code
//c[insertChild].printNodes();
//System.out.println("going to promote " + c[insertChild].key[T-1]);
n++;
c[n]=c[n-1];
for(int j = n-1;j>insertChild;j--){
c[j] =c[j-1];
key[j] = key[j-1];
}
key[insertChild]= c[insertChild].key[T-1];
c[insertChild].n = T-1;
BTreeNode newNode = new BTreeNode(T);
for(int k=0;k<T-1;k++){
newNode.c[k] = c[insertChild].c[k+T];
newNode.key[k] = c[insertChild].key[k+T];
}
newNode.c[T-1] = c[insertChild].c[2*T-1];
newNode.n=T-1;
newNode.isLeaf = c[insertChild].isLeaf;
c[insertChild+1]=newNode;
//System.out.println("This is the left side ");
//c[insertChild].printNodes();
//System.out.println("This is the right side ");
//c[insertChild+1].printNodes();
//c[insertChild+1].printNodes();
if (newKey <key[insertChild]){
c[insertChild].insert(newKey); }
else{
c[insertChild+1].insert(newKey); }
}
else
c[insertChild].insert(newKey);
}
}
public void print(){
//Prints all keys in the tree in ascending order
if (isLeaf){
for(int i =0; i<n;i++)
System.out.print(key[i]+" ");
System.out.println();
}
else{
for(int i =0; i<n;i++){
c[i].print();
System.out.print(key[i]+" ");
}
c[n].print();
}
}
public void printNodes(){
//Prints all keys in the tree, node by node, using preorder
//It also prints the indicator of whether a node is a leaf
//Used mostly for debugging purposes
printNode();
if (!isLeaf){
for(int i =0; i<=n;i++){
c[i].printNodes();
}
}
}
public void printNode(){
//Prints all keys in node
for(int i =0; i<n;i++)
System.out.print(key[i]+" ");
System.out.println(isLeaf);
}
}
B Tree
public class BTree{
private BTreeNode root;
private int T; //2T is the maximum number of childen a node can have
private int height;
public BTree(int t){
root = new BTreeNode(t);
T = t;
height = 0;
}
public void printHeight(){
System.out.println("Tree height is "+height);
}
public void insert(int newKey){
if (root.isFull()){//Split root;
split();
height++;
}
root.insert(newKey);
}
public void print(){
// Wrapper for node print method
root.print();
}
public void printNodes(){
// Wrapper for node print method
root.printNodes();
}
public void split(){
// Splits the root into three nodes.
// The median element becomes the only element in the root
// The left subtree contains the elements that are less than the median
// The right subtree contains the elements that are larger than the median
// The height of the tree is increased by one
//System.out.println("Before splitting root");
//root.printNodes(); // Code used for debugging
BTreeNode leftChild = new BTreeNode(T);
BTreeNode rightChild = new BTreeNode(T);
leftChild.isLeaf = root.isLeaf;
rightChild.isLeaf = root.isLeaf;
leftChild.n = T-1;
rightChild.n = T-1;
int median = T-1;
for (int i = 0;i<T-1;i++){
leftChild.c[i] = root.c[i];
leftChild.key[i] = root.key[i];
}
leftChild.c[median]= root.c[median];
for (int i = median+1;i<root.n;i++){
rightChild.c[i-median-1] = root.c[i];
rightChild.key[i-median-1] = root.key[i];
}
rightChild.c[median]=root.c[root.n];
root.key[0]=root.key[median];
root.n = 1;
root.c[0]=leftChild;
root.c[1]=rightChild;
root.isLeaf = false;
//System.out.println("After splitting root");
//root.printNodes();
}}
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));
I have an integer arraylist..
ArrayList <Integer> portList = new ArrayList();
I need to check if a specific integer has already been entered twice. Is this possible in Java?
You could use something like this to see how many times a specific value is there:
System.out.println(Collections.frequency(portList, 1));
// There can be whatever Integer, and I use 1, so you can understand
And to check if a specific value is there more than once you could use something like this:
if ( (Collections.frequency(portList, x)) > 1 ){
System.out.println(x + " is in portList more than once ");
}
My solution
public static boolean moreThanOnce(ArrayList<Integer> list, int searched)
{
int numCount = 0;
for (int thisNum : list) {
if (thisNum == searched)
numCount++;
}
return numCount > 1;
}
If you are looking to do this in one method, then no. However, you could do it in two steps if you need to simply find out if it exists at least more than once in the List. You could do
int first = list.indexOf(object)
int second = list.lastIndexOf(object)
// Don't forget to also check to see if either are -1, the value does not exist at all.
if (first == second) {
// No Duplicates of object appear in the list
} else {
// Duplicate exists
}
This will tell you if you have at least two same values in your ArrayList:
int first = portList.indexOf(someIntValue);
int last = portList.lastIndexOf(someIntValue);
if (first != -1 && first != last) {
// someIntValue exists more than once in the list (not sure how many times though)
}
If you really want to know how many duplicates of a given value you have, you need to iterate through the entire array. Something like this:
/**
* Will return a list of all indexes where the given value
* exists in the given array. The list will be empty if the
* given value does not exist at all.
*
* #param List<E> list
* #param E value
* #return List<Integer> a list of indexes in the list
*/
public <E> List<Integer> collectFrequency(List<E> list, E value) {
ArrayList<Integer> freqIndex = new ArrayList<Integer>();
E item;
for (int i=0, len=list.size(); i<len; i++) {
item = list.get(i);
if ((item == value) || (null != item && item.equals(value))) {
freqIndex.add(i);
}
}
return freqIndex;
}
if (!collectFrequency(portList, someIntValue).size() > 1) {
// Duplicate value
}
Or using the already availble method:
if (Collections.frequency(portList, someIntValue) > 1) {
// Duplicate value
}
Set portSet = new HashSet<Integer>();
portSet.addAll(portList);
boolean listContainsDuplicates = portSet.size() != portList.size();
I used the following solution to find out whether an ArrayList contains a number more than once. This solution comes very close to the one listed by user3690146, but it does not use a helper variable at all. After running it, you get "The number is listed more than once" as a return message.
public class Application {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(4);
list.add(8);
list.add(1);
list.add(8);
int number = 8;
if (NumberMoreThenOnceInArray(list, number)) {
System.out.println("The number is listed more than once");
} else {
System.out.println("The number is not listed more than once");
}
}
public static boolean NumberMoreThenOnceInArray(ArrayList<Integer> list, int whichNumber) {
int numberCounter = 0;
for (int number : list) {
if (number == whichNumber) {
numberCounter++;
}
}
if (numberCounter > 1) {
return true;
}
return false;
}
}
Here is my solution (in Kotlin):
// getItemsMoreThan(list, 2) -> [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3}
// getItemsMoreThan(list, 1)-> [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3, 2.05=2}
fun getItemsMoreThan(list: List<Any>, moreThan: Int): Map<Any, Int> {
val mapNumbersByElement: Map<Any, Int> = getHowOftenItemsInList(list)
val findItem = mapNumbersByElement.filter { it.value > moreThan }
return findItem
}
// Return(map) how often an items is list.
// E.g.: [16.44, 200.00, 200.00, 33.33, 200.00, 0.00] -> {16.44=1, 200.00=3, 33.33=1, 0.00=1}
fun getHowOftenItemsInList(list: List<Any>): Map<Any, Int> {
val mapNumbersByItem = list.groupingBy { it }.eachCount()
return mapNumbersByItem
}
By looking at the question, we need to find out whether a value exists twice in an ArrayList. So I believe that we can reduce the overhead of "going through the entire list just to check whether the value only exists twice" by doing the simple check below.
public boolean moreThanOneMatch(int number, ArrayList<Integer> list) {
int count = 0;
for (int num : list) {
if (num == number) {
count ++ ;
if (count == 2) {
return true;
}
}
}
return false;
}