language-agnosticcode-golfrosetta-stone

Code Golf: Lights out


The challenge

The shortest code by character count to solve the input lights out board.

The lights out board is a 2d square grid of varying size composed of two characters - . for a light that is off and * for a light that is on.

To solve the board, all "lights" have to be turned off. Toggling a light (i.e. turning off when it is on, turning on when it is off) is made 5 lights at a time - the light selected and the lights surround it in a + (plus) shape. "Selecting" the middle light will solve the board:

.*.
***
.*.

Since Lights Out! solution order does not matter, the output will be a new board with markings on what bulbs to select. The above board's solution is

...
.X.
...

Turning off a light in a corner where there are no side bulbs to turn off will not overflow:

...
..*
.**

Selecting the lower-right bulb will only turn off 3 bulbs in this case.

Test cases

Input:
    **.**
    *.*.*
    .***.
    *.*.*
    **.**
Output:
    X...X
    .....
    ..X..
    .....
    X...X

Input:
    .*.*.
    **.**
    .*.*.
    *.*.*
    *.*.*
Output:
    .....
    .X.X.
    .....
    .....
    X.X.X

Input:
    *...*
    **.**
    ..*..
    *.*..
    *.**.
Output:
    X.X.X
    ..X.. 
    .....
    .....
    X.X..

Code count includes input/output (i.e full program).


Solution

  • Perl, 172 characters

    Perl, 333 251 203 197 190 172 characters. In this version, we randomly push buttons until all of the lights are out.

      map{$N++;$E+=/\*/*1<<$t++for/./g}<>;
      $C^=$b=1<<($%=rand$t),
      $E^=$b|$b>>$N|($%<$t-$N)*$b<<$N|($%%$N&&$b/2)|(++$%%$N&&$b*2)while$E;
      die map{('.',X)[1&$C>>$_-1],$_%$N?"":$/}1..$t