Programming design efficiency - java

I'm currently writing a piece of code that handles the User Interface of my app.
The code has the objective of setting the location of text in orientation to two other points (centering the text). For example:
PointX 1 = 50;
PointX 2 = 150;
This input would yield the X value of the text to be 100.
My question now is that each time when the UI is refreshed this simple calculation is performed. Is this permissible or should I create a variable that stores the x value?
NB: The reason why I'm not going with the variable method, is that this would up the amount of variables in my code, which I'm not a big fan of, since I'm trying to keep my code as clean, simply and maintainable as possible.

If you are trying to keep it simple and keep memory down I would keep it the way you have it now. I'd assume that you are finding the average between the two values and this is not a very expensive operation.

Related

Efficiently gathering data from a game board

Say I have a connect-4 board, it's a 7x6 board, and I want to store what piece is being stored in what spot on that board. Using a 2-array would be nice, on the fact that I can quickly visualize it as a board, but I worry about the efficiency of looping through an array to gather data so often.
What would be the most efficient way of 1) Storing that game board and 2) Gathering the data from the said game board?
Thanks.
The trite answer is that at 7x6, it's not going to be a big deal: Unless you're on a microcontroller this might not make a practical difference. However, if you're thinking about this from an algorithm perspective, you can reason about the operations; "storing" and "gathering" are not quite specific enough. You'll need to think through exactly which operations you're trying to support, and how they would scale if you had thousands of columns and millions of pieces. Operations might be:
Read whether a piece exist, and what color it is, given its x and y coordinates.
When you add a piece to a column, it will "fall". Given a column, how far does it fall, or what would the new y value be for a piece added to column x? At most this will be height times whatever the cost of reading is, since you could just scan the column.
Add a piece at the given x and y coordinate.
Scan through all pieces, which is at most width times height times the cost of reading.
Of course, all of this has to fit on your computer as well, so you care about storage space as well as time.
Let's list out some options:
Array, such as game[x][y] or game[n] where n is something like x * height + y: Constant time (O(1)) to read/write given x and y, but O(width * height) to scan and count, and O(height) time to figure out how far a piece drops. Constant space of O(width * height). Perfectly reasonable for 7x6, might be a bad idea if you had a huge grid (e.g. 7 million x 6 million).
Array such as game[n] where each piece is added to the board and each piece contains its x and y coordinate: O(pieces) time to find/add/delete a piece given x and y, O(pieces) scan time, O(pieces) space. Probably good for an extremely sparse grid (e.g. 7 million x 6 million), but needlessly slow for 7x6.
HashMap as Grant suggests, where the key is a Point data object you write that contains x and y. O(1) to read/write, O(height) to see how far a piece drops, O(pieces) time to scan, O(pieces) space. Slightly better than an array, because you don't need an empty array slot per blank space on the board. There's a little extra memory per piece entry for the HashMap key object, but you could effectively make an enormous board with very little extra cost, which makes this slightly better than option 1 if you don't mind writing the extra Point class.
An array of resizable column arrays, e.g. List. This is similar to an array of fixed arrays, but because List stores its size and can allocate only as much memory as needed, you can store the state very efficiently including how far a piece needs to fall. Constant read/write/add, constant "fall" time, O(pieces) + O(width) scan time, O(pieces) + O(width) space because you don't need to scan/store the cells you know are empty.
Given those options, I think that an array of Lists (#4) is the most scalable solution, but unless I knew it needed to scale I would probably choose the array of arrays (#1) for ease of writing and understanding.
I may be wrong, but I think you're looking a hashmap (a form of hashtable) if you want efficiency.
Here's the documentation:
https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html
HashMap provides expected constant-time performance O(1) for most operations like add(), remove() and contains().
Since you're using a 7x6 board, you can simply name your keys and values A1 ... A6 for example.

How to get the amount of torque of a Body in Box2D?

I'm making a LibGDX game with Box2D. I have a car, which back wheels get some extra torque when a key is pressed, in order to accelerate. The car is connected with the wheels using joints.
public void handleInput(){
if(Gdx.input.isKeyPressed(Input.Keys.D)){
wheelBody.applyTorque(-100f, true); //Add torque when 'D' is pressed
}
}
But if you press the key when the car is in the air, the torque becomes huge. When the car wheels touch the ground, the car gets launched forward. I could avoid that by using a MAX_TORQUE value. The torque will only increase when it's below MAX_TORQUE.
But how can I 'measure' the amount of torque currently on the wheels? I haven't found a wheelBody.getTorque() function. Or is there another solution?
I don't think you will like the following answer (I don't). I'm not aware of a better way to deal with this than the following suggestions short of modifying the both the C++ Box2D source and the Java source code that interfaces to that.
Explanation:
Looking at the Box2D source code, the torque on a body is stored in its m_torque member variable. This variable gets incremented by the call to the Java applyTorque method. Meanwhile the m_torque variable has no public way to get its current value. That came as a surprise to me to discover (i.e. to confirm what it sounds like you already discovered) when initially trying to answer your question.
This variable's only use is in Box2D's island solver code where it's used to increment the body's angular velocity. It's used directly though by the b2Island class that's a friend class of the b2Body class.
Work Around #1
OTOH, calling the world step method, by default invokes the world clear forces method. This in turn resets all bodies' torques back to 0. That means the torque after a given step could be determined from the delta time of that step, the body's rotational inertia, and the body's angular velocity. All of which can be accessed via public methods.
Calculating the torque from the values these value that can be accessed is probably achieved via some math like: torque = I * w / h (where I is the rotational inertia of the body accessed from the get mass data method, w is the angular velocity that's accessed from the get-angular-velocity method, and h is the time delta of the step). That assumes that your body has its angular damping set to zero however (which it is by default). This seems pretty ugly to me though, uglier than my second solution at least.
Work Around #2
The way I'd deal with the lack of the torque getter, is to manually keep track of the sum torque I had applied on the body between world steps and just bite-the-bullet and use that value then.
If you needed, you could track this sum value in the body's user data field if you're not already using that for something else. There's other ways to keep track of it of course but none that are elegant IMO.

Box containing as much given points as possible in a coordinate system

I have a question:
It's may a bit more a mathematical question, but in informatical context.
I have a number of n points on a coordinate system. (They are randomly placed.)
My problem is, to find a box which has a diameter d and (theoretically) infinite length (like a big line) that contains as much of the n points as possible.
Any idea?
I finally want to write a programm in Java based on the answers, but a already written one is welcome, too ;)

Is it better to modify an object directly or to return a modified clone of the object?

The problem is I can't modify an object I'm writing from inside itself and thus made a clone that I modify and return. However, in other functions I directly modify the object calling the method. I would like, and people have recommended, to keep things consistent and so the user can do anything they like with the returned clone without modifying the actual object.
I HAVE to return a modified clone of the object in certain functions because there's no way around it (that I'm aware of). Along with the question in the title, is it better to have a consistent way of doing things (causing me to return clones for even the slightest change) or is it okay if I have different ways to respond to the user in the same class?
[Edit] Is it better to do this:
public Image fillWithColor(Color fillColor) {
Image newImage = new Image(this.getWidth(), this.getHeight(), this.getType());
for (int x = 0; x < this.getWidth(); x++) {
for (int y = 0; y < this.getHeight(); y++) {
newImage.setPixel(x, y, fillColor.getRGB());
}
}
return newImage;
}
or this:
public void fillWithColor(Color fillColor) {
for (int x = 0; x < this.getWidth(); x++) {
for (int y = 0; y < this.getHeight(); y++) {
this.setPixel(x, y, fillColor.getRGB());
}
}
}
A mega-trend is to treat as much data as possible as read-only, for various important reasons. Even databases do this today.
You obviously have recognized that uncontrolled modification of data can get you into trouble. Very good. Try to design your data as immutable objects, and many things will be much easier in the long run. Just note that certain data structures in Java are inherently mutable (arrays, hash-tables, and so on), and are meant and expected to get mutated.
In the exmple above, I'd choose the first variant. Why? It might cost a few microseconds and some RAM to copy the image, instead to update in-place. But you can keep the old image around, and depending on your application, this may be beneficial. Also, you could color the same image with 10 different fill colors in 10 different threads in parallel, and there would be no locking problems.
That being said, it is still not possible to answer your question like "It is always better ...". It depends on your problem, on your environment, programming language, libraries you are using and many factors more.
So let's say, immutable data are preferrable most of the time, unless there are serious reasons against it. (Saving a few micro-seconds on execution time is usually not a serious reason.)
To put it differently, there should be good reasons to make a data type mutable, while immutability should be the default. Unfortunately, Java is not the language that supports this approach, to the contrary, everything is mutable by default, and it takes some effort to make it different.
The only correct answer is:
"It depends".
This is what engineering is all about. Making the right trade offs. Suppose you are an engineer working for the city and tasked with designing new garbage bins for the city center. You have some decisions to make. You want to make them big, so they can contain lots of garbage and don't overflow on busy days. But you also want to make them small so they don't take up a lot of space on the sidewalk. You want to make them light so they can be handled easily when emptying them, and heavy so they aren't blown over by the wind or kicked over by hooligans. So it's not a question of big or small and heavy or light, but how big and how heavy.
In software engineering there are also many mutually exclusive qualities for which you have to make the right choice in your project. Some examples:
latency vs throughput - do you want to react quickly to requests, or do you want to get a lot of work done;
memory vs cpu - are you okay with using lots of memory as a look-up table, or will you burn cpu time to calculate the answer.
Immutable vs mutable
The advantage of immutable types is that they are thread-safe. Thread A and B can both have a reference to the same object and still be sure its value will not change unexpectedly without using locks. If thread A wants to change the value then it can do so by changing the reference it holds to a new object; thread B is still happily holding onto the original object.
Having the value of an object change unexpectedly is not only a problem in concurrent programming, but can also occur when the users of your class are not expecting it. That is why there is the concept of defensive copying.
The stock Date class in java is mutable. So consider a Person class with a getBirthDate() getter and setBirthDate() setter. As a user of the Person class you would expect to only be able to change the birth date of the person by using the setter, but if your getter does not return a defensive copy then the user of the class can also change it unexpectedly by changing the Date object it received from getBirthDate().
So immutable types make programs thread-safe(r) and less error prone and are therefore generally a good idea but you can not always use them. Your fillWithColor() function is an example where it isn't really feasible.
A Canvas class is a mutable object. You would have a fillWithColor() function, but also drawLine(), drawElipse(), drawText(), and many more. Building up a drawing with these functions can take many calls. Consider drawing a 'no parking' traffic sign:
fill with background color
draw a red circle
draw a white circle inside it
draw a black P inside that
draw a red diagonal line across it
If your Canvas class is immutable you would need five times the amount of memory and process five times the number of pixels. And this is really a trivial example. Consider this SVG image of a cheetah. Every spot on its back is a call to a draw function.
It depends
I would say that you should use immutable types where you can and use immutable where you can not. Generally this divide falls along small vs big data types.
If your type references a data structure that is small enough to be a value type then it should probably be an immutable reference type. Like the java Date should have been immutable, after all it's only 8 bytes.
If your type references something big and you need to allow many operations on it, then you will have to be pragmatic and make it a mutable type. Like your Canvas example, after all images can be megabytes big.
Mutable and immutable are both needed.

Cost of storing and retrieving data

I am dealing with the case of pattern recognition and for input, I need to read coordinates of points, up to 10000 points from a text file. I need to perform certain calculations on the points read. So, my question is whether I should always read them from the text file when I need to do some calculation or I should store them in some data structure, eg, a 2D array and hence access the values. What difference would there be in terms of storage and time?
Edit:
The language I am using is Java.
The data structure is user defined that has
a constructor that instantiates the object with x and y coordinates.
a method to draw the point on standard output.
a method to draw a line between two given points.
a method to compare the position of two points based on coordinates.
a method to compute the slope between two points.
an inner class extending Comparable interface that can be used to compare two points.
The comparison is based on slope made by each point w.r.t a reference point.
PS - I am sorry if the question is a silly one but just wanted to be clear about things than shying back. Thanks in advance!
Well storing them in the memory will be the recommended option here, assuming that its a static text file(meaning that the points don't change when you are running the recognition ) as it will really speed up the whole process and 10000 points is not too large to be cached in memory.
Not to mention this point also depends on the fact which language and data structure you are using.

Categories

Resources