Cardinal direction algorithm in Java -
At the end of this week, I will take an algorithm that takes a title (in degrees) and back together for a string Beating spend a few minutes on the main direction (I'm using it in an Android Compass app). I ended up with it:
Private string headingtoostring (float heading) {string strHeading = "?"; Hashtable & lt; String, float & gt; Cardinal = new hashtable & lt; String, float & gt; (); Cardinal.put ("North_1", new Float (0)); Cardinal.put ("Northeast", New Float (45)); Cardinal.put ("East", New Float (90)); Cardinal.put ("southeast", new float (135)); Cardinal.put ("south", new float (180)); Cardinal.put ("south west", new float (225)); Cardinal.put ("west", new float (270)); Cardinal.put ("Northwest", New Float (315)); Cardinal.put ("North_2", new float (360)); For (string key: cardinal.keySet ()) {float value = cardinal.get (key); If (mathematics.base (title - value) <30) {strHeading = key; If (key.contains ("North_")) {strHeading = "North"; } break; }} Return Strawing; }
My question is, is this the best way to do it? It should have been done several times earlier, although I have not yet searched for examples on the web.
Solution
[East] In most cases this is fine, although it is optimized and (IMO) cleaner For what you can do, you can find a function to address the input title used in the map. For example: (I'm pretty sure this is correct, but you want to see it) This is the first 45 near priceless. Now change your map So, now instead of roaming through the algorithm map, The calculation becomes. In addition, you do not have to have a handshake because it creates concurrency (if I remember correctly) and in your case it actually reduced performance. Once again, the performance hits can be completely negligible for your needs. Edit for Thilo and Shinjin's suggestions: Instead of multiplying by 45, keep the rest of the equation, which gives value to 0-7, and string directions [] = {"N", "NE", "E", "SE", "S", "SW", "W" [String Guideline] [/ p], "NW"} Return Directions [(Int) Math Field (((double (double) x% 360) / 45))% 8] And you have solved your problem in two rows. A Note: Modulus will not work properly for negative numbers. If our input title is negative, then you have to make it positive earlier. Public stable String HeadingString 2 (Double X) {String Directions [] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW", "N"} ; Returning directions [(int) Mathrade ((((x) x% 360) / 45); } "
45 * (int) Mathround (((((double) X% 360) / 45))
X% 360
ensures that the title is within a valid range. finds 45 * round (... / 45)
hashmap < Integer, string & gt; Map = new hashmap & lt; Integer, string & gt; Map.put (0, "answer") map.put (45, "Northeast") etc ...
Comments
Post a Comment