Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>That's fine in most cases, though to make it optimized and (IMO) cleaner, what you could do is find a function to relate the input heading to one used in the map.</p> <p>For example: (I'm pretty sure this is right, but you'll want to check it)</p> <pre><code>45* (int)Math.round(( ((double)x % 360) / 45)) </code></pre> <p>What this does is first <code>x % 360</code> makes sure the heading is within a valid range. then </p> <pre><code>45 * round(.../45) </code></pre> <p>finds the closest multiple of 45.</p> <p>Now change your map to be </p> <pre><code> HashMap&lt;Integer, String&gt; map = new HashMap&lt;Integer, String&gt;() map.put(0, "North") map.put(45, "Northeast") etc... </code></pre> <p>So, now your algorithm becomes a fast mathemtical calculation rather than iterating through the map. Furthermore, you don't need as Hashtable here since it provides constructs for concurrency (if I remember correctly) and in your case it would actually cause a performance decrease.</p> <p>Once again, the performance hit may be completely negligible for your needs.</p> <p>Edit for Thilo's and shinjin's suggestions:</p> <p>Instead of multiplying by 45, just keep the rest of the equation, which gives you values for 0-7, and make an array of your strings.</p> <pre><code>String directions[] = {"N", "NE", "E", "SE", "S", "SW", "W", "NW"} return directions[ (int)Math.round(( ((double)x % 360) / 45)) % 8 ] </code></pre> <p>and you've got your problem solved in two lines.</p> <p>One note: Modulus won't work correctly for negative numbers. If our input heading is negative, you'll need to make it positive first.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload