How to store data from generated text fields - java

Here's an overview of what I want to do.
The program will accept positive and negative integers to do addition, substraction, multiplication, division.
There will be two jars beside each other, while the numbers are being entered balls will drop in the jar.
If the numbers being entered are positive it will drop in one jar and if the numbers are negative it will drop in the other jar. When the calculation is perform the results of the number of balls will remain in the jar.
Also more than two numbers can be calculated at one time.
It's simple but am not sure what path to take.
Can someone guide me on how to this.
I have started but not sure if am on the right track.
Here's what I did so far.
I have two text field with a drop down to choose the type of operation (x, /, -, +).
An "add" button to add more text field if more numbers are required.
But am not sure how to store those numbers and have the numbers drop the amount of balls as they are enter into the text field.
Any help or ideas would be greatful.
Thanks.

Unless I misunderstand what you are trying to do, it looks like you want to have a sort of visual calculator with a variable number of operations per calculation.
While many may argue this, an easy and educational way of doing this would be to create an "Operation" object (class) that holds the entered number and the operation that will be performed (+-*/).
From here there are two approaches that you can take...
The sane approach:
Limit the number of operations to a sane number (ie. 8) and create a statically sized array ( ie. Operation[] ops = new Operation[8]; ) and for every new operation up to the limit, add it to the array.
Once you do this you can either keep a counter of entries or search through the array until you hit an uninitialized index then sort the operations by precedence (+ then - then * then /...) and run the calculation.
The not-so-sane approach:
Unlimited operations! The same thing as previous only using an ArrayList ( ArrayList, java API ) and once you have the total number of entries, do the same as above.
Happy coding ;)

Related

query for Math.random to generate only a certain amount of each number needed

I am curious if anyone knows a way to use math.random to generate random numbers between say 0 and 3, But when it generates two 0's or two 1's it rules out the possibility of generating them numbers?
This is for a game assignment for college and all I have left to do is set it that it only generates two of each number with one 3. If anyone knows how this would be very helpful (even if it is using something other than math.random.
The language is Java.
So, you basically want to keep track of the number draws, right?
A possible solution is to use an array whose length is the valid range of your random numbers, where each cell counts the occurrences of the respective number. Then, for each draw, you check the contents of the respective cell in the array to see if you reached the limit. If you did, then redraw and repeat.
Note: at the time of writing this, the language of use is unknown, but the solution is generic enough to be implemented in virtually any language that provide a random() function.

storing sets of integers to check if a certain set has already been mentioned

I've come across an interesting problem which I would love to get some input on.
I have a program that generates a set of numbers (based on some predefined conditions). Each set contains up to 6 numbers that do not have to be unique with integers that ranges from 1 to 100).
I would like to somehow store every set that is created so that I can quickly check if a certain set with the exact same numbers (order doesn't matter) has previously been generated.
Speed is a priority in this case as there might be up to 100k sets stored before the program stops (maybe more, but most the time probably less)! Would anyone have any recommendations as to what data structures I should use and how I should approach this problem?
What I have currently is this:
Sort each set before storing it into a HashSet of Strings. The string is simply each number in the sorted set with some separator.
For example, the set {4, 23, 67, 67, 71} would get encoded as the string "4-23-67-67-71" and stored into the HashSet. Then for every new set generated, sort it, encode it and check if it exists in the HashSet.
Thanks!
if you break it into pieces it seems to me that
creating a set (generate 6 numbers, sort, stringify) runs in O(1)
checking if this string exists in the hashset is O(1)
inserting into the hashset is O(1)
you do this n times, which gives you O(n).
this is already optimal as you have to touch every element once anyways :)
you might run into problems depending on the range of your random numbers.
e.g. assume you generate only numbers between one and one, then there's obviously only one possible outcome ("1-1-1-1-1-1") and you'll have only collisions from there on. however, as long as the number of possible sequences is much larger than the number of elements you generate i don't see a problem.
one tip: if you know the number of generated elements beforehand it would be wise to initialize the hashset with the correct number of elements (i.e. new HashSet<String>( 100000 ) );
p.s. now with other answers popping up i'd like to note that while there may be room for improvement on a microscopic level (i.e. using language specific tricks), your overal approach can't be improved.
Create a class SetOfIntegers
Implement a hashCode() method that will generate reasonably unique hash values
Use HashMap to store your elements like put(hashValue,instance)
Use containsKey(hashValue) to check if the same hashValue already present
This way you will avoid sorting and conversion/formatting of your sets.
Just use a java.util.BitSet for each set, adding integers to the set with the set(int bitIndex) method, you don't have to sort anything, and check a HashMap for already existing BitSet before adding a new BitSet to it, it will be really very fast. Don't use sorting of value and toString for that purpose ever if speed is important.

Random Number generator to cover all numbers in the set

I am writing an Android app and I want to generate random numbers.
But, Java's RandomGenerator gives me only pseudo random numbers. The numbers repeat and not all the numbers are covered.
I want something that will give me non-repeating numbers and will cover all the numbers. How do I do that?
You can put all random values you want into a List and shuffle it.
List<Integer> numbers = ...
Collections.shuffle(numbers);
This will give you unique numbers in a random order.
You could fill a data structure with the numbers you want to loop over, then randomize the order of the elements in the structure and pull them out one by one. Alternatively, you could randomly pick indexes, and retrieve elements at those indexes. Whichever you do (you would choose the one more efficient for the specific data structure), you be sure to remove this element as you grab it. As you keep going your data structure will get smaller and smaller until you've received every element and have nothing left. This also ensures you'll never hit the same number twice, because you'll have removed it from your pool of possible numbers.

How to keep the for-loop counter at 0; BigDecimal; etc

I have been trying to complete the following assignment for my college. So far, I have received help on this assignment a couple of times (which I really appreciate).
Since this is an assignment for college, I would appreciate non-direct answers that explain the concepts with examples that don't directly fix my assignment.
The assignment requires me to check for some things depending on user input.
If the user inputs an order, then inputs the same order with the same code again, it replaces the previous information with the new one. EG, if the user inputs G22 as code and 5 as quantity, then again enters G22 and then 4 as quantity, it forgets about the 5 and replaces that with 4. How can I make it so it remembers the previous one and simply adds the new order and makes it Quantity = 9 (I am using arrays for user input).
If the user enters G22 and quantity 3, but then doesn't enter anything and just hits enter, the counter adds one and upon pressing X (to quit) the shipping charges show up as $2.00 which is for 2 items. How can I avoid the counter from adding 1 in case nothing sensible is entered, i.e. anything else apart from the 4 options available is entered.
I understand that using doubles is not advisable for anything related to money and BigDecimal is recommended (alongwith NumberFormat, maybe). Can I replace my current doubles with BigDecimal with minimal problems, or do I have to replace the whole code? I also do not understand how to implement BigDecimal that easily so I would appreciate layman examples on that (especially on whether I can add/subtract/multiply/divide BigDecimal with ints etc).
I would post the code here but I don't want it copied by anyone else doing the same course and then submit it before I do (not that my code is the most awesome thing in the world, I just put in a lot of effort since its my first ever program).
1) I would use a Map<String, Integer> to store all the quantities for a product code.
2) I would get the total of items ordered by summing the quantities in the map. How the user enters the data shouldn't matter.
3) This advice is project dependant. In your case the option of the marker is what matters. Working in investment banks and trading firms for many years, and I haven't seen anyone use BigDecimal for money. Its not a major rewrite, and at a minimum you should know how to use both double and BigDecimal handling rounding correctly.

How do I apply a sequence of insert/delete-character operations on a string?

I have a text like this:
My name is Bob and I live in America.
I have some reference to the characters of this string, for example:
from 3 to 7 chars, deleted
at 3 char, added "surname"
from 20 to 25, deleted
at 25 char ....
but these statements aren't ordered (and I can't order them).
So, this is the question: how can I modify the text without losing the reference of the characters?
For example, if I apply the first sentence, my text became:
My is Bob and I live in America.
and my third sentence doesn't work correctly anymore, cause I've lost the reference to the original 20th character.
Keep in mind that the text is pretty long, so I can't use any indexes...
First off, if this statement is true, the situation is hopeless:
but these statements aren't ordered (and I can't order them).
An unordered list of patch statements could lead to a conflict. It will not be possible to decide what the right answer is in an automated fashion. For instance, consider the following situation:
0 1 2
index: 012345678901234567890
text: "apple banana coconuts"
- delete 5 characters from index 10
- add "xyz" at index 10
- delete 10 characters from index 5
You will wind up with different results depending on what order you execute these statements.
For instance, if you apply (1), then (2), then (3), you wind up with "apple banaconuts" --> "apple banaxyzconuts" --> "apple uts".
But if you apply (3), then (2), then (1), you wind up with "apple onuts" --> "apple onutsxyz" --> [error -- there aren't enough characters to delete!].
Either you need a repeatable, agreed-upon ordering of the statements, or you cannot proceed any further. Even worse, it turns out that discovering which orderings are valid (for example, eliminating all orderings where an impossible statement occurs, like "delete 10 characters from index 20", when there is no index 20) is an undecidable computer science problem.
If it turns out that the patches can be applied in a specific order (or at least in a repeatable, agreed-upon, deterministic order), the situation improves but is still obnoxious. Because the indices in any "patch" could be invalidated by any previous one, it's not going to be possible to straightforwardly apply each statement. Instead, you'll have to implement a small, pseudo-diff. Here's how I'd do it:
Scan through the list of patch-statements. Build a list of operations. An operation is an object with a command and some optional arguments, and an index to apply that command to. For example, your operations might look like:
DeleteOperation(index 3, length 4)
AddOperation(index 3, text "surname")
DeleteOperation(index 20, length 5)
As you perform operations, keep a reference to the original string and store a "dirty pointer". This is the latest contiguous index in the string which has had no operations performed on it. Any operation you perform whose index exceeds the dirty pointer must first be pre-processed.
If you encounter a clean operation, one whose index is less than or equal to the dirty pointer, you can apply it with no further work. The dirty pointer now moves to that operation's index.
If you encounter a dirty operation, one whose index is greater than the dirty pointer, you'll have to do some work before you can apply it. Determine the real index of where the operation should be applied by looking at the previous operations, then make the appropriate offset and apply it.
Execute each operation in turn until there are no more operations to execute.
The result is your transformed string.
You will just have to track what you are doing to the string and add or subtract from future item indexes in your list of commands.
Each time you execute a statement go over the whole list and modify indexes appropriately.
Sounds like you are doing Operational Transforms
This article over here discusses them in theory and practice (and quite some depth)
Understanding and Applying Operational Transformation
If they aren't in any order though, how can you apply them? How do you know if one operation should be applied before or after another operation? Are none of the operations additive? (ie: do all of the operations only apply to the original String?)
What exactly are you trying to do here?
If you are trying to apply these "references" to your text,
My name is Bob and I live in America.
Keep this data unaltered. Copy this to another string, and apply your "reference" there every time you need to modify it.

Categories

Resources