Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a variant without nested loops. I've tried to use a similar to <a href="https://stackoverflow.com/questions/327531/can-i-optimize-code-that-has-3-for-loops-and-4-ifs">your question</a> notation.</p> <pre><code>// g++ 26neighbours.cpp -o 26neighbours &amp;&amp; 26neighbours #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;vector&gt; namespace { struct Pos { double x, y, z; template&lt;class Char, class Traits&gt; friend std::basic_ostream&lt;Char, Traits&gt;&amp; operator&lt;&lt; (std::basic_ostream&lt;Char, Traits&gt;&amp; out, const Pos&amp; p) { return out &lt;&lt; p.x &lt;&lt; " " &lt;&lt; p.y &lt;&lt; " " &lt;&lt; p.z; } explicit Pos(double x_ = 0, double y_ = 0, double z_ = 0) : x(x_), y(y_), z(z_) { } }; template &lt;class OutputPosIterator, class InputPosIterator, class Number&gt; void translate(OutputPosIterator first, OutputPosIterator last, InputPosIterator delta, Number factor) { for ( ; first != last; ++first, ++delta) { first-&gt;x += delta-&gt;x * factor; first-&gt;y += delta-&gt;y * factor; first-&gt;z += delta-&gt;z * factor; } } } int main(int argc, char *argv[]) { const Pos delta[] = { // ruby -e"(-1..1).each{|i| (-1..1).each{|j| (-1..1).each{|k| printf(\"Pos(%2d,%2d,%2d),\n\", i, j, k) if (i!=0 || j!=0 || k!=0)}}}" Pos(-1,-1,-1), Pos(-1,-1, 0), Pos(-1,-1, 1), Pos(-1, 0,-1), Pos(-1, 0, 0), Pos(-1, 0, 1), Pos(-1, 1,-1), Pos(-1, 1, 0), Pos(-1, 1, 1), Pos( 0,-1,-1), Pos( 0,-1, 0), Pos( 0,-1, 1), Pos( 0, 0,-1), Pos( 0, 0, 1), Pos( 0, 1,-1), Pos( 0, 1, 0), Pos( 0, 1, 1), Pos( 1,-1,-1), Pos( 1,-1, 0), Pos( 1,-1, 1), Pos( 1, 0,-1), Pos( 1, 0, 0), Pos( 1, 0, 1), Pos( 1, 1,-1), Pos( 1, 1, 0), Pos( 1, 1, 1), }; const int N = sizeof(delta) / sizeof(*delta); // find neighbours of somePos double cube_size = 0.5; Pos somePos(0.5, 0.5, 0.5); std::vector&lt;Pos&gt; neighbours(N, somePos); translate(neighbours.begin(), neighbours.end(), delta, cube_size); // print neighbours std::copy(neighbours.begin(), neighbours.end(), std::ostream_iterator&lt;Pos&gt;(std::cout, "\n")); std::cout &lt;&lt; std::endl; 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