Last active
November 26, 2023 07:55
-
-
Save oguz-ismail/ce4fdd52ffdf3ee25614f5aa1e6a57b1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
BEGIN { | |
FS = " |," | |
} | |
{ | |
if (/toggle/) { | |
x1 = $2; y1 = $3 | |
x2 = $5; y2 = $6 | |
} | |
else { | |
x1 = $3; y1 = $4 | |
x2 = $6; y2 = $7 | |
} | |
if (NR % 2) { | |
delete lit1 | |
sub_from_each(lit2, x1, y1, x2, y2, lit1) | |
} | |
else { | |
delete lit2 | |
sub_from_each(lit1, x1, y1, x2, y2, lit2) | |
} | |
} | |
/turn on/ { | |
if (NR % 2) | |
lit1[x1, y1, x2, y2] | |
else | |
lit2[x1, y1, x2, y2] | |
} | |
/toggle/ { | |
if (NR % 2) | |
sub_each(lit2, x1, y1, x2, y2, lit1) | |
else | |
sub_each(lit1, x1, y1, x2, y2, lit2) | |
} | |
END { | |
if (NR % 2) | |
print total_area(lit1) | |
else | |
print total_area(lit2) | |
} | |
function sub_each(src, x1, y1, x2, y2, dst, turn) { | |
delete buf1 | |
buf1[x1, y1, x2, y2] | |
for (rect in src) { | |
split(rect, xy, SUBSEP) | |
turn++ | |
if (turn % 2) { | |
delete buf2 | |
sub_from_each(buf1, xy[1], xy[2], xy[3], xy[4], buf2) | |
} | |
else { | |
delete buf1 | |
sub_from_each(buf2, xy[1], xy[2], xy[3], xy[4], buf1) | |
} | |
} | |
if (turn % 2) | |
copy(buf2, dst) | |
else | |
copy(buf1, dst) | |
} | |
function sub_from_each(src, x1, y1, x2, y2, dst) { | |
for (rect in src) { | |
split(rect, xy, SUBSEP) | |
subtract(xy[1], xy[2], xy[3], xy[4], x1, y1, x2, y2, dst) | |
} | |
} | |
function copy(src, dst) { | |
for (i in src) | |
dst[i] | |
} | |
function subtract(x1, y1, x2, y2, x3, y3, x4, y4, dst) { | |
if (max(x1, x3) > min(x2, x4) || max(y1, y3) > min(y2, y4)) { | |
dst[x1, y1, x2, y2] | |
return | |
} | |
if (x3 > x1 && x3 <= x2) | |
dst[x1, y1, x3-1, y2] | |
if (x4 >= x1 && x4 < x2) | |
dst[x4+1, y1, x2, y2] | |
if (y3 > y1 && y3 <= y2 && max(x1, x3) <= min(x2, x4)) | |
dst[max(x1, x3), y1, min(x2, x4), y3-1] | |
if (y4 >= y1 && y4 < y2 && max(x1, x3) <= min(x2, x4)) | |
dst[max(x1, x3), y4+1, min(x2, x4), y2] | |
} | |
function min(x, y) { | |
if (x < y) | |
return x | |
else | |
return y | |
} | |
function max(x, y) { | |
if (x > y) | |
return x | |
else | |
return y | |
} | |
function total_area(src, sum) { | |
for (rect in src) { | |
split(rect, xy, SUBSEP) | |
sum += (xy[3]-xy[1] + 1)*(xy[4]-xy[2] + 1) | |
} | |
return sum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment