how does the regex engine not choose a free square in d4 when looking
for free squares in d3?
I do not know what you mean by this. Do you mean "why doesn't the
regex engine never try to place a queen on both d4 and d3?" In that
case, the answer is simple - it will never even attempt to place two
queens on the same column. The first part of the string is:
is being matched against the first part of the regex:
The newlines in the string and regex are significant here (. won't match
a newline). This part will make \1 one of 'a1' .. 'a8', \2 one of 'b1' ..
'b8', \3 one of 'c1' .. 'c8', etc. So, it will never try to place two
queens on the 'd' column.
But you may ask, "why doesn't it put a queen on d3 and one on e4?". That's
where the second part of the string and regex come in. \4 contains the
position of the queen on the d column, so, in this case, \4 equals 'd3'.
Then there's this line in the second part of the regex:
We know that \4 equals 'd3', so part of this lines read '\nd3:'. Looking
back at the second part of the string, there is only one line that starts
If you look carefully, after the colon are all the fields that aren't
attacked by a queen on d3. Specifically, the field 'e4' is missing.
But the line
is saying "match a line that starts with 'd3', and has after the colon
a list of fields that include the positions of all other 7 queens".
just skips enough lines to get to the next