I have a number. 1st I found out the prime factor of this number. Say the number is 12, then prime factor [2,2,3].
Next I have to find out the other factor of this number like 12/2=6 ,[2,6] one factor. Second one is 12/3=4, [3,4] another factor.
2nd example , I considered another number =30. prime factor is[2,3,5]. Other factor is[2,15],[3,10],[5,6].
1 and the number itself is excluded.
Now I take an arraylist which consist of the prime factors of a given number. Then I iterate a loop and divide the number with there prime factor and get another factor.
Say ArrayList abc={2,3,5}
if(abc.size()>=3){
for(int i=0;i<abc.size();i++){
abc1.add(abc.get(i));
abc1.add(number / abc.get(i));
}
}
abc1 is another ArrayList for appending purpose. Now this solution work well when the abc arraylist consist of 3 or more than 3 different numbers like example 30. But it doesn't work well for a repeating numbers like example 12 where is the prime list 2 is a repeated number. I get the output [2,6],[2,6],[3,4].
To find out the repeated number from a list I write down this code block
for(int k=0;k<abc.size();k++){
for(int j=k+1;j<abc.size();j++){
if(abc.get(k).equals(abc.get(j))){
System.out.println(abc.get(j));
}
}
}
But how could I use this with previous code to eliminate one 2.
If you want to avoid duplicates you could use a linkedHashSet (to remove duplicates and maintain order or insertion) and then pass in that as the argument in the constructor of an ArrayList.
Set<Integer> s = new LinkedHashSet<>();
ArrayList<Integer> a = new ArrayList<>(s);
I hope I was able to answer your question, if I did not please let me know.
Related
I have been thinking about this, but i havent been able to come up with a solution.
I have 9 ArrayLists, which can have Integers from 1 to 10.
What i want to do is:
Find 2 Numbers(from 1 to 10), that occur in exactly 2 of these ArrayLists( Must be the same Array. For Example, the number 2 and 3 both appear only in List1 and List)4. Preferably also know in which ArrayLists these numbers occured.
Thanks for any help in advance
One method:
First: Create a Map<Integer, BitSet>. Call it m.
Next: Iterate through the 9 ArrayLists that you have. For each number n that you encounter in array #a:
m.putIfAbsent(n, new BitSet(9)); // Make there the number has a BitSet to start
m.get(n).set(a); // Set the bit indicating number n is in array a
After that, you just need to look for two BitSets in your Map having cardinality() == 2 and are BitSet.equals() equal to each other.
I am trying to have a piece of code in which a random number would be generated and will be saved in a collection so next time when another random number is generated i can check if this new number is already in list or not.
The main point of this method would be generating a number in ranged of 1 to 118, no duplicated number allowed.
Random rand = new Random();
randomNum2 = rand.nextInt(118) + 1;
if (!generated.contains(randomNum2))
{
String strTemp = "whiteElements\\"+String.valueOf(randomNum2)+".JPG";
btnPuzzlePiece2.setIcon(new ImageIcon(strTemp));
generated.add(randomNum2);
btnPuzzlePiece2.repaint();
}
else
setPicForBtnGame1();
BUT the problem is in this piece of code as the program continues generating numbers the possibility to have a correct random number (in range without duplicating) imagine after running the method 110 times... the possibility for the method to generate a valid random number reduces to less than 1%... which leaves the program with the chance of never having the list of numbers from 1-118 and also too much waste of process.
so how can i write this correctly?
p.s i thought of making 118 object and save them in a collection then generate a random object and after remove the object from the list so the next element has no chance of being duplicated.
Help me out please ...
Create a List, and populate it with the elements in your range. Then shuffle() the list, and the order is your random numbers. That is, the 0-th element is your first random number, the 1st element is your second random number, etc.
Wouldn't it be better to just generate something that can never be a duplicate?
A random number with no duplicates is usually known as a UUID.
The easiest way to generate a UUID is to prefix your random number with the current system time in milliseconds.
Of course there's a chance that it could be a duplicate but it's vanishingly small. Of course it might be long, so you'd want to then base64 encode it for example, to reduce it's size.
You can get a more or less guaranteed UUID down to about 8 characters using encoding.
I have a simple code which generates random numbers
SecureRandom random = new SecureRandom();
...
public int getRandomNumber(int maxValue) {
return random.nextInt(maxValue);
}
The method above is called about 10 times (not in a loop). I want to ensure that all the numbers are unique (assuming that maxValue > 1000).
Can I be sure that I will get unique numbers every time I call it? If not, how can I fix it?
EDIT: I may have said it vaguely. I wanted to avoid manual checks if I really got unique numbers so I was wondering if there is a better solution.
There are different ways of achieving this and which is more appropriate will depend on how many numbers you need to pick from how many.
If you are selecting a small number of random numbers from a large range of potential numbers, then you're probably best just storing previously chosen numbers in a set and "manually" checking for duplicates. Most of the time, you won't actually get a duplicate and the test will have practically zero cost in practical terms. It might sound inelegant, but it's not actually as bad as it sounds.
Some underlying random number generation algorithms don't produce duplicates at their "raw" level. So for example, an algorithm called a XORShift generator can effectively produce all of the numbers within a certain range, shuffled without duplicates. So you basically choose a random starting point in the sequence then just generate the next n numbers and you know there won't be duplicates. But you can't arbitrarily choose "max" in this case: it has to be the natural maximum of the generator in question.
If the range of possible numbers is small-ish but the number of numbers you need to pick is within a couple of orders of magnitude of that range, then you could treat this as a random selection problem. For example, to choose 100,000 numbers within the range 10,000,000 without duplicates, I can do this:
Let m be the number of random numbers I've chosen so far
For i = 1 to 10,000,000
Generate a random (floating point) number, r, in the range 0-1
If (r < (100,000-m)/(10,000,000-i)), then add i to the list and increment m
Shuffle the list, then pick numbers sequentially from the list as required
But obviously, there's only much point in choosing the latter option if you need to pick some reasonably large proportion of the overall range of numbers. For choosing 10 numbers in the range 1 to a billion, you would be generating a billion random numbers when by just checking for duplicates as you go, you'd be very unlikely to actually get a duplicate and would only have ended up generating 10 random numbers.
A random sequence does not mean that all values are unique. The sequence 1,1,1,1 is exactly as likely as the sequence 712,4,22,424.
In other words, if you want to be guaranteed a sequence of unique numbers, generate 10 of them at once, check for the uniqueness condition of your choice and store them, then pick a number from that list instead of generating a random number in your 10 places.
Every time you call Random#nextInt(int) you will get
a pseudorandom, uniformly distributed int value between 0 (inclusive)
and the specified value (exclusive).
If you want x unique numbers, keep getting new numbers until you have that many, then select your "random" number from that list. However, since you are filtering the numbers generated, they won't truly be random anymore.
For such a small number of possible values, a trivial implementation would be to put your 1000 integers in a list, and have a loop which, at each iteration, generates a random number between 0 and list.size(), pick the number stored at this index, and remove it from the list.
This is code is very efficient with the CPU at the cost of memory. Each potiental value cost sizeof(int) * maxValue. An unsigned integer will work up to 65535 as a max. long can be used at the cost of a lot of memory 2000 bytes for 1000 values of 16 bit integers.
The whole purpose of the array is to say have you used this value before or not 1 = yes
'anything else = no
'The while loop will keep generating random numbers until a unique value is found.
'after a good random value is found it marks it as used and then returns it.
'Be careful of the scope of variable a as if it goes out of scope your array could erased.
' I have used this in c and it works.
' may take a bit of brushing up to get it working in Java.
unsigned int a(1000);
public int getRandomNumber(int maxValue) {
unsigned int rand;
while(a(rand)==1) {
rand=random.nextInt(maxValue);
if (a(rand)!=1) { a(rand)=1; return rand;}
}
}
I'm looking to find the number of duplicate pairs in a Java ArrayList.
I can work it out on paper but I don't know if there is some form of mathematical formula for working this out easily as I'm trying to avoid nested for loops in my code.
An example using the data set [2,2,3,2,2]:
0:1, 0:3, 0:4, 1:3, 1:4, 3:4. So the answer is six duplicate pairs?
You just need to count how many times each number appears (I would go with a map here) and calculate 2-combinations ( http://en.wikipedia.org/wiki/Combination ) of that count for each number with a count > 1.
So basically you need a method to calculate n!/k!(n-k)! with k being 2 and n being the count.
Taking your example [2,2,3,2,2], the number 2 appears 4 times, so the math would go:
4!/2!(4-2)! = 24/4 = 6 --> 6 pairs
If you don't want to implement the factorial function, you can use the ArithmeticUtils from Apache Commons, they already have the factorial implemented.
If you want to avoid nested loops (at the expense of having 2 loops), you could:
for each number in the list, find how many times each number is repeated (maybe use a Map with key = number, value = times that number occurred in the List)
for each number in the map, calculate the number of possible combinations based on the times that it occurred (0 or 1 times = no duplicate pairs, 2 or more = n!/(2*(n-2)!) = (n*(n-1))/2 duplicate pairs)
sum all the possible combinations
Doing a sort like ElKamina suggests would allow for some optimization on this method.
Sort the numbers first. Later, if there k copies of a given number, there will be k*(k-1)/2 pairs from that number. Now sum it over all the numbers.
Using Guava, if your elements were Strings:
Multiset<String> multiset = HashMultiset.create(list);
int pairs = 0;
for(Multiset.Entry<String> entry : multiset.entrySet()) {
pairs += IntMath.binomial(entry.getCount(), 2);
}
return pairs;
That uses Guava's Multiset and math utilities.
I have two list of numbers, for every member of the second one I must tell if it's obtainable using all the numbers of the first one and placing '+' or '*' and as many '(' ')' I want.
I can't change the order .
List1 can contain a max of 20 elements beetween 1 and 100.
List2 can contain max 5 elements beetween 1 and 20'000.
EX:
List1=[2 4 3 5]
List2=[19 15 24]
19-> 2+(4*3)+5 YES
15 NO
24->2*(4+3+5) YES
With brute force it takes ages to handle inputs with List1 larger than 10.
edit: numbers are always positive.
edit:
I find the max and min numbers that are obtainable from the list and then I discard all the possibilities that have the target outside this range, then I try all the remaining ones.
MAX=n1*n2*n3*....*ni if there are 1 thei r added to their smallest neighbour
MIN=n1+n2+....+ni 1 excluded
Still it's not fast enough when input are big (List1 longer than 10 or numbers in List2 bigger than 10000)
For each sublist of List1, compute the numbers between 1 and 20,000 that can be made with that sublist. The resulting DP bears resemblance to CYK.
I'm being somewhat vague here because this is almost certainly a programming contest problem.
#u mad is correct, but I'll give a little more detail.
Suppose that n = size of list 1. For each 0 <= i < j < n you need to compute all of the distinct values in the range (1..20_000) that can be made from the numbers in the interval [i, j-1]. You can do this with recursion and memoization.
Once you've done this then the problem is easy.
You could try a smart brute force which discards sets of equations by chunks.