this one might sound trivial question but I am not able to arrive at a proper solution. Request for help.
Problem : In my code, I get 2 events (one after the other) in a sequence. The sequence could be "event A" first then "event B" or vice versa. If my event sequence is AB then I need to take some action and similarly if my sequence is BA, then I need to take another action.
However, I am finding it tough to determine the sequence and set a boolean value.
One solution I have thought of is to use stack. Both these events will be pushed to stack. I will check if my stack size is 2, then I will pop the last value and see which event it is. If it is A, then i will add logic for BA and if it is B, then I will add logic for AB. Once it is done I will clear my stack.
Is there a simpler way to do it? Please advice
If it is Synchronous and you only can have these to possibilities, you only need one boolean (hasOtherArrived) to do it:
When Event arrives, check if hasOtherArrived is true: if it is execute needed code (depending on which event arrived) and set hasOtherArrived to false. Otherwise set hasOtherArrived to true.
A little schema for AB (the BA case is similar)
use a counter . set its value =2;
1. in onreceiveEventA : decerement the counter
if(counter==0){
// you know that event sequence is BA
}
2. in onreceiveEventB :decrement the counter
if(counter==0){
// you know that event sequence is AB
}
Since, I do not know exactly how you are getting your input or your use-case, it is not that clear to me what is better for you. here is what I am thinking about:
You can use queue instead of stack. Since queue follow FIFO style First In First Out. So, no need to reverse the selection like what you are thinking about in Stack
If you are sure there is only two option then you can define two variable. for example choice1 and choice2 where you are storing the first input in choice1 and the second input in choice2.
Note: this solution will not work if there is more than one choice.
Related
I am trying to count an element in an array of objects.
long number = Stream.of(jobTitle).count();
System.out.println("There are " + number + " employees.");
What happens is that it will print out the message as many times as many employees have the same job title. Yet "number" stays always 1.
Any guiding would be much appreciated.
long number = Stream.of(jobTitle).count();
Counts the elements in a stream that contains one element.
It is not surprising that this operation always ends up with the exact same result.
Your code is equivalent to:
List<Whatever> titels = new ArrayList<>();
titels.put(oneEntry);
... print titels.size()
Long story short: that statement is nonsensical. What you probably meant was:
if (arbetstitel.equalsIgnoreCase(jobCount)){
g++;
or something alikw. Of course g is a rather bad name for a counter.
But the real answer here is: step back. Think what the problem is you intend to solve, and what the elements are you need to look at. The code you are showing here is simply not making (much) sense. I can't tell you how to fix it, because, as said: it is not clear what you try to achieve here.
A streamish way of counting:
long usersWithMatchingTitle = Arrays.stream(employees).filter(e -> e.getJobTitle().equalsIgnoreCase(jobTitleFromUser)).count();
Meaning: instead of manually iterating your array, you can turn the whole array into a stream, and then filter/count whatever you want to.
Please note: your code seems to only care about the first 30 elements in that array. If that is really what you want, you will need ...stream(employees).limit(30)...
You need to change the stream of command to define a proper Predicate for filter option.
Stream.of(employees).filter(e -> e.getJobTitle().equals(jobTitle)).count();
I am in need of some help trying to compare 2 arraylist and then sorting; If I am even on the right track. So here is my problem..
Say arraylist 1 contains the objects in which 3 integers adds up to 4 and each integer has to be at least greater or greater/equal to the next number.
So for example, arraylist 1 contains {(2,1,1), (2,2,0), (3,1,0), (4,0,0)}.
Also each object integers are sorted from greatest to least.
Now I have a take the (2,1,1) and send it to a method to perform an algorithm on it. for each integer place, i need to add 2 to that integer place, and subtract 1 from the rest. We can call these A event, B event, or C Event.
for example, (2,1,1) which these events would be
A Event: (4,0,0)
B Event: (3,1,0)
C Event: (3,1,0)
Now, my question is because A event produced (4,0,0) how would I sort the first arraylist to have that number come next and then have (3,1,0) but without (3,1,0) duplicating. So after sorting the array, it should be
(2,1,1) ( 4,0,0) (3,1,0) (2,2,0)
At present your question is not clear to me, but I think I can help point you in the right direction.
Since you said:
without (3,1,0) duplicating
I'd suggest that to ensure uniqueness of objects in a Collection you should consider using a class that implements the Set interface (see Javadoc for Set for details).
Assuming you are not writing the sorting algorithm yourself you could use a SortedSet and then implement the necessary functionality (Comparable interface or Comparator) so that your objects are sorted in the way you want (the earlier link provides links that describe how to do this).
Hope this helps, and if you could try to make the question more clear I'd be happy to offer some additional pointers.
Here are some of the confusing parts that you could work on:
each integer has to be at least greater or greater/equal to the next number.
This is confusing because you're giving two conflicting requirements. Is each number strictly greater than the next or is it greater than or equal to the next?
Also each object integers are sorted from greatest to least.
I'm not sure what you mean by this because you already said that the integers contained in the objects were in a specific order.
because A event produced (4,0,0) how would I sort the first arraylist to have that number come next
You're not really telling us how the sorting should work. Can you describe the algorithm more - how does it decide the order of the items, how should one item be compared with another?
The Title is self explanatory. This was an interview question. In java, List is an interface. So it should be initialized by some collection.
I feel that this is a tricky question to confuse. Am I correct or not? How to answer this question?
Assuming you don't have a copy of the original List, and the randomizing algorithm is truly random, then no, you cannot restore the original List.
The explanation is far more important on this type of question than the answer. To be able to explain it fully, you need to describe it using the mathematical definitions of Function and Map (not the Java class definitions).
A Function is a Map of Elements in one Domain to another Domain. In our example, the first domain is the "order" in the first list, and the second domain is the "order" in the second list. Any way that can get from the first domain to the second domain, where each element in the first domain only goes to one of the elements in the second domain is a Function.
What they want is to know if there is an Inverse Function, or a corresponding function that can "back map" the elements from the second domain to the elements in the first domain. Some functions (squaring a number, or F(x) = x*x ) cannot be reversed because one element in the second domain might map back to multiple (or none) elements in the first domain. In the squaring a number example
F(x) = x * x
F(3) = 9 or ( 3 -> 9)
F(12) = 144 or ( 12 -> 144)
F(-11) = 121 or (-11 -> 121)
F(-3) = 9 or ( -3 -> 9)
attempting the inverse function, we need a function where
9 maps to 3
144 maps to 12
121 maps to -11
9 maps to -3
Since 9 must map to 3 and -3, and a Map must have only one destination for every origin, constructing an inverse function of x*x is not possible; that's why mathematicians fudge with the square root operator and say (plus or minus).
Going back to our randomized list. If you know that the map is truly random, then you know that the output value is truly independent of the input value. Thus if you attempted to create the inverse function, you would run into the delimma. Knowledge that the function is random tells you that the input cannot be calculated from the output, so even though you "know" the function, you cannot make any assumptions about the input even if you have the output.
Unless, it is pseudo-random (just appears to be random) and you can gather enough information to reverse the now-not-truly random function.
If you have not kept some external order information (this includes things like JVM trickery with ghost copies), and the items are not implicitly ordered, you cannot recover the original ordering.
When information is lost, it is lost. If the structure of the list is the only place recording the order you want, and you disturb that order, it's gone for good.
There's a user's view, and there's internals. There's the question as understood and the question as can be interpreted.
The user's view is that list items are blocks of memory, and that the pointer to the next item is a set of (4?8? they keep changing the numbers:) bytes inside this memory. So when the list is randomized and the pointer to the next item is changed, that area of memory is overriden and can't be recovered.
The question as understood is that you are given a list after it had been randomized.
Internals - I'm not a Java or an OS guy, but you should look into situations where the manner in which the process is executed differs from the naive view: Maybe Java randomizes lists by copying all the cells, so the old list is still kept in memory somewhere? Maybe it keeps backup values of pointers? Maybe the pointers are kept at an external table, separate from the list, and can be reconstructed? Maybe. Internals.
Understanding - Who says you haven't got an access to the list before it was randomized? You could have just printed it out! Or maybe you have a trace of the execution? Or who said you're using Java's built it list? Maybe you are using your own version controlled list? Or maybe you're using your own reversable-randomize method?
Edwin Buck's answer is great but it all depends what the interviewer was looking for.
I need to get some input from user in my application, and then use it in Java. But, it is quite more complicated than get some value from GUI and assign it to variable. The value should be processed according some rules.
For example:
input from user is string "2 + 3", then he clicks "RUN" button, and when the button is clicked I need to assign "2" to one variable, "3" to next variable, and then make SUM of it.
I suggest you use http://www.beanshell.org/ This tool is used in a number of IDEs with the debugger to evaluate expressions.
Use the ScriptEngine. E.G. here.
=
If all you needed is to make some simple math calculation like these, I would use 2 Stacks to maintain the syntax. You can tokenise the input Strings and then use one Stack as the operators Stack and the other as the value Stack. And then you know that for every one pop from the operator Stack, the next pop from the value Stack must be an integer. If it isn't, you know the rules is broken and you can throw an error to your user.
Here is some code for a four-function calculator.
This is a question more about best practices/design patterns than regexps.
In short I have 3 values: from, to and the value I want to change. From has to match one of several patterns:
XX.X
>XX.X
>=XX.X
<XX.X
<=XX.X
XX.X-XX.X
Whereas To has to be a decimal number. Depending on what value is given in From I have to check whether a value I want to change satisfies the From condition. For example the user inputs "From: >100.00 To: 150.00" means that every value greater than 100.00 should be changed.
The regexp itself isn't a problem. The thing is if I match the whole From against one regexp and it passes I still need to check which option was inputted - this will generate at least 5 IFs in my code and every time I want to add another option I will need to add another IF - not cool. Same thing if I were to create 5 Patterns.
Now I have a HashMap which holds a pattern as the key and a ValueMatcher as the value. When a user inputs a From value then I match it in a loop against every key in that map and if it matches then I use the corresponding ValueMatcher to actually check if the value that I want to change satisfies the "From" value.
This aproach on the other hand requires me to have a HashMap with all the possibilities, a ValueMatcher interface and 5 implementations each with only 1 short "matches" methode. I think it sure is better than the IFs, but still looks like an exaggerated solution.
Is there any other way to do it? Or is this how I actually should do it? I really regret that we can't hold methods in a HashMap/pass them as arguments because then I'd only have 1 class with all the matching methodes and store them in a HashMap.
How about a chain of responsibility.
Each ValueMatcher object exactly one From/To rule and a reference to the next ValueMatcher in the chain. Each ValueMatcher has a method which examines a candidate and either transaforms it or passes it on to the next in the chain.
This way adding a new rule is a trivial extension and the controlling code just passes the candidate to the first member of the chain.
a ValueMatcher interface and 5 implementations each with only 1 short "matches" methode. I think it sure is better than the IFs, but still looks like an exaggerated solution.
Well, for something as simple as evaluating a number against an operator and a limit value, couldn't you just write one slightly more generic ValueMatcher which has a limit value and an operator as its parameters? It would then be pretty easy to add 5 instances of this ValueMatcher with a few combinations of >, >=, etc.
EDIT: Removed non Java stuff... sorry about that.