Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Thanks all for your help, this is what I came up with:</p> <pre><code>public static boolean disco(boolean[] init, boolean[] target) { if (java.util.Arrays.equals(init, target)) { return true; } else { return disco(init, target, 0); } } private static boolean disco(boolean[] init, boolean[] target, int i) { if (i &gt; init.length-1) { return false; } disco(init, target, i+1); boolean t = false; if (init[i] != target[i]) { switchBulb(init, target, i); } if (java.util.Arrays.equals(init, target)) { t = true; } return t; } private static void switchBulb(boolean[] init, boolean[] target, int i) { if ( (i &gt; 1) &amp;&amp; (init[i-1] != target[i-1]) &amp;&amp; (init[i-2] != target[i-2]) ) { // If there's a series of 3 opposite-to-target bulbs, switch the middle one &amp; from both sides init[i-1] = !init[i-1]; init[i] = !init[i]; init[i-2] = !init[i-2]; } else if (i &gt; 0 &amp;&amp; i &lt; init.length-1) { // There's only 1 bulb or 2 adjacent bulbs that are opposite of target. if (i == 1 &amp;&amp; (init[0] != target[0]) ) { // First 2 bulbs are opposite of target's, so switch the 1st one. init[i-1] = !init[i-1]; init[i] = !init[i]; } else if ( (i == init.length-2) &amp;&amp; (init[i+1] != target[i+1]) ) { init[i+1] = !init[i+1]; init[i] = !init[i]; } else { init[i] = !init[i]; init[i-1] = !init[i-1]; init[i+1] = !init[i+1]; } } else { // First bulb or last bulb. init[i] = !init[i]; if (i == 0) { init[i+1] = !init[i+1]; } else { init[i-1] = !init[i-1]; } } } </code></pre> <p>I feel my use of recursion here is minimal, could be much cleaner if recursion was used properly. <strong>Any thoughts?</strong> I'm talking about the switchBulb function, it could be swapped with a little bit more sophisticated recursion logic, or am I wrong?</p> <p>As in, if you simply iterate over the bulbs one by one and compare to the target array, you won't necessary get it right for ALL combinations of bulbs (see example), so how do you mimic random bulb switching with recursion? Or is there a pattern? There must be, if not, how would it know when to stop?</p> <p>I think I got the solution, will post later if anyone's interested...</p>
    singulars
    1. This table or related slice is empty.
    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.
    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