Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a simple C version of the solution that takes advantage of the Ai + Ak must be even test:</p> <pre><code>#include &lt;stdio.h&gt; static int arr[] = {9, 4, 2, 3, 6, 10, 3, 3, 10}; int main () { int i, j, k; int sz = sizeof(arr)/sizeof(arr[0]); int count = 0; for (i = 0; i &lt; sz - 2; i++) { for (k = i + 2; k &lt; sz; k++) { int ik = arr[i] + arr[k]; int ikdb2 = ik / 2; if ((ikdb2 * 2) == ik) // if ik is even { for (j = i + 1; j &lt; k; j++) { if (arr[j] == ikdb2) { count += 1; printf("{%d, %d, %d}\n", arr[i], arr[j], arr[k]); } } } } } printf("Count is: %d\n", count); } </code></pre> <p>and the console dribble:</p> <pre><code>tmp e$ cc -o triples triples.c tmp e$ ./triples {9, 6, 3} {9, 6, 3} {2, 6, 10} {2, 6, 10} {3, 3, 3} Count is: 5 tmp e$ </code></pre> <p>This more complicated version keeps a list of Aj indexed by value to go from n-cubed to n-squared (kinda).</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdint.h&gt; static uint32_t arr[] = {9, 4, 2, 3, 6, 10, 3, 3, 10}; #define MAX_VALUE 100000u #define MAX_ASIZE 30000u static uint16_t index[MAX_VALUE+1]; static uint16_t list[MAX_ASIZE+1]; static inline void remove_from_index (int subscript) { list[subscript] = 0u; // it is guaranteed to be the last element uint32_t value = arr[subscript]; if (value &lt;= MAX_VALUE &amp;&amp; subscript == index[value]) { index[value] = 0u; // list now empty } } static inline void add_to_index (int subscript) { uint32_t value = arr[subscript]; if (value &lt;= MAX_VALUE) { list[subscript] = index[value]; // cons index[value] = subscript; } } int main () { int i, k; int sz = sizeof(arr)/sizeof(arr[0]); int count = 0; for (i = 0; i &lt; sz - 2; i++) { for (k = i; k &lt; sz; k++) remove_from_index(k); for (k = i + 2; k &lt; sz; k++) { uint32_t ik = arr[i] + arr[k]; uint32_t ikdb2 = ik / 2; add_to_index(k-1); // A(k-1) is now a legal middle value if ((ikdb2 * 2) == ik) // if ik is even { uint16_t rover = index[ikdb2]; while (rover != 0u) { count += 1; printf("{%d, %d, %d}\n", arr[i], arr[rover], arr[k]); rover = list[rover]; } } } } printf("Count is: %d\n", count); } </code></pre> <p>and the dribble:</p> <pre><code>tmp e$ cc -o triples triples.c tmp e$ ./triples {9, 6, 3} {9, 6, 3} {2, 6, 10} {2, 6, 10} {3, 3, 3} Count is: 5 tmp e$ </code></pre>
    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. This table or related slice is empty.
    1. 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