File size: 36,890 Bytes
d5bfab8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 |
# types
from typing import (
List,
Union,
Tuple,
Any,
Container,
Callable,
FrozenSet,
Iterable
)
Boolean = bool
Integer = int
IntegerTuple = Tuple[Integer, Integer]
Numerical = Union[Integer, IntegerTuple]
IntegerSet = FrozenSet[Integer]
Grid = Tuple[Tuple[Integer]]
Cell = Tuple[Integer, IntegerTuple]
Object = FrozenSet[Cell]
Objects = FrozenSet[Object]
Indices = FrozenSet[IntegerTuple]
IndicesSet = FrozenSet[Indices]
Patch = Union[Object, Indices]
Element = Union[Object, Grid]
Piece = Union[Grid, Patch]
TupleTuple = Tuple[Tuple]
ContainerContainer = Container[Container]
# constants
ZERO = 0
ONE = 1
TWO = 2
THREE = 3
FOUR = 4
FIVE = 5
SIX = 6
SEVEN = 7
EIGHT = 8
NINE = 9
TEN = 10
F = False
T = True
NEG_ONE = -1
ORIGIN = (0, 0)
UNITY = (1, 1)
DOWN = (1, 0)
RIGHT = (0, 1)
UP = (-1, 0)
LEFT = (0, -1)
NEG_TWO = -2
NEG_UNITY = (-1, -1)
UP_RIGHT = (-1, 1)
DOWN_LEFT = (1, -1)
ZERO_BY_TWO = (0, 2)
TWO_BY_ZERO = (2, 0)
TWO_BY_TWO = (2, 2)
THREE_BY_THREE = (3, 3)
# primitives
def identity(
x: Any
) -> Any:
""" identity function """
return x
def add(
a: Numerical,
b: Numerical
) -> Numerical:
""" addition """
if isinstance(a, int) and isinstance(b, int):
return a + b
elif isinstance(a, tuple) and isinstance(b, tuple):
return (a[0] + b[0], a[1] + b[1])
elif isinstance(a, int) and isinstance(b, tuple):
return (a + b[0], a + b[1])
return (a[0] + b, a[1] + b)
def subtract(
a: Numerical,
b: Numerical
) -> Numerical:
""" subtraction """
if isinstance(a, int) and isinstance(b, int):
return a - b
elif isinstance(a, tuple) and isinstance(b, tuple):
return (a[0] - b[0], a[1] - b[1])
elif isinstance(a, int) and isinstance(b, tuple):
return (a - b[0], a - b[1])
return (a[0] - b, a[1] - b)
def multiply(
a: Numerical,
b: Numerical
) -> Numerical:
""" multiplication """
if isinstance(a, int) and isinstance(b, int):
return a * b
elif isinstance(a, tuple) and isinstance(b, tuple):
return (a[0] * b[0], a[1] * b[1])
elif isinstance(a, int) and isinstance(b, tuple):
return (a * b[0], a * b[1])
return (a[0] * b, a[1] * b)
def divide(
a: Numerical,
b: Numerical
) -> Numerical:
""" floor division """
if isinstance(a, int) and isinstance(b, int):
return a // b
elif isinstance(a, tuple) and isinstance(b, tuple):
return (a[0] // b[0], a[1] // b[1])
elif isinstance(a, int) and isinstance(b, tuple):
return (a // b[0], a // b[1])
return (a[0] // b, a[1] // b)
def invert(
n: Numerical
) -> Numerical:
""" inversion with respect to addition """
return -n if isinstance(n, int) else (-n[0], -n[1])
def even(
n: Integer
) -> Boolean:
""" evenness """
return n % 2 == 0
def double(
n: Numerical
) -> Numerical:
""" scaling by two """
return n * 2 if isinstance(n, int) else (n[0] * 2, n[1] * 2)
def halve(
n: Numerical
) -> Numerical:
""" scaling by one half """
return n // 2 if isinstance(n, int) else (n[0] // 2, n[1] // 2)
def flip(
b: Boolean
) -> Boolean:
""" logical not """
return not b
def equality(
a: Any,
b: Any
) -> Boolean:
""" equality """
return a == b
def contained(
value: Any,
container: Container
) -> Boolean:
""" element of """
return value in container
def combine(
a: Container,
b: Container
) -> Container:
""" union """
return type(a)((*a, *b))
def intersection(
a: FrozenSet,
b: FrozenSet
) -> FrozenSet:
""" returns the intersection of two containers """
return a & b
def difference(
a: Container,
b: Container
) -> Container:
""" difference """
return type(a)(e for e in a if e not in b)
def dedupe(
iterable: Tuple
) -> Tuple:
""" remove duplicates """
return tuple(e for i, e in enumerate(iterable) if iterable.index(e) == i)
def order(
container: Container,
compfunc: Callable
) -> Tuple:
""" order container by custom key """
return tuple(sorted(container, key=compfunc))
def repeat(
item: Any,
num: Integer
) -> Tuple:
""" repetition of item within vector """
return tuple(item for i in range(num))
def greater(
a: Integer,
b: Integer
) -> Boolean:
""" greater """
return a > b
def size(
container: Container
) -> Integer:
""" cardinality """
return len(container)
def merge(
containers: ContainerContainer
) -> Container:
""" merging """
return type(containers)(e for c in containers for e in c)
def maximum(
container: IntegerSet
) -> Integer:
""" maximum """
return max(container, default=0)
def minimum(
container: IntegerSet
) -> Integer:
""" minimum """
return min(container, default=0)
def valmax(
container: Container,
compfunc: Callable
) -> Integer:
""" maximum by custom function """
return compfunc(max(container, key=compfunc, default=0))
def valmin(
container: Container,
compfunc: Callable
) -> Integer:
""" minimum by custom function """
return compfunc(min(container, key=compfunc, default=0))
def argmax(
container: Container,
compfunc: Callable
) -> Any:
""" largest item by custom order """
return max(container, key=compfunc, default=None)
def argmin(
container: Container,
compfunc: Callable
) -> Any:
""" smallest item by custom order """
return min(container, key=compfunc, default=None)
def mostcommon(
container: Container
) -> Any:
""" most common item """
return max(set(container), key=container.count)
def leastcommon(
container: Container
) -> Any:
""" least common item """
return min(set(container), key=container.count)
def initset(
value: Any
) -> FrozenSet:
""" initialize container """
return frozenset({value})
def both(
a: Boolean,
b: Boolean
) -> Boolean:
""" logical and """
return a and b
def either(
a: Boolean,
b: Boolean
) -> Boolean:
""" logical or """
return a or b
def increment(
x: Numerical
) -> Numerical:
""" incrementing """
return x + 1 if isinstance(x, int) else (x[0] + 1, x[1] + 1)
def decrement(
x: Numerical
) -> Numerical:
""" decrementing """
return x - 1 if isinstance(x, int) else (x[0] - 1, x[1] - 1)
def crement(
x: Numerical
) -> Numerical:
""" incrementing positive and decrementing negative """
if isinstance(x, int):
return 0 if x == 0 else (x + 1 if x > 0 else x - 1)
return (
0 if x[0] == 0 else (x[0] + 1 if x[0] > 0 else x[0] - 1),
0 if x[1] == 0 else (x[1] + 1 if x[1] > 0 else x[1] - 1)
)
def sign(
x: Numerical
) -> Numerical:
""" sign """
if isinstance(x, int):
return 0 if x == 0 else (1 if x > 0 else -1)
return (
0 if x[0] == 0 else (1 if x[0] > 0 else -1),
0 if x[1] == 0 else (1 if x[1] > 0 else -1)
)
def positive(
x: Integer
) -> Boolean:
""" positive """
return x > 0
def toivec(
i: Integer
) -> IntegerTuple:
""" vector pointing vertically """
return (i, 0)
def tojvec(
j: Integer
) -> IntegerTuple:
""" vector pointing horizontally """
return (0, j)
def sfilter(
container: Container,
condition: Callable
) -> Container:
""" keep elements in container that satisfy condition """
return type(container)(e for e in container if condition(e))
def mfilter(
container: Container,
function: Callable
) -> FrozenSet:
""" filter and merge """
return merge(sfilter(container, function))
def extract(
container: Container,
condition: Callable
) -> Any:
""" first element of container that satisfies condition """
return next(e for e in container if condition(e))
def totuple(
container: FrozenSet
) -> Tuple:
""" conversion to tuple """
return tuple(container)
def first(
container: Container
) -> Any:
""" first item of container """
return next(iter(container))
def last(
container: Container
) -> Any:
""" last item of container """
return max(enumerate(container))[1]
def insert(
value: Any,
container: FrozenSet
) -> FrozenSet:
""" insert item into container """
return container.union(frozenset({value}))
def remove(
value: Any,
container: Container
) -> Container:
""" remove item from container """
return type(container)(e for e in container if e != value)
def other(
container: Container,
value: Any
) -> Any:
""" other value in the container """
return first(remove(value, container))
def interval(
start: Integer,
stop: Integer,
step: Integer
) -> Tuple:
""" range """
return tuple(range(start, stop, step))
def astuple(
a: Integer,
b: Integer
) -> IntegerTuple:
""" constructs a tuple """
return (a, b)
def product(
a: Container,
b: Container
) -> FrozenSet:
""" cartesian product """
return frozenset((i, j) for j in b for i in a)
def pair(
a: Tuple,
b: Tuple
) -> TupleTuple:
""" zipping of two tuples """
return tuple(zip(a, b))
def branch(
condition: Boolean,
if_value: Any,
else_value: Any
) -> Any:
""" if else branching """
return if_value if condition else else_value
def compose(
outer: Callable,
inner: Callable
) -> Callable:
""" function composition """
return lambda x: outer(inner(x))
def chain(
h: Callable,
g: Callable,
f: Callable
) -> Callable:
""" function composition with three functions """
return lambda x: h(g(f(x)))
def matcher(
function: Callable,
target: Any
) -> Callable:
""" construction of equality function """
return lambda x: function(x) == target
def rbind(
function: Callable,
fixed: Any
) -> Callable:
""" fix the rightmost argument """
n = function.__code__.co_argcount
if n == 2:
return lambda x: function(x, fixed)
elif n == 3:
return lambda x, y: function(x, y, fixed)
else:
return lambda x, y, z: function(x, y, z, fixed)
def lbind(
function: Callable,
fixed: Any
) -> Callable:
""" fix the leftmost argument """
n = function.__code__.co_argcount
if n == 2:
return lambda y: function(fixed, y)
elif n == 3:
return lambda y, z: function(fixed, y, z)
else:
return lambda y, z, a: function(fixed, y, z, a)
def power(
function: Callable,
n: Integer
) -> Callable:
""" power of function """
if n == 1:
return function
return compose(function, power(function, n - 1))
def fork(
outer: Callable,
a: Callable,
b: Callable
) -> Callable:
""" creates a wrapper function """
return lambda x: outer(a(x), b(x))
def apply(
function: Callable,
container: Container
) -> Container:
""" apply function to each item in container """
return type(container)(function(e) for e in container)
def rapply(
functions: Container,
value: Any
) -> Container:
""" apply each function in container to value """
return type(functions)(function(value) for function in functions)
def mapply(
function: Callable,
container: ContainerContainer
) -> FrozenSet:
""" apply and merge """
return merge(apply(function, container))
def papply(
function: Callable,
a: Tuple,
b: Tuple
) -> Tuple:
""" apply function on two vectors """
return tuple(function(i, j) for i, j in zip(a, b))
def mpapply(
function: Callable,
a: Tuple,
b: Tuple
) -> Tuple:
""" apply function on two vectors and merge """
return merge(papply(function, a, b))
def prapply(
function: Callable,
a: Container,
b: Container
) -> FrozenSet:
""" apply function on cartesian product """
return frozenset(function(i, j) for j in b for i in a)
def mostcolor(
element: Element
) -> Integer:
""" most common color """
values = [v for r in element for v in r] if isinstance(element, tuple) else [v for v, _ in element]
return max(set(values), key=values.count)
def leastcolor(
element: Element
) -> Integer:
""" least common color """
values = [v for r in element for v in r] if isinstance(element, tuple) else [v for v, _ in element]
return min(set(values), key=values.count)
def height(
piece: Piece
) -> Integer:
""" height of grid or patch """
if len(piece) == 0:
return 0
if isinstance(piece, tuple):
return len(piece)
return lowermost(piece) - uppermost(piece) + 1
def width(
piece: Piece
) -> Integer:
""" width of grid or patch """
if len(piece) == 0:
return 0
if isinstance(piece, tuple):
return len(piece[0])
return rightmost(piece) - leftmost(piece) + 1
def shape(
piece: Piece
) -> IntegerTuple:
""" height and width of grid or patch """
return (height(piece), width(piece))
def portrait(
piece: Piece
) -> Boolean:
""" whether height is greater than width """
return height(piece) > width(piece)
def colorcount(
element: Element,
value: Integer
) -> Integer:
""" number of cells with color """
if isinstance(element, tuple):
return sum(row.count(value) for row in element)
return sum(v == value for v, _ in element)
def colorfilter(
objs: Objects,
value: Integer
) -> Objects:
""" filter objects by color """
return frozenset(obj for obj in objs if next(iter(obj))[0] == value)
def sizefilter(
container: Container,
n: Integer
) -> FrozenSet:
""" filter items by size """
return frozenset(item for item in container if len(item) == n)
def asindices(
grid: Grid
) -> Indices:
""" indices of all grid cells """
return frozenset((i, j) for i in range(len(grid)) for j in range(len(grid[0])))
def ofcolor(
grid: Grid,
value: Integer
) -> Indices:
""" indices of all grid cells with value """
return frozenset((i, j) for i, r in enumerate(grid) for j, v in enumerate(r) if v == value)
def ulcorner(
patch: Patch
) -> IntegerTuple:
""" index of upper left corner """
return tuple(map(min, zip(*toindices(patch))))
def urcorner(
patch: Patch
) -> IntegerTuple:
""" index of upper right corner """
return tuple(map(lambda ix: {0: min, 1: max}[ix[0]](ix[1]), enumerate(zip(*toindices(patch)))))
def llcorner(
patch: Patch
) -> IntegerTuple:
""" index of lower left corner """
return tuple(map(lambda ix: {0: max, 1: min}[ix[0]](ix[1]), enumerate(zip(*toindices(patch)))))
def lrcorner(
patch: Patch
) -> IntegerTuple:
""" index of lower right corner """
return tuple(map(max, zip(*toindices(patch))))
def crop(
grid: Grid,
start: IntegerTuple,
dims: IntegerTuple
) -> Grid:
""" subgrid specified by start and dimension """
return tuple(r[start[1]:start[1]+dims[1]] for r in grid[start[0]:start[0]+dims[0]])
def toindices(
patch: Patch
) -> Indices:
""" indices of object cells """
if len(patch) == 0:
return frozenset()
if isinstance(next(iter(patch))[1], tuple):
return frozenset(index for value, index in patch)
return patch
def recolor(
value: Integer,
patch: Patch
) -> Object:
""" recolor patch """
return frozenset((value, index) for index in toindices(patch))
def shift(
patch: Patch,
directions: IntegerTuple
) -> Patch:
""" shift patch """
if len(patch) == 0:
return patch
di, dj = directions
if isinstance(next(iter(patch))[1], tuple):
return frozenset((value, (i + di, j + dj)) for value, (i, j) in patch)
return frozenset((i + di, j + dj) for i, j in patch)
def normalize(
patch: Patch
) -> Patch:
""" moves upper left corner to origin """
if len(patch) == 0:
return patch
return shift(patch, (-uppermost(patch), -leftmost(patch)))
def dneighbors(
loc: IntegerTuple
) -> Indices:
""" directly adjacent indices """
return frozenset({(loc[0] - 1, loc[1]), (loc[0] + 1, loc[1]), (loc[0], loc[1] - 1), (loc[0], loc[1] + 1)})
def ineighbors(
loc: IntegerTuple
) -> Indices:
""" diagonally adjacent indices """
return frozenset({(loc[0] - 1, loc[1] - 1), (loc[0] - 1, loc[1] + 1), (loc[0] + 1, loc[1] - 1), (loc[0] + 1, loc[1] + 1)})
def neighbors(
loc: IntegerTuple
) -> Indices:
""" adjacent indices """
return dneighbors(loc) | ineighbors(loc)
def objects(
grid: Grid,
univalued: Boolean,
diagonal: Boolean,
without_bg: Boolean
) -> Objects:
""" objects occurring on the grid """
bg = mostcolor(grid) if without_bg else None
objs = set()
occupied = set()
h, w = len(grid), len(grid[0])
unvisited = asindices(grid)
diagfun = neighbors if diagonal else dneighbors
for loc in unvisited:
if loc in occupied:
continue
val = grid[loc[0]][loc[1]]
if val == bg:
continue
obj = {(val, loc)}
cands = {loc}
while len(cands) > 0:
neighborhood = set()
for cand in cands:
v = grid[cand[0]][cand[1]]
if (val == v) if univalued else (v != bg):
obj.add((v, cand))
occupied.add(cand)
neighborhood |= {
(i, j) for i, j in diagfun(cand) if 0 <= i < h and 0 <= j < w
}
cands = neighborhood - occupied
objs.add(frozenset(obj))
return frozenset(objs)
def partition(
grid: Grid
) -> Objects:
""" each cell with the same value part of the same object """
return frozenset(
frozenset(
(v, (i, j)) for i, r in enumerate(grid) for j, v in enumerate(r) if v == value
) for value in palette(grid)
)
def fgpartition(
grid: Grid
) -> Objects:
""" each cell with the same value part of the same object without background """
return frozenset(
frozenset(
(v, (i, j)) for i, r in enumerate(grid) for j, v in enumerate(r) if v == value
) for value in palette(grid) - {mostcolor(grid)}
)
def uppermost(
patch: Patch
) -> Integer:
""" row index of uppermost occupied cell """
return min(i for i, j in toindices(patch))
def lowermost(
patch: Patch
) -> Integer:
""" row index of lowermost occupied cell """
return max(i for i, j in toindices(patch))
def leftmost(
patch: Patch
) -> Integer:
""" column index of leftmost occupied cell """
return min(j for i, j in toindices(patch))
def rightmost(
patch: Patch
) -> Integer:
""" column index of rightmost occupied cell """
return max(j for i, j in toindices(patch))
def square(
piece: Piece
) -> Boolean:
""" whether the piece forms a square """
return len(piece) == len(piece[0]) if isinstance(piece, tuple) else height(piece) * width(piece) == len(piece) and height(piece) == width(piece)
def vline(
patch: Patch
) -> Boolean:
""" whether the piece forms a vertical line """
return height(patch) == len(patch) and width(patch) == 1
def hline(
patch: Patch
) -> Boolean:
""" whether the piece forms a horizontal line """
return width(patch) == len(patch) and height(patch) == 1
def hmatching(
a: Patch,
b: Patch
) -> Boolean:
""" whether there exists a row for which both patches have cells """
return len(set(i for i, j in toindices(a)) & set(i for i, j in toindices(b))) > 0
def vmatching(
a: Patch,
b: Patch
) -> Boolean:
""" whether there exists a column for which both patches have cells """
return len(set(j for i, j in toindices(a)) & set(j for i, j in toindices(b))) > 0
def manhattan(
a: Patch,
b: Patch
) -> Integer:
""" closest manhattan distance between two patches """
return min(abs(ai - bi) + abs(aj - bj) for ai, aj in toindices(a) for bi, bj in toindices(b))
def adjacent(
a: Patch,
b: Patch
) -> Boolean:
""" whether two patches are adjacent """
return manhattan(a, b) == 1
def bordering(
patch: Patch,
grid: Grid
) -> Boolean:
""" whether a patch is adjacent to a grid border """
return uppermost(patch) == 0 or leftmost(patch) == 0 or lowermost(patch) == len(grid) - 1 or rightmost(patch) == len(grid[0]) - 1
def centerofmass(
patch: Patch
) -> IntegerTuple:
""" center of mass """
return tuple(map(lambda x: sum(x) // len(patch), zip(*toindices(patch))))
def palette(
element: Element
) -> IntegerSet:
""" colors occurring in object or grid """
if isinstance(element, tuple):
return frozenset({v for r in element for v in r})
return frozenset({v for v, _ in element})
def numcolors(
element: Element
) -> IntegerSet:
""" number of colors occurring in object or grid """
return len(palette(element))
def color(
obj: Object
) -> Integer:
""" color of object """
return next(iter(obj))[0]
def toobject(
patch: Patch,
grid: Grid
) -> Object:
""" object from patch and grid """
h, w = len(grid), len(grid[0])
return frozenset((grid[i][j], (i, j)) for i, j in toindices(patch) if 0 <= i < h and 0 <= j < w)
def asobject(
grid: Grid
) -> Object:
""" conversion of grid to object """
return frozenset((v, (i, j)) for i, r in enumerate(grid) for j, v in enumerate(r))
def rot90(
grid: Grid
) -> Grid:
""" quarter clockwise rotation """
return tuple(row for row in zip(*grid[::-1]))
def rot180(
grid: Grid
) -> Grid:
""" half rotation """
return tuple(tuple(row[::-1]) for row in grid[::-1])
def rot270(
grid: Grid
) -> Grid:
""" quarter anticlockwise rotation """
return tuple(tuple(row[::-1]) for row in zip(*grid[::-1]))[::-1]
def hmirror(
piece: Piece
) -> Piece:
""" mirroring along horizontal """
if isinstance(piece, tuple):
return piece[::-1]
d = ulcorner(piece)[0] + lrcorner(piece)[0]
if isinstance(next(iter(piece))[1], tuple):
return frozenset((v, (d - i, j)) for v, (i, j) in piece)
return frozenset((d - i, j) for i, j in piece)
def vmirror(
piece: Piece
) -> Piece:
""" mirroring along vertical """
if isinstance(piece, tuple):
return tuple(row[::-1] for row in piece)
d = ulcorner(piece)[1] + lrcorner(piece)[1]
if isinstance(next(iter(piece))[1], tuple):
return frozenset((v, (i, d - j)) for v, (i, j) in piece)
return frozenset((i, d - j) for i, j in piece)
def dmirror(
piece: Piece
) -> Piece:
""" mirroring along diagonal """
if isinstance(piece, tuple):
return tuple(zip(*piece))
a, b = ulcorner(piece)
if isinstance(next(iter(piece))[1], tuple):
return frozenset((v, (j - b + a, i - a + b)) for v, (i, j) in piece)
return frozenset((j - b + a, i - a + b) for i, j in piece)
def cmirror(
piece: Piece
) -> Piece:
""" mirroring along counterdiagonal """
if isinstance(piece, tuple):
return tuple(zip(*(r[::-1] for r in piece[::-1])))
return vmirror(dmirror(vmirror(piece)))
def fill(
grid: Grid,
value: Integer,
patch: Patch
) -> Grid:
""" fill value at indices """
h, w = len(grid), len(grid[0])
grid_filled = list(list(row) for row in grid)
for i, j in toindices(patch):
if 0 <= i < h and 0 <= j < w:
grid_filled[i][j] = value
return tuple(tuple(row) for row in grid_filled)
def paint(
grid: Grid,
obj: Object
) -> Grid:
""" paint object to grid """
h, w = len(grid), len(grid[0])
grid_painted = list(list(row) for row in grid)
for value, (i, j) in obj:
if 0 <= i < h and 0 <= j < w:
grid_painted[i][j] = value
return tuple(tuple(row) for row in grid_painted)
def underfill(
grid: Grid,
value: Integer,
patch: Patch
) -> Grid:
""" fill value at indices that are background """
h, w = len(grid), len(grid[0])
bg = mostcolor(grid)
grid_filled = list(list(row) for row in grid)
for i, j in toindices(patch):
if 0 <= i < h and 0 <= j < w:
if grid_filled[i][j] == bg:
grid_filled[i][j] = value
return tuple(tuple(row) for row in grid_filled)
def underpaint(
grid: Grid,
obj: Object
) -> Grid:
""" paint object to grid where there is background """
h, w = len(grid), len(grid[0])
bg = mostcolor(grid)
grid_painted = list(list(row) for row in grid)
for value, (i, j) in obj:
if 0 <= i < h and 0 <= j < w:
if grid_painted[i][j] == bg:
grid_painted[i][j] = value
return tuple(tuple(row) for row in grid_painted)
def hupscale(
grid: Grid,
factor: Integer
) -> Grid:
""" upscale grid horizontally """
upscaled_grid = tuple()
for row in grid:
upscaled_row = tuple()
for value in row:
upscaled_row = upscaled_row + tuple(value for num in range(factor))
upscaled_grid = upscaled_grid + (upscaled_row,)
return upscaled_grid
def vupscale(
grid: Grid,
factor: Integer
) -> Grid:
""" upscale grid vertically """
upscaled_grid = tuple()
for row in grid:
upscaled_grid = upscaled_grid + tuple(row for num in range(factor))
return upscaled_grid
def upscale(
element: Element,
factor: Integer
) -> Element:
""" upscale object or grid """
if isinstance(element, tuple):
upscaled_grid = tuple()
for row in element:
upscaled_row = tuple()
for value in row:
upscaled_row = upscaled_row + tuple(value for num in range(factor))
upscaled_grid = upscaled_grid + tuple(upscaled_row for num in range(factor))
return upscaled_grid
else:
if len(element) == 0:
return frozenset()
di_inv, dj_inv = ulcorner(element)
di, dj = (-di_inv, -dj_inv)
normed_obj = shift(element, (di, dj))
upscaled_obj = set()
for value, (i, j) in normed_obj:
for io in range(factor):
for jo in range(factor):
upscaled_obj.add((value, (i * factor + io, j * factor + jo)))
return shift(frozenset(upscaled_obj), (di_inv, dj_inv))
def downscale(
grid: Grid,
factor: Integer
) -> Grid:
""" downscale grid """
h, w = len(grid), len(grid[0])
downscaled_grid = tuple()
for i in range(h):
downscaled_row = tuple()
for j in range(w):
if j % factor == 0:
downscaled_row = downscaled_row + (grid[i][j],)
downscaled_grid = downscaled_grid + (downscaled_row, )
h = len(downscaled_grid)
downscaled_grid2 = tuple()
for i in range(h):
if i % factor == 0:
downscaled_grid2 = downscaled_grid2 + (downscaled_grid[i],)
return downscaled_grid2
def hconcat(
a: Grid,
b: Grid
) -> Grid:
""" concatenate two grids horizontally """
return tuple(i + j for i, j in zip(a, b))
def vconcat(
a: Grid,
b: Grid
) -> Grid:
""" concatenate two grids vertically """
return a + b
def subgrid(
patch: Patch,
grid: Grid
) -> Grid:
""" smallest subgrid containing object """
return crop(grid, ulcorner(patch), shape(patch))
def hsplit(
grid: Grid,
n: Integer
) -> Tuple:
""" split grid horizontally """
h, w = len(grid), len(grid[0]) // n
offset = len(grid[0]) % n != 0
return tuple(crop(grid, (0, w * i + i * offset), (h, w)) for i in range(n))
def vsplit(
grid: Grid,
n: Integer
) -> Tuple:
""" split grid vertically """
h, w = len(grid) // n, len(grid[0])
offset = len(grid) % n != 0
return tuple(crop(grid, (h * i + i * offset, 0), (h, w)) for i in range(n))
def cellwise(
a: Grid,
b: Grid,
fallback: Integer
) -> Grid:
""" cellwise match of two grids """
h, w = len(a), len(a[0])
resulting_grid = tuple()
for i in range(h):
row = tuple()
for j in range(w):
a_value = a[i][j]
value = a_value if a_value == b[i][j] else fallback
row = row + (value,)
resulting_grid = resulting_grid + (row, )
return resulting_grid
def replace(
grid: Grid,
replacee: Integer,
replacer: Integer
) -> Grid:
""" color substitution """
return tuple(tuple(replacer if v == replacee else v for v in r) for r in grid)
def switch(
grid: Grid,
a: Integer,
b: Integer
) -> Grid:
""" color switching """
return tuple(tuple(v if (v != a and v != b) else {a: b, b: a}[v] for v in r) for r in grid)
def center(
patch: Patch
) -> IntegerTuple:
""" center of the patch """
return (uppermost(patch) + height(patch) // 2, leftmost(patch) + width(patch) // 2)
def position(
a: Patch,
b: Patch
) -> IntegerTuple:
""" relative position between two patches """
ia, ja = center(toindices(a))
ib, jb = center(toindices(b))
if ia == ib:
return (0, 1 if ja < jb else -1)
elif ja == jb:
return (1 if ia < ib else -1, 0)
elif ia < ib:
return (1, 1 if ja < jb else -1)
elif ia > ib:
return (-1, 1 if ja < jb else -1)
def index(
grid: Grid,
loc: IntegerTuple
) -> Integer:
""" color at location """
i, j = loc
h, w = len(grid), len(grid[0])
if not (0 <= i < h and 0 <= j < w):
return None
return grid[loc[0]][loc[1]]
def canvas(
value: Integer,
dimensions: IntegerTuple
) -> Grid:
""" grid construction """
return tuple(tuple(value for j in range(dimensions[1])) for i in range(dimensions[0]))
def corners(
patch: Patch
) -> Indices:
""" indices of corners """
return frozenset({ulcorner(patch), urcorner(patch), llcorner(patch), lrcorner(patch)})
def connect(
a: IntegerTuple,
b: IntegerTuple
) -> Indices:
""" line between two points """
ai, aj = a
bi, bj = b
si = min(ai, bi)
ei = max(ai, bi) + 1
sj = min(aj, bj)
ej = max(aj, bj) + 1
if ai == bi:
return frozenset((ai, j) for j in range(sj, ej))
elif aj == bj:
return frozenset((i, aj) for i in range(si, ei))
elif bi - ai == bj - aj:
return frozenset((i, j) for i, j in zip(range(si, ei), range(sj, ej)))
elif bi - ai == aj - bj:
return frozenset((i, j) for i, j in zip(range(si, ei), range(ej - 1, sj - 1, -1)))
return frozenset()
def cover(
grid: Grid,
patch: Patch
) -> Grid:
""" remove object from grid """
return fill(grid, mostcolor(grid), toindices(patch))
def trim(
grid: Grid
) -> Grid:
""" trim border of grid """
return tuple(r[1:-1] for r in grid[1:-1])
def move(
grid: Grid,
obj: Object,
offset: IntegerTuple
) -> Grid:
""" move object on grid """
return paint(cover(grid, obj), shift(obj, offset))
def tophalf(
grid: Grid
) -> Grid:
""" upper half of grid """
return grid[:len(grid) // 2]
def bottomhalf(
grid: Grid
) -> Grid:
""" lower half of grid """
return grid[len(grid) // 2 + len(grid) % 2:]
def lefthalf(
grid: Grid
) -> Grid:
""" left half of grid """
return rot270(tophalf(rot90(grid)))
def righthalf(
grid: Grid
) -> Grid:
""" right half of grid """
return rot270(bottomhalf(rot90(grid)))
def vfrontier(
location: IntegerTuple
) -> Indices:
""" vertical frontier """
return frozenset((i, location[1]) for i in range(30))
def hfrontier(
location: IntegerTuple
) -> Indices:
""" horizontal frontier """
return frozenset((location[0], j) for j in range(30))
def backdrop(
patch: Patch
) -> Indices:
""" indices in bounding box of patch """
if len(patch) == 0:
return frozenset({})
indices = toindices(patch)
si, sj = ulcorner(indices)
ei, ej = lrcorner(patch)
return frozenset((i, j) for i in range(si, ei + 1) for j in range(sj, ej + 1))
def delta(
patch: Patch
) -> Indices:
""" indices in bounding box but not part of patch """
if len(patch) == 0:
return frozenset({})
return backdrop(patch) - toindices(patch)
def gravitate(
source: Patch,
destination: Patch
) -> IntegerTuple:
""" direction to move source until adjacent to destination """
source_i, source_j = center(source)
destination_i, destination_j = center(destination)
i, j = 0, 0
if vmatching(source, destination):
i = 1 if source_i < destination_i else -1
else:
j = 1 if source_j < destination_j else -1
direction = (i, j)
gravitation_i, gravitation_j = i, j
maxcount = 42
c = 0
while not adjacent(source, destination) and c < maxcount:
c += 1
gravitation_i += i
gravitation_j += j
source = shift(source, direction)
return (gravitation_i - i, gravitation_j - j)
def inbox(
patch: Patch
) -> Indices:
""" inbox for patch """
ai, aj = uppermost(patch) + 1, leftmost(patch) + 1
bi, bj = lowermost(patch) - 1, rightmost(patch) - 1
si, sj = min(ai, bi), min(aj, bj)
ei, ej = max(ai, bi), max(aj, bj)
vlines = {(i, sj) for i in range(si, ei + 1)} | {(i, ej) for i in range(si, ei + 1)}
hlines = {(si, j) for j in range(sj, ej + 1)} | {(ei, j) for j in range(sj, ej + 1)}
return frozenset(vlines | hlines)
def outbox(
patch: Patch
) -> Indices:
""" outbox for patch """
ai, aj = uppermost(patch) - 1, leftmost(patch) - 1
bi, bj = lowermost(patch) + 1, rightmost(patch) + 1
si, sj = min(ai, bi), min(aj, bj)
ei, ej = max(ai, bi), max(aj, bj)
vlines = {(i, sj) for i in range(si, ei + 1)} | {(i, ej) for i in range(si, ei + 1)}
hlines = {(si, j) for j in range(sj, ej + 1)} | {(ei, j) for j in range(sj, ej + 1)}
return frozenset(vlines | hlines)
def box(
patch: Patch
) -> Indices:
""" outline of patch """
if len(patch) == 0:
return patch
ai, aj = ulcorner(patch)
bi, bj = lrcorner(patch)
si, sj = min(ai, bi), min(aj, bj)
ei, ej = max(ai, bi), max(aj, bj)
vlines = {(i, sj) for i in range(si, ei + 1)} | {(i, ej) for i in range(si, ei + 1)}
hlines = {(si, j) for j in range(sj, ej + 1)} | {(ei, j) for j in range(sj, ej + 1)}
return frozenset(vlines | hlines)
def shoot(
start: IntegerTuple,
direction: IntegerTuple
) -> Indices:
""" line from starting point and direction """
return connect(start, (start[0] + 42 * direction[0], start[1] + 42 * direction[1]))
def occurrences(
grid: Grid,
obj: Object
) -> Indices:
""" locations of occurrences of object in grid """
occurrences = set()
normed = normalize(obj)
h, w = len(grid), len(grid[0])
for i in range(h):
for j in range(w):
occurs = True
for v, (a, b) in shift(normed, (i, j)):
if 0 <= a < h and 0 <= b < w:
if grid[a][b] != v:
occurs = False
break
else:
occurs = False
break
if occurs:
occurrences.add((i, j))
return frozenset(occurrences)
def frontiers(
grid: Grid
) -> Objects:
""" set of frontiers """
h, w = len(grid), len(grid[0])
row_indices = tuple(i for i, r in enumerate(grid) if len(set(r)) == 1)
column_indices = tuple(j for j, c in enumerate(dmirror(grid)) if len(set(c)) == 1)
hfrontiers = frozenset({frozenset({(grid[i][j], (i, j)) for j in range(w)}) for i in row_indices})
vfrontiers = frozenset({frozenset({(grid[i][j], (i, j)) for i in range(h)}) for j in column_indices})
return hfrontiers | vfrontiers
def compress(
grid: Grid
) -> Grid:
""" removes frontiers from grid """
ri = tuple(i for i, r in enumerate(grid) if len(set(r)) == 1)
ci = tuple(j for j, c in enumerate(dmirror(grid)) if len(set(c)) == 1)
return tuple(tuple(v for j, v in enumerate(r) if j not in ci) for i, r in enumerate(grid) if i not in ri)
def hperiod(
obj: Object
) -> Integer:
""" horizontal periodicity """
normalized = normalize(obj)
w = width(normalized)
for p in range(1, w):
offsetted = shift(normalized, (0, -p))
pruned = frozenset({(c, (i, j)) for c, (i, j) in offsetted if j >= 0})
if pruned.issubset(normalized):
return p
return w
def vperiod(
obj: Object
) -> Integer:
""" vertical periodicity """
normalized = normalize(obj)
h = height(normalized)
for p in range(1, h):
offsetted = shift(normalized, (-p, 0))
pruned = frozenset({(c, (i, j)) for c, (i, j) in offsetted if i >= 0})
if pruned.issubset(normalized):
return p
return h
|