Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strong>Table lookup</strong></p> <pre><code>#include &lt;stdio.h&gt; #define SIZE 16 #define SIDE 4 //sqrt(SIZE) int table[SIZE]; int rtable[100];// {x,y| x&lt;=99, y&lt;=99 } void setup(){ int i, x, y, xy, index;//xy = x + y x=y=xy=0; for(i=0;i&lt;SIZE;++i){ table[i]= index= x*10 + y; rtable[x*10+y]=i; x = x + 1; y = y - 1;//right up if(y &lt; 0 || x &gt;= SIDE){ ++xy; x = 0; y = xy;; while(y&gt;=SIDE){ ++x; --y; } } } } int getNGonalNeighbor(int index, int offsetX, int offsetY){ int x,y; x=table[index] / 10 + offsetX; y=table[index] % 10 + offsetY; if(x &lt; 0 || x &gt;= SIDE || y &lt; 0 || y &gt;= SIDE) return -1; //ERROR return rtable[ x*10+y ]; } int main() { int i; setup(); printf("%d\n", getNGonalNeighbor(15,-1,-1)); printf("%d\n", getNGonalNeighbor(15, 0,-1)); printf("%d\n", getNGonalNeighbor(15,-1, 0)); printf("%d\n", getNGonalNeighbor(11,-2,-1)); printf("%d\n", getNGonalNeighbor(0, -1,-1)); return 0; } </code></pre> <p>don't use table version.</p> <pre><code>#include &lt;stdio.h&gt; #define SIZE 16 #define SIDE 4 void num2xy(int index, int *offsetX, int *offsetY){ int i, x, y, xy;//xy = x + y x=y=xy=0; for(i=0;i&lt;SIZE;++i){ if(i == index){ *offsetX = x; *offsetY = y; return; } x = x + 1; y = y - 1;//right up if(y &lt; 0 || x &gt;= SIDE){ ++xy; x = 0; y = xy;; while(y&gt;=SIDE){ ++x; --y; } } } } int xy2num(int offsetX, int offsetY){ int i, x, y, xy, index;//xy = x + y x=y=xy=0; for(i=0;i&lt;SIZE;++i){ if(offsetX == x &amp;&amp; offsetY == y) return i; x = x + 1; y = y - 1;//right up if(y &lt; 0 || x &gt;= SIDE){ ++xy; x = 0; y = xy;; while(y&gt;=SIDE){ ++x; --y; } } } return -1; } int getNGonalNeighbor(int index, int offsetX, int offsetY){ int x,y; num2xy(index, &amp;x, &amp;y); return xy2num(x + offsetX, y + offsetY); } int main() { printf("%d\n", getNGonalNeighbor(15,-1,-1)); printf("%d\n", getNGonalNeighbor(15, 0,-1)); printf("%d\n", getNGonalNeighbor(15,-1, 0)); printf("%d\n", getNGonalNeighbor(11,-2,-1)); printf("%d\n", getNGonalNeighbor(0, -1,-1)); return 0; } </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