Find the lights which are turn on.

See the interview question from other site, that I'd like to implement by AWK.

The rules are:

There are 100 lamps, number from 1 to 100. Initially, all of them are returned off.
First time, if the number of lamp is multiple by one, switch the lamp status; that's mean, if it turn off, turn it on, vice versa.
Second time, if the number of lamp is multiple by two, switch the lamp status;
Third time, if the number of lamp is multiple by three, switch the lamp status;
And so on, until find out the number of lamp is multiples of 100, switch the lamp status;

Finally list all number of lamps which turn on.

I write the code, but seems the var in Function is not public var. array a 's value can't be used outside of function.

$ Cat my.awk

function s(n) {for (i=1;i<=100;i++) {a=(a%n)?a:-a}}
BEGIN{for (i=1;i<=100;i++) a=1}
{for (i=1;i<=100;i++) s(i)}
END {for (i=1;i<=100;i++) {if (a=="-1") print i, a} }'

How can I fix it?

Something like this?

awk '
BEGIN {
for(nL=1;nL<=100;nL++) 
   for(nS=1;nS<=100;nS++) 
      if  ( ! nL % nS ) a[nL]=a[nL]?0:1
for(nL=1;nL<=100;nL++)
   if ( a[nL] ) {print "Lamp:  "nL" --> Encendida"} 
}'
Lamp:  1 --> Encendida
Lamp:  4 --> Encendida
Lamp:  9 --> Encendida
Lamp:  16 --> Encendida
Lamp:  25 --> Encendida
Lamp:  36 --> Encendida
Lamp:  49 --> Encendida
Lamp:  64 --> Encendida
Lamp:  81 --> Encendida
Lamp:  100 --> Encendida
1 Like

I don't know the answer, but it is interesting, your results are some regular numbers, all of them are square numbers.

When I run your code in my system, I don't get any output. Try to understand your idea first.

Klashxx's result is correct. However, a more efficient way of calculating the result would be:

awk -v n=100 'BEGIN {while ((j=++i^2) <= n) print j}'

:wink:

If you think about the problem (forget about the code, just think about the math), every single time that a lamp's id number is divisible by a number x, there will be another number, y, less than or equal to the number of lamps, by which it will also be divisible. So, for each x that toggles the lamp's state, there is a y which will undo its effect ... except when x=y, a square root.

Regards,
Alister

1 Like

Very , very smart Alister !!