Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Pay particular attention to the encode method. It has some bithacks =).</p> <pre><code>import java.util.*; class MortonQuadTree&lt;E&gt; { List&lt;E&gt; data = new ArrayList&lt;E&gt;(); public E insert(int x, int y, E e) { int pos = encode(x,y); ensureCapacity(pos); return data.set(pos,e); } public E query(int x, int y) { int pos = encode(x,y); return data.get(pos); } private void ensureCapacity(int size) { while(data.size() &lt; size + 1) data.add(null); } // technically the values here aren't final... don't overwrite them :) static final int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF}; static final int S[] = {1, 2, 4, 8}; /** * Interleave lower 16 bits of x and y, so the bits of x * are in the even positions and bits from y in the odd; * x and y must initially be less than 65536. * Adapated from http://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN */ private static int encode(int x, int y) { x = (x | (x &lt;&lt; S[3])) &amp; B[3]; x = (x | (x &lt;&lt; S[2])) &amp; B[2]; x = (x | (x &lt;&lt; S[1])) &amp; B[1]; x = (x | (x &lt;&lt; S[0])) &amp; B[0]; y = (y | (y &lt;&lt; S[3])) &amp; B[3]; y = (y | (y &lt;&lt; S[2])) &amp; B[2]; y = (y | (y &lt;&lt; S[1])) &amp; B[1]; y = (y | (y &lt;&lt; S[0])) &amp; B[0]; return x | (y &lt;&lt; 1); } public static void main(String[] args) { MortonQuadTree&lt;String&gt; tree = new MortonQuadTree&lt;String&gt;(); tree.insert(1,4,"Hello"); tree.insert(6,8,"World"); System.out.println(tree.query(1,4)); // should be hello System.out.println(tree.query(6,8)); // should be world System.out.println(tree.query(9,6)); // should be null System.out.println(tree.query(900,600)); // should be index error } } </code></pre>
 

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