creating set from input - java

I want to create a set of elements from the given input.
(i.e. i/p : 5 5 4 4 4 3 3 3 3 2 2 2 1 1 1 ,then o/p : 5 4 3 2 1)
I have a logic: create an array and store the elements in it.successively read elements and write a loop which will assign boolean false if two elements (the current chosen element and an element from the array whose index is less than that of the current element) are not the same. After the loop has executed for an element , all the boolean values stored are passed through bitwise OR operation and if the overall value is false , then the current element is pushed to an array that stores the set and the next element is the given sequence is chosen and same operation is performed.
I haven't yet written the code for this. So, is this algo. right? Also, do you know a better algo. to find a set?
Thanks.

You never need to use arrays for this sort of thing. Learn about Lists and Sets and use those instead.
Set<Integer> set = new LinkedHashSet<Integer>(Arrays.asList(5, 5, 4, 4, 3, 2, 4, 3, 1));
System.out.println(set); // prints [5, 4, 3, 2, 1]

Related

how to return the sum as an array of the numbers that have the most appearances

You are giving an array representing a list of non-negative integers.
Write a function findMostAppearances() to return the sum as an array of the numbers that have the most appearances.
constraints:
a: 0 <= list.length =< 100
b: 2 <= list[i] <= 100
This is one my interview question and till this day I still don't know what the question want.
What does it mean when it say return the sum as an array of the numbers that have the most appearances
What does the a. and b. have to do with that? can anyone tell me?
First I answer your second question.
a. means that input array contains less then 100 elements.
b. means that vakue of element is between 2 and 100
whole task is to find most common element of array and if multiply its value by number of appearances.
For example if you have [1, 1, 2, 3, 3, 3, 3] as input, most common element is 3 it appears 4 times in input array while 1 appears twice and 2 only once. So result be 3 * 4.

Find the level of array elements in BST

We have a given array and we want to print each node's level in the BST.
For example if the given array is: {15, 6, 2, 10, 9, 7, 13}
then the answer is:
1 2 3 3 4 5 4
(it means that the level of node that stores 15 is 1 and ...)
I have some algorithms in my mind but I don't know how to implement them in code.
These are the steps that you should follow :
Create a binary search tree from the elements given in the array.
Write a function findLevel( Node root, int value) to find the level of any value passed to this function.
Iterate the array and pass each array element as an argument to findLevel( Node root, int value) and print the values returned from the function.

How to determine if 3 out of 5 numbers match in java?

I have 5 numbers randomly generated by "dice" which are all 10, 2, 3, 4, 5, or 6. Is there a way I could determine whenever 3 of the 5 generated numbers are all the same(a roll of 4, 4, 4, 5, 2 or a roll of 10, 3, 5, 3, 3 for example)?
I could use a series of nested if statements but is there a simpler way that I'm missing?
This is a simple algorithm question, and you should understand how to write such an algorithm as well as how it will behave in different situations.
Don't use nested if statements. That will be hard to maintain, especially if the code has to change. Try to create generalized algorithms.
I don't know the requirements of your answer completely, so I'll answer it in two ways.
If ordering does not matter:
Create a dictionary of integer to integer. (Java calls this a Map. You can use HashMap in your case.) The key will be the value from the dice (10, 2, 3, 4, 5, or 6 in your case), and the value will be the number of times that number has appeared. Then you can just look at each key in the dictionary and see if its value hits your threshold.
Alternatively, you can store all the results in an array, and just loop over the elements in the array and count.
If ordering does matter (e.g., you have to get 3 2's in a row):
You'll have to keep an array of the dice roll results, and then you can check after each dice roll if the previous 2 values were the same. Or, you can wait until you have all the rolls and then just check one by one to see if you get 3 in a row.
I haven't put any code down because I don't think that's as instructive. If you need more guidance let me know.
Sort the array. Then look for 3 numbers in a row with the same value.
Sure, I'll do your homework for you.
boolean hasTriplets = false;
Arrays.sort(nums); //Your array of random ints
for(int x=1; x<nums.length-1; x++)
if(nums[x-1] == nums[x] && nums[x] == numx[x+1])
{
hasTriplets = true;
break;
}
This should do:
if (Stream.of(4, 4, 4, 5, 2)
.collect(Collectors.groupingBy(Function.identity()))
.values().stream().mapToInt(List::size)
.filter(value -> value == 3)
.count() > 0) {
System.out.println("found exactly 3 occurrences of one number");
}
Assuming the 10 in the question should have been a 1, it would seem you're rolling five 6-sided dice, and want to find three-of-a-kind for a Yahtzee (or Yatzy) game.
If that is the case, you'll want other combinations detected too, so it would be best to collect count of each value, i.e. how many 1's, 2's, ..., and 6's, then find the highest count (and second highest).
See my answer here for longer description of how to do that for Yahtzee/Yatzy game.
If all you're interested in is three-of-a-kind, and it's ok to sort the values, as other have suggested, you can optimize the search a bit.
Once you sort the list, three-of-a-kind will be one of these combinations:
3 3 3 4 5
2 3 3 3 4
1 2 3 3 3
As you can see, the middle number is always part of the sequence, so you'll start with that. For the first combination, if the first value is equal to the third value, you don't have to test the second value, since it must be the same (sorted, remember). Same for the last combination.
So you code can be:
int[] dice = { 4, 4, 4, 5, 2 };
Arrays.sort(dice);
int candidate = dice[2];
if (dice[0] == candidate || dice[4] == candidate
|| (dice[1] == candidate && dice[3] == candidate)) {
System.out.println("Found three-of-a-kind for " + candidate);
}

Merge sort Recursion Error

Mergesort(a,p,r){
if(p<r){
int q=[p+r]/2;
Mergesort(a,p,q);
Mergesort(a,q+1,r);
Merge(a,p,q,r);
It's from the book Introduction to ALgorithms:Cormen
in this i can't understand the recursive call of the merge sort algorithm
2 4 1 6 8 5 3 7
2 4 1 6
2 4
2
in the first recursive call i got upto three then where does the control goes from here i m struck at 2 will it call the next function mergesort(a,q+1,r) and merge(a,p,q,r) ?
Suppose your array is a = { 2, 4, 6, 1, 8, 5, 3, 7 }. I swapped two elements of the array proposed by you. Now, what follows is exactly what your program does, call after call.
At the first call p=0, q=7: your while array is the input.
At the second call p=0, q=3, at the third p=0, q=1.
At the fourth call p=0, q=0: the input is the subarray { 2 }. This array has just one element, thus is sorted: the line if(p<r) makes sure the fourth call ends here and control returns to the third call.
The third call has the input { 2, 4 }. We have just ended the line Mergesort(a,p,q);, thus we know the first half of the input is sorted. The fifth call (line Mergesort(a,q+1,r);) will now sort the second half.
At the fifth call p=1, q=1. The input is once again an array of length 1, thus sorted by default. Control returns to the third call.
The third call is now evaluating the line Merge(a,p,q,r);. The first half is sorted, the second half is sorted: Merge(a,p,q,r); takes those two halves and shifts the element making sure the whole subarray from index p to index r is sorted. The third call ends.
The second call had { 2, 4, 6, 1 } has input. The first half is sorted, now remains the second half: after that call the input become { 2, 4, 1, 6 }. After Merge is called the input become { 1, 2, 4, 6 } and the second call ends, returning control to the first call.
The first call now needs to sort the second half of its input, that incidentally is the whole array. That is done as before.

generate random order but with constraint in java

When I put a integer list, how can I generate another random order but with constraint?
For example, I put integer 1, 2, 3, 4 into the collection and when I try to print result like be "1 2 3 4","1 2 4 3","1 3 2 4" ,"2 1 3 4",or "2 1 4 3"(1 must before 3, 2 must before 4)
thanks in advance
One thing you can consider is swapping elements at random. You could pick a random position in your collection, then swap the element in that position with the next element. This way, you can prevent swapping 1 with 3, or 2 with 4. You can do this repetitively, until the numbers are properly scrambled:
[1, 2, 3, 4] random number is 0, swap with element at position 1.
[2, 1, 3, 4] random number is 1, swap with element at position 2.
elements are 1 and 3, so don't swap.
[2, 1, 3, 4] random number is 2, swap with element at position 3.
[2, 1, 4, 3] etc.
If you'd like to generalize the constraint, you can simply change the condition. Instead of refusing to swap when the elements are either 1 and 3, or 2 and 4 (as in the example above), you could make sure the two elements at the positions to be swapped are not within 2 of each other, so something like if(b==a+2)continue;:
elements are 5 and 7, so don't swap.
if(7==5+2)continue; // ie don't swap.
What you've defined here is known as a partial order. You wish to generate a random permutation which still satisfies the partial order, i.e. a random linear extension.
Luckily, the Java API specifies Collections.shuffle, which implements the Fisher-Yates algorithm to generate a random permutation.
Unfortunately, the standard Java technique via Collections.sort is a comparison sort, and thus focused on total orders -- unlike the partial order we want. In fact, the Java API lacks a sorting algorithm we could use here.
One approach covered in "Generating Linear Extensions of Posets by Transpositions" involves that of swapping adjacent elements in the set in a fashion similar to Hassan's solution. This appears to be a functioning way for the localized problem at hand.
If you use it as a string then you could use this answer's algorithm to swap all the numbers
When you enter all the numbers then just concatenate them together. There is no need to treat them as numbers or strings. All you want to do is reorder them.
When you get the result you could then check to see if your constraints match and then print out another list. Something like this perhaps
private boolean isConstraintSatisfied(String wholeString, String firstNum, String secondNum){
return wholeString.indexOf(firstNum) <= wholeString.indexOf(secondNum);
}
Not the most elegant solution but I think it would work. For small input sets it shouldnt be too inefficient.

Categories

Resources