Spaces:
Runtime error
Runtime error
File size: 129,859 Bytes
b144cb7 | 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 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 | Code_ID,Code_Text,Label,Source_Type,Generation_Prompt,Language,normalized_code,original_line_count,normalized_line_count
,"from dataclasses import dataclass, field, fields
class ValidationError(Exception): pass
def vfield(d=None, v=()):
return field(default=d, metadata={""v"": v})
def validate(o):
for f in fields(o):
for fn in f.metadata.get(""v"", ()):
if not fn(getattr(o, f.name)):
raise ValidationError(f""{f.name} invalid"")
@dataclass
class User:
name: str
age: int = vfield(0, v=[lambda x: 0 <= x <= 150])
email: str = vfield("""", v=[lambda x: ""@"" in x])
# ---------- INPUT ----------
u = User(""Arsen"", 30, ""arsen@example.com"")
# ---------- OUTPUT ----------
try:
validate(u)
print(""User is valid"")
except ValidationError as e:
print(e)
",1.0,GPT,write a shorter python code for Data Validation Library with Dataclasses including I/O,python,"from dataclasses import dataclass, field, fields
class ValidationError(Exception): pass
def vfield(d=None, v=()):
return field(default=d, metadata={""v"": v})
def validate(o):
for f in fields(o):
for fn in f.metadata.get(""v"", ()):
if not fn(getattr(o, f.name)):
raise ValidationError(f""{f.name} invalid"")
@dataclass
class User:
name: str
age: int = vfield(0, v=[lambda x: 0 <= x <= 150])
email: str = vfield("""", v=[lambda x: ""@"" in x])
# ---------- INPUT ----------
u = User(""Arsen"", 30, ""arsen@example.com"")
# ---------- OUTPUT ----------
try:
validate(u)
print(""User is valid"")
except ValidationError as e:
print(e)",28,28
,"class Solution:
def generateParenthesis(self, n):
res = [[] for _ in range(n+1)]
res[0] = [""""]
for k in range(n + 1):
for i in range(k):
for left in res[i]:
for right in res[k-i-1]:
res[k].append(""("" + left + "")"" + right)
return res[-1]",0.0,GFG,,python,"class Solution:
def generateParenthesis(self, n):
res = [[] for _ in range(n+1)]
res[0] = [""""]
for k in range(n + 1):
for i in range(k):
for left in res[i]:
for right in res[k-i-1]:
res[k].append(""("" + left + "")"" + right)
return res[-1]",12,12
,"public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}",1.0,GEMINI,write a program to Implement a thread-safe Singleton that prevents unnecessary synchronization.,java,"public class Singleton {
private static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) instance = new Singleton();
}
}
return instance;
}
}",11,11
,"import numpy as np
arr = np.array([3+4j, 1+7j, 3+2j, 2+5j, 1+2j])
# Use lexsort with imaginary part as the first key, real part as the second
sorted_indices = np.lexsort((np.imag(arr), np.real(arr)))
sorted_arr = arr[sorted_indices]
print(""Sorted array:"", sorted_arr)",1.0,DEEPAI,"Write a NumPy program to sort a given complex array using the real part first, then the imaginary part.",python,"import numpy as np
arr = np.array([3+4j, 1+7j, 3+2j, 2+5j, 1+2j])
# Use lexsort with imaginary part as the first key, real part as the second
sorted_indices = np.lexsort((np.imag(arr), np.real(arr)))
sorted_arr = arr[sorted_indices]
print(""Sorted array:"", sorted_arr)",8,8
,"public class FactorialDP {
public static long factorial(int n) {
if (n <= 1) return 1;
long[] dp = new long[n + 1];
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] * i;
}
return dp[n];
}
}
",1.0,PERPLEXITY,Implement a Java dynamic programming solution to compute factorial of a large number using an array.,java,"public class FactorialDP {
public static long factorial(int n) {
if (n <= 1) return 1;
long[] dp = new long[n + 1];
dp[0] = dp[1] = 1;
for (int i = 2; i <= n; i++) {
dp[i] = dp[i - 1] * i;
}
return dp[n];
}
}",11,11
,"class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int[] v = new int[n+1];
Arrays.fill(v, -1);
for(int i = 0; i < nums.length; i++) {
v[nums[i]] = nums[i];
}
for(int i = 0; i < v.length; i++) {
if(v[i] == -1) return i;
}
return 0;
}
}
",0.0,leetcode,,java,"class Solution {
public int missingNumber(int[] nums) {
int n = nums.length;
int[] v = new int[n+1];
Arrays.fill(v, -1);
for(int i = 0; i < nums.length; i++) {
v[nums[i]] = nums[i];
}
for(int i = 0; i < v.length; i++) {
if(v[i] == -1) return i;
}
return 0;
}
}",14,14
,"from collections import Counter
def leastInterval(tasks, n):
count = Counter(tasks)
max_freq = max(count.values())
max_count = sum(1 for v in count.values() if v == max_freq)
return max(len(tasks), (max_freq - 1) * (n + 1) + max_count)
",1.0,GPT,"Solve the problem ""Task Scheduler"".
Given a list of tasks and a cooldown n,
return the least number of units of time needed to finish all tasks
with cooldown constraints.
",python,"from collections import Counter
def leastInterval(tasks, n):
count = Counter(tasks)
max_freq = max(count.values())
max_count = sum(1 for v in count.values() if v == max_freq)
return max(len(tasks), (max_freq - 1) * (n + 1) + max_count)",8,8
,"# Define a function named 'printValues' that generates a list of squares of numbers from 1 to 20
def printValues():
# Create an empty list 'l'
l = list()
# Iterate through numbers from 1 to 20 (inclusive)
for i in range(1, 21):
# Calculate the square of 'i' and append it to the list 'l'
l.append(i**2)
# Print the list containing squares of numbers from 1 to 20
print(l)
# Call the 'printValues' function to generate and print the list of squares
printValues() ",0.0,W3RESOURCE,,python,"# Define a function named 'printValues' that generates a list of squares of numbers from 1 to 20
def printValues():
# Create an empty list 'l'
l = list()
# Iterate through numbers from 1 to 20 (inclusive)
for i in range(1, 21):
# Calculate the square of 'i' and append it to the list 'l'
l.append(i**2)
# Print the list containing squares of numbers from 1 to 20
print(l)
# Call the 'printValues' function to generate and print the list of squares
printValues() ",15,15
,"def setZeroes(matrix):
rows, cols = len(matrix), len(matrix[0])
row_zero = any(matrix[0][c] == 0 for c in range(cols))
col_zero = any(matrix[r][0] == 0 for r in range(rows))
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][c] == 0:
matrix[r][0] = matrix[0][c] = 0
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][0] == 0 or matrix[0][c] == 0:
matrix[r][c] = 0
if row_zero:
for c in range(cols):
matrix[0][c] = 0
if col_zero:
for r in range(rows):
matrix[r][0] = 0
",1.0,GPT,"Solve the problem ""Set Matrix Zeroes"".
Given an m x n matrix,
if an element is 0, set its entire row and column to 0.
Do it in-place with constant extra space.
Provide Python solution.
",python,"def setZeroes(matrix):
rows, cols = len(matrix), len(matrix[0])
row_zero = any(matrix[0][c] == 0 for c in range(cols))
col_zero = any(matrix[r][0] == 0 for r in range(rows))
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][c] == 0:
matrix[r][0] = matrix[0][c] = 0
for r in range(1, rows):
for c in range(1, cols):
if matrix[r][0] == 0 or matrix[0][c] == 0:
matrix[r][c] = 0
if row_zero:
for c in range(cols):
matrix[0][c] = 0
if col_zero:
for r in range(rows):
matrix[r][0] = 0",21,21
,"public class PalindromeChecking
{
public static void main(String[] args)
{
String inpstr =""AMMA"";
char[] inpArray = inpstr.toCharArray();
char[] revArray = new char[inpArray.length];
int j=0;
for (int i = inpArray.length - 1; i >= 0; i--) {
revArray[j]=inpArray[i];
j++;
}
String revstr=String.valueOf(revArray);
if(inpstr.equals(revstr))
{
System.out.println(""The given string is a Palindrome"");
}
else
{
System.out.println(""The given string is not a Palindrome"");
}
}
}
",0.0,IPSGWALIOR.ORG,,java,"public class PalindromeChecking
{
public static void main(String[] args)
{
String inpstr =""AMMA"";
char[] inpArray = inpstr.toCharArray();
char[] revArray = new char[inpArray.length];
int j=0;
for (int i = inpArray.length - 1; i >= 0; i--) {
revArray[j]=inpArray[i];
j++;
}
String revstr=String.valueOf(revArray);
if(inpstr.equals(revstr))
{
System.out.println(""The given string is a Palindrome"");
}
else
{
System.out.println(""The given string is not a Palindrome"");
}
}
}",23,23
,"def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-1]>currentvalue:
nlist[position]=nlist[position-1]
position = position-1
nlist[position]=currentvalue
nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)",0.0,W3RESOURCE,,python,"def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-1]>currentvalue:
nlist[position]=nlist[position-1]
position = position-1
nlist[position]=currentvalue
nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)",15,15
,"import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecution {
String value() default """";
}
public class AnnotationProcessor {
public static void process(Object obj) throws Exception {
for (java.lang.reflect.Method m : obj.getClass().getMethods()) {
if (m.isAnnotationPresent(LogExecution.class)) {
System.out.println(""Logging: "" + m.getName());
}
}
}
}
",1.0,PERPLEXITY,Create a basic custom annotation with processor stub for runtime processing,java,"import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecution {
String value() default """";
}
public class AnnotationProcessor {
public static void process(Object obj) throws Exception {
for (java.lang.reflect.Method m : obj.getClass().getMethods()) {
if (m.isAnnotationPresent(LogExecution.class)) {
System.out.println(""Logging: "" + m.getName());
}
}
}
}",15,15
,"def searchMatrix(matrix, target):
if not matrix or not matrix[0]:
return False
rows, cols = len(matrix), len(matrix[0])
l, r = 0, rows * cols - 1
while l <= r:
m = (l + r) // 2
val = matrix[m // cols][m % cols]
if val == target:
return True
elif val < target:
l = m + 1
else:
r = m - 1
return False
",1.0,GPT,"Solve the problem ""Search a 2D Matrix"".
The matrix has the following properties:
- Integers in each row are sorted
- First integer of each row is greater than the last integer of the previous row
Given a target, return true if found.
Provide O(log(m*n)) Python solution.
",python,"def searchMatrix(matrix, target):
if not matrix or not matrix[0]:
return False
rows, cols = len(matrix), len(matrix[0])
l, r = 0, rows * cols - 1
while l <= r:
m = (l + r) // 2
val = matrix[m // cols][m % cols]
if val == target:
return True
elif val < target:
l = m + 1
else:
r = m - 1
return False",18,18
,"public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode iter = head, next;
// First round: make copy of each node,
// and link them together side-by-side in a single list.
while (iter != null) {
next = iter.next;
RandomListNode copy = new RandomListNode(iter.label);
iter.next = copy;
copy.next = next;
iter = next;
}
// Second round: assign random pointers for the copy nodes.
iter = head;
while (iter != null) {
if (iter.random != null) {
iter.next.random = iter.random.next;
}
iter = iter.next.next;
}
// Third round: restore the original list, and extract the copy list.
iter = head;
RandomListNode pseudoHead = new RandomListNode(0);
RandomListNode copy, copyIter = pseudoHead;
while (iter != null) {
next = iter.next.next;
// extract the copy
copy = iter.next;
copyIter.next = copy;
copyIter = copy;
// restore the original list
iter.next = next;
iter = next;
}
return pseudoHead.next;
}",0.0,leetcode,,java,"public RandomListNode copyRandomList(RandomListNode head) {
RandomListNode iter = head, next;
// First round: make copy of each node,
// and link them together side-by-side in a single list.
while (iter != null) {
next = iter.next;
RandomListNode copy = new RandomListNode(iter.label);
iter.next = copy;
copy.next = next;
iter = next;
}
// Second round: assign random pointers for the copy nodes.
iter = head;
while (iter != null) {
if (iter.random != null) {
iter.next.random = iter.random.next;
}
iter = iter.next.next;
}
// Third round: restore the original list, and extract the copy list.
iter = head;
RandomListNode pseudoHead = new RandomListNode(0);
RandomListNode copy, copyIter = pseudoHead;
while (iter != null) {
next = iter.next.next;
// extract the copy
copy = iter.next;
copyIter.next = copy;
copyIter = copy;
// restore the original list
iter.next = next;
iter = next;
}
return pseudoHead.next;
}",45,45
,"import time
class Timer:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
return lambda *a, **k: self(obj, *a, **k)
def __call__(self, obj, *a, **k):
t = time.time()
r = self.func(obj, *a, **k)
print(f""{self.func.__name__}: {time.time()-t:.4f}s"")
return r
",1.0,GPT,"write a python code for Class-Based Decorator for Execution Time , let the code be more shorter .",python,"import time
class Timer:
def __init__(self, func):
self.func = func
def __get__(self, obj, objtype=None):
return lambda *a, **k: self(obj, *a, **k)
def __call__(self, obj, *a, **k):
t = time.time()
r = self.func(obj, *a, **k)
print(f""{self.func.__name__}: {time.time()-t:.4f}s"")
return r",14,14
,"static boolean dfs(char[][] b,int i,int j,String w,int k){
if(k==w.length()) return true;
if(i<0||j<0||i==b.length||j==b[0].length||b[i][j]!=w.charAt(k)) return false;
char t=b[i][j]; b[i][j]='#';
boolean r=dfs(b,i+1,j,w,k+1)||dfs(b,i-1,j,w,k+1)||dfs(b,i,j+1,w,k+1)||dfs(b,i,j-1,w,k+1);
b[i][j]=t; return r;
}
",1.0,GPT,give me an efficient java code to Find if word exists in grid using DFS + Trie.,java,"static boolean dfs(char[][] b,int i,int j,String w,int k){
if(k==w.length()) return true;
if(i<0||j<0||i==b.length||j==b[0].length||b[i][j]!=w.charAt(k)) return false;
char t=b[i][j]; b[i][j]='#';
boolean r=dfs(b,i+1,j,w,k+1)||dfs(b,i-1,j,w,k+1)||dfs(b,i,j+1,w,k+1)||dfs(b,i,j-1,w,k+1);
b[i][j]=t; return r;
}",7,7
,"class MagicDictionary {
Set<String> originalWords;
Map<String, Integer> extensions;
public MagicDictionary() {
originalWords = new HashSet<>();
extensions = new HashMap<>();
}
public void buildDict(String[] dictionary) {
for (String word : dictionary) {
originalWords.add(word);
char[] str = word.toCharArray();
int n = str.length;
for (int i = 0; i < n; i++) {
char temp = str[i];
str[i] = '*';
String key = new String(str);
extensions.put(key, extensions.getOrDefault(key, 0) + 1);
str[i] = temp;
}
}
}
public boolean search(String searchWord) {
char[] str = searchWord.toCharArray();
int n = str.length;
for (int i = 0; i < n; i++) {
char temp = str[i];
str[i] = '*';
String key = new String(str);
if (extensions.containsKey(key)) {
// If count >= 2, then there's definitely a different word that maps to this pattern
// If count == 1, make sure it's not the same word
if (extensions.get(key) >= 2 || !originalWords.contains(searchWord)) {
return true;
}
}
str[i] = temp;
}
return false;
}
}",0.0,leetcode,,java,"class MagicDictionary {
Set<String> originalWords;
Map<String, Integer> extensions;
public MagicDictionary() {
originalWords = new HashSet<>();
extensions = new HashMap<>();
}
public void buildDict(String[] dictionary) {
for (String word : dictionary) {
originalWords.add(word);
char[] str = word.toCharArray();
int n = str.length;
for (int i = 0; i < n; i++) {
char temp = str[i];
str[i] = '*';
String key = new String(str);
extensions.put(key, extensions.getOrDefault(key, 0) + 1);
str[i] = temp;
}
}
}
public boolean search(String searchWord) {
char[] str = searchWord.toCharArray();
int n = str.length;
for (int i = 0; i < n; i++) {
char temp = str[i];
str[i] = '*';
String key = new String(str);
if (extensions.containsKey(key)) {
// If count >= 2, then there's definitely a different word that maps to this pattern
// If count == 1, make sure it's not the same word
if (extensions.get(key) >= 2 || !originalWords.contains(searchWord)) {
return true;
}
}
str[i] = temp;
}
return false;
}
}",43,43
,"// Define the Cat class
public class Cat {
// Private instance variables
private String name;
private int age;
// Default constructor
public Cat() {
// Initialize name to ""Unknown""
this.name = ""Unknown"";
// Initialize age to 0
this.age = 0;
}
// Getter for name
public String getName() {
return name;
}
// Getter for age
public int getAge() {
return age;
}
// Main method to test the Cat class
public static void main(String[] args) {
// Create a new Cat object using the default constructor
Cat myCat = new Cat();
// Use the getter methods to access private variables
System.out.println(""Cat's Name: "" + myCat.getName());
System.out.println(""Cat's Age: "" + myCat.getAge());
}
}
",0.0,WE3RESOURCE,,java,"// Define the Cat class
public class Cat {
// Private instance variables
private String name;
private int age;
// Default constructor
public Cat() {
// Initialize name to ""Unknown""
this.name = ""Unknown"";
// Initialize age to 0
this.age = 0;
}
// Getter for name
public String getName() {
return name;
}
// Getter for age
public int getAge() {
return age;
}
// Main method to test the Cat class
public static void main(String[] args) {
// Create a new Cat object using the default constructor
Cat myCat = new Cat();
// Use the getter methods to access private variables
System.out.println(""Cat's Name: "" + myCat.getName());
System.out.println(""Cat's Age: "" + myCat.getAge());
}
}",29,29
,"from bs4 import BeautifulSoup
import requests
handle = input('Input your account name on Twitter: ')
temp = requests.get('https://twitter.com/'+handle)
bs = BeautifulSoup(temp.text,'lxml')
try:
favorite_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--favorites'})
favorite = favorite_box.find('a').find('span',{'class':'ProfileNav-value'})
print(""Number of post {} liked are {}: "".format(handle,favorite.get('data-count')))
except:
print('Account name not found...')
",0.0,WERESOURCE,,python,"from bs4 import BeautifulSoup
import requests
handle = input('Input your account name on Twitter: ')
temp = requests.get('https://twitter.com/'+handle)
bs = BeautifulSoup(temp.text,'lxml')
try:
favorite_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--favorites'})
favorite = favorite_box.find('a').find('span',{'class':'ProfileNav-value'})
print(""Number of post {} liked are {}: "".format(handle,favorite.get('data-count')))
except:
print('Account name not found...')",14,14
,"import java.util.*;
class Solution {
public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {
Map<String, Integer> evalmap = new HashMap<>();
for (int i = 0; i < evalvars.length; i++) evalmap.put(evalvars[i], evalints[i]);
List<String> tokens = tokenize(expression);
Map<List<String>, Integer> poly = parseExpression(tokens, evalmap);
List<Map.Entry<List<String>, Integer>> list = new ArrayList<>(poly.entrySet());
list.sort((a, b) -> {
if (b.getKey().size() != a.getKey().size()) return b.getKey().size() - a.getKey().size();
// lexicographic compare by joining with '*'
return String.join(""*"", a.getKey()).compareTo(String.join(""*"", b.getKey()));
});
List<String> ans = new ArrayList<>();
for (var e : list) {
int coeff = e.getValue();
if (coeff == 0) continue;
StringBuilder sb = new StringBuilder();
sb.append(coeff);
for (String v : e.getKey()) sb.append(""*"").append(v);
ans.add(sb.toString());
}
return ans;
}
private List<String> tokenize(String expr) {
List<String> tokens = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (char c : expr.toCharArray()) {
if (Character.isLetterOrDigit(c)) sb.append(c);
else {
if (sb.length() > 0) { tokens.add(sb.toString()); sb.setLength(0); }
if (c == '+' || c == '-' || c == '*' || c == '(' || c == ')') tokens.add(String.valueOf(c));
}
}
if (sb.length() > 0) tokens.add(sb.toString());
return tokens;
}
private Map<List<String>, Integer> parseExpression(List<String> tokens, Map<String, Integer> evalmap) {
Deque<Map<List<String>, Integer>> vals = new ArrayDeque<>();
Deque<String> ops = new ArrayDeque<>();
Map<String, Integer> prec = Map.of(""+"",1, ""-"",1, ""*"",2);
for (String tok : tokens) {
if (tok.equals(""("")) ops.push(tok);
else if (tok.equals("")"")) {
while (!ops.peek().equals(""("")) applyOp(vals, ops.pop());
ops.pop();
} else if (prec.containsKey(tok)) {
while (!ops.isEmpty() && prec.containsKey(ops.peek()) && prec.get(ops.peek()) >= prec.get(tok)) {
applyOp(vals, ops.pop());
}
ops.push(tok);
} else {
vals.push(parseToken(tok, evalmap));
}
}
while (!ops.isEmpty()) applyOp(vals, ops.pop());
return vals.isEmpty() ? new HashMap<>() : vals.pop();
}
private void applyOp(Deque<Map<List<String>, Integer>> vals, String op) {
Map<List<String>, Integer> b = vals.pop();
Map<List<String>, Integer> a = vals.pop();
if (op.equals(""+"")) vals.push(add(a, b));
else if (op.equals(""-"")) vals.push(sub(a, b));
else vals.push(mul(a, b));
}
private Map<List<String>, Integer> parseToken(String tok, Map<String, Integer> evalmap) {
Map<List<String>, Integer> res = new HashMap<>();
if (tok.matches(""-?\\d+"")) {
res.put(Collections.emptyList(), Integer.parseInt(tok));
} else if (evalmap.containsKey(tok)) {
res.put(Collections.emptyList(), evalmap.get(tok));
} else {
res.put(Arrays.asList(tok), 1);
}
return res;
}
private Map<List<String>, Integer> combine(Map<List<String>, Integer> m) {
Map<List<String>, Integer> res = new HashMap<>();
for (var e : m.entrySet()) {
if (e.getValue() != 0) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue());
}
res.entrySet().removeIf(kv -> kv.getValue() == 0);
return res;
}
private Map<List<String>, Integer> add(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
Map<List<String>, Integer> res = new HashMap<>(a);
for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue());
return combine(res);
}
private Map<List<String>, Integer> sub(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
Map<List<String>, Integer> res = new HashMap<>(a);
for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) - e.getValue());
return combine(res);
}
private Map<List<String>, Integer> mul(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
Map<List<String>, Integer> res = new HashMap<>();
for (var ea : a.entrySet()) {
for (var eb : b.entrySet()) {
List<String> merged = new ArrayList<>(ea.getKey());
merged.addAll(eb.getKey());
Collections.sort(merged);
res.put(merged, res.getOrDefault(merged, 0) + ea.getValue() * eb.getValue());
}
}
return combine(res);
}
}",0.0,leetcode,,java,"import java.util.*;
class Solution {
public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {
Map<String, Integer> evalmap = new HashMap<>();
for (int i = 0; i < evalvars.length; i++) evalmap.put(evalvars[i], evalints[i]);
List<String> tokens = tokenize(expression);
Map<List<String>, Integer> poly = parseExpression(tokens, evalmap);
List<Map.Entry<List<String>, Integer>> list = new ArrayList<>(poly.entrySet());
list.sort((a, b) -> {
if (b.getKey().size() != a.getKey().size()) return b.getKey().size() - a.getKey().size();
// lexicographic compare by joining with '*'
return String.join(""*"", a.getKey()).compareTo(String.join(""*"", b.getKey()));
});
List<String> ans = new ArrayList<>();
for (var e : list) {
int coeff = e.getValue();
if (coeff == 0) continue;
StringBuilder sb = new StringBuilder();
sb.append(coeff);
for (String v : e.getKey()) sb.append(""*"").append(v);
ans.add(sb.toString());
}
return ans;
}
private List<String> tokenize(String expr) {
List<String> tokens = new ArrayList<>();
StringBuilder sb = new StringBuilder();
for (char c : expr.toCharArray()) {
if (Character.isLetterOrDigit(c)) sb.append(c);
else {
if (sb.length() > 0) { tokens.add(sb.toString()); sb.setLength(0); }
if (c == '+' || c == '-' || c == '*' || c == '(' || c == ')') tokens.add(String.valueOf(c));
}
}
if (sb.length() > 0) tokens.add(sb.toString());
return tokens;
}
private Map<List<String>, Integer> parseExpression(List<String> tokens, Map<String, Integer> evalmap) {
Deque<Map<List<String>, Integer>> vals = new ArrayDeque<>();
Deque<String> ops = new ArrayDeque<>();
Map<String, Integer> prec = Map.of(""+"",1, ""-"",1, ""*"",2);
for (String tok : tokens) {
if (tok.equals(""("")) ops.push(tok);
... truncated ...
else if (op.equals(""-"")) vals.push(sub(a, b));
else vals.push(mul(a, b));
}
private Map<List<String>, Integer> parseToken(String tok, Map<String, Integer> evalmap) {
Map<List<String>, Integer> res = new HashMap<>();
if (tok.matches(""-?\\d+"")) {
res.put(Collections.emptyList(), Integer.parseInt(tok));
} else if (evalmap.containsKey(tok)) {
res.put(Collections.emptyList(), evalmap.get(tok));
} else {
res.put(Arrays.asList(tok), 1);
}
return res;
}
private Map<List<String>, Integer> combine(Map<List<String>, Integer> m) {
Map<List<String>, Integer> res = new HashMap<>();
for (var e : m.entrySet()) {
if (e.getValue() != 0) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue());
}
res.entrySet().removeIf(kv -> kv.getValue() == 0);
return res;
}
private Map<List<String>, Integer> add(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
Map<List<String>, Integer> res = new HashMap<>(a);
for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) + e.getValue());
return combine(res);
}
private Map<List<String>, Integer> sub(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
Map<List<String>, Integer> res = new HashMap<>(a);
for (var e : b.entrySet()) res.put(e.getKey(), res.getOrDefault(e.getKey(), 0) - e.getValue());
return combine(res);
}
private Map<List<String>, Integer> mul(Map<List<String>, Integer> a, Map<List<String>, Integer> b) {
Map<List<String>, Integer> res = new HashMap<>();
for (var ea : a.entrySet()) {
for (var eb : b.entrySet()) {
List<String> merged = new ArrayList<>(ea.getKey());
merged.addAll(eb.getKey());
Collections.sort(merged);
res.put(merged, res.getOrDefault(merged, 0) + ea.getValue() * eb.getValue());
}
}
return combine(res);
}
}",120,101
,"import hashlib
class BloomFilter:
def __init__(self, size, hash_count):
self.size = size # Size of the bit array
self.hash_count = hash_count # Number of hash functions
self.bit_array = [0] * size # Bit array to store elements
def _hashes(self, item):
""""""Generate hash_count hashes for the item using different hash functions.""""""
hashes = []
for i in range(self.hash_count):
# Create a unique hash for each iteration
hash_result = int(hashlib.md5((str(item) + str(i)).encode()).hexdigest(), 16) % self.size
hashes.append(hash_result)
return hashes
def add(self, item):
""""""Add an item to the Bloom filter.""""""
hashes = self._hashes(item)
for hash_value in hashes:
self.bit_array[hash_value] = 1
def check(self, item):
""""""Check if an item is possibly in the Bloom filter.""""""
hashes = self._hashes(item)
return all(self.bit_array[hash_value] == 1 for hash_value in hashes)
# Example usage
size = 1000 # Size of the bit array
hash_count = 10 # Number of hash functions
bloom_filter = BloomFilter(size, hash_count)
# Add items to the Bloom filter
bloom_filter.add(""Red"")
bloom_filter.add(""Green"")
bloom_filter.add(""Blue"")
bloom_filter.add(""Orange"")
# Check for item membership
print(""Red in filter:"", bloom_filter.check(""Red"")) # Should be True
print(""Green in filter:"", bloom_filter.check(""Green"")) # Should be True
print(""Orange in filter:"", bloom_filter.check(""Orange"")) # Should be True
print(""Black in filter:"", bloom_filter.check(""Black"")) # Should be False (most likely)",0.0,W3RESOURCE,,python,"import hashlib
class BloomFilter:
def __init__(self, size, hash_count):
self.size = size # Size of the bit array
self.hash_count = hash_count # Number of hash functions
self.bit_array = [0] * size # Bit array to store elements
def _hashes(self, item):
""""""Generate hash_count hashes for the item using different hash functions.""""""
hashes = []
for i in range(self.hash_count):
# Create a unique hash for each iteration
hash_result = int(hashlib.md5((str(item) + str(i)).encode()).hexdigest(), 16) % self.size
hashes.append(hash_result)
return hashes
def add(self, item):
""""""Add an item to the Bloom filter.""""""
hashes = self._hashes(item)
for hash_value in hashes:
self.bit_array[hash_value] = 1
def check(self, item):
""""""Check if an item is possibly in the Bloom filter.""""""
hashes = self._hashes(item)
return all(self.bit_array[hash_value] == 1 for hash_value in hashes)
# Example usage
size = 1000 # Size of the bit array
hash_count = 10 # Number of hash functions
bloom_filter = BloomFilter(size, hash_count)
# Add items to the Bloom filter
bloom_filter.add(""Red"")
bloom_filter.add(""Green"")
bloom_filter.add(""Blue"")
bloom_filter.add(""Orange"")
# Check for item membership
print(""Red in filter:"", bloom_filter.check(""Red"")) # Should be True
print(""Green in filter:"", bloom_filter.check(""Green"")) # Should be True
print(""Orange in filter:"", bloom_filter.check(""Orange"")) # Should be True
print(""Black in filter:"", bloom_filter.check(""Black"")) # Should be False (most likely)",45,45
,"import tweepy
# Replace with your actual bearer token from Twitter Developer Portal
BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'
# Initialize the client with bearer token (sufficient for read access)
client = tweepy.Client(bearer_token=BEARER_TOKEN)
# Input for Twitter username (without @)
username = input(""Enter Twitter username: "")
try:
# Get the user by username
user = client.get_user(username=username)
if user.data:
# Access public_metrics which includes total tweet count
public_metrics = user.data.public_metrics
tweet_count = public_metrics['tweet_count']
print(f""@{username} has posted {tweet_count:,} tweets (including retweets and replies)."")
else:
print(""User not found."")
except tweepy.TweepyException as e:
print(f""Error: {e}"")
",1.0,PERPLEXITY,Write a Python program to count number of tweets by a given Twitter account. add a input feature where the user would give their account as an input .,python,"import tweepy
# Replace with your actual bearer token from Twitter Developer Portal
BEARER_TOKEN = 'YOUR_BEARER_TOKEN_HERE'
# Initialize the client with bearer token (sufficient for read access)
client = tweepy.Client(bearer_token=BEARER_TOKEN)
# Input for Twitter username (without @)
username = input(""Enter Twitter username: "")
try:
# Get the user by username
user = client.get_user(username=username)
if user.data:
# Access public_metrics which includes total tweet count
public_metrics = user.data.public_metrics
tweet_count = public_metrics['tweet_count']
print(f""@{username} has posted {tweet_count:,} tweets (including retweets and replies)."")
else:
print(""User not found."")
except tweepy.TweepyException as e:
print(f""Error: {e}"")",26,26
,"def shellSort(alist):
sublistcount = len(alist)//2
while sublistcount > 0:
for start_position in range(sublistcount):
gap_InsertionSort(alist, start_position, sublistcount)
print(""After increments of size"",sublistcount, ""The list is"",nlist)
sublistcount = sublistcount // 2
def gap_InsertionSort(nlist,start,gap):
for i in range(start+gap,len(nlist),gap):
current_value = nlist[i]
position = i
while position>=gap and nlist[position-gap]>current_value:
nlist[position]=nlist[position-gap]
position = position-gap
nlist[position]=current_value
nlist = [14,46,43,27,57,41,45,21,70]
shellSort(nlist)
print(nlist)
",0.0,W3RESOURCE,,python,"def shellSort(alist):
sublistcount = len(alist)//2
while sublistcount > 0:
for start_position in range(sublistcount):
gap_InsertionSort(alist, start_position, sublistcount)
print(""After increments of size"",sublistcount, ""The list is"",nlist)
sublistcount = sublistcount // 2
def gap_InsertionSort(nlist,start,gap):
for i in range(start+gap,len(nlist),gap):
current_value = nlist[i]
position = i
while position>=gap and nlist[position-gap]>current_value:
nlist[position]=nlist[position-gap]
position = position-gap
nlist[position]=current_value
nlist = [14,46,43,27,57,41,45,21,70]
shellSort(nlist)
print(nlist)",26,26
,"class WordFilter {
constructor(words) {
this.pTrie = new Array(27)
this.sTrie = new Array(27)
let wordSet = new Set()
for (let index = words.length - 1; ~index; index--) {
let word = words[index], wlen = word.length
if (wordSet.has(word))
continue;
wordSet.add(word)
this.insert(word, index, this.pTrie, 0, wlen, 1)
this.insert(word, index, this.sTrie, wlen-1, -1, -1)
}
}
insert(word, index, trie, start, end, step) {
for (let i = start; i != end; i += step) {
let c = word.charCodeAt(i) - 97
if (!trie[c]) trie[c] = new Array(27)
trie = trie[c]
if (!trie[26]) trie[26] = []
trie[26].push(index)
}
}
retrieve(word, trie, start, end, step) {
for (let i = start; i != end; i += step) {
let c = word.charCodeAt(i) - 97
if (!trie[c]) return []
trie = trie[c]
}
return trie[26]
}
f(pre, suf) {
let pVals = this.retrieve(pre, this.pTrie, 0, pre.length, 1),
sVals = this.retrieve(suf, this.sTrie, suf.length-1, -1, -1),
svix = 0, pvix = 0
while (svix < sVals.length && pvix < pVals.length) {
let sVal = sVals[svix], pVal = pVals[pvix]
if (sVal === pVal) return sVal
sVal > pVal ? svix++ : pvix++
}
return -1
}
};",0.0,leetcode,,java,"class WordFilter {
constructor(words) {
this.pTrie = new Array(27)
this.sTrie = new Array(27)
let wordSet = new Set()
for (let index = words.length - 1; ~index; index--) {
let word = words[index], wlen = word.length
if (wordSet.has(word))
continue;
wordSet.add(word)
this.insert(word, index, this.pTrie, 0, wlen, 1)
this.insert(word, index, this.sTrie, wlen-1, -1, -1)
}
}
insert(word, index, trie, start, end, step) {
for (let i = start; i != end; i += step) {
let c = word.charCodeAt(i) - 97
if (!trie[c]) trie[c] = new Array(27)
trie = trie[c]
if (!trie[26]) trie[26] = []
trie[26].push(index)
}
}
retrieve(word, trie, start, end, step) {
for (let i = start; i != end; i += step) {
let c = word.charCodeAt(i) - 97
if (!trie[c]) return []
trie = trie[c]
}
return trie[26]
}
f(pre, suf) {
let pVals = this.retrieve(pre, this.pTrie, 0, pre.length, 1),
sVals = this.retrieve(suf, this.sTrie, suf.length-1, -1, -1),
svix = 0, pvix = 0
while (svix < sVals.length && pvix < pVals.length) {
let sVal = sVals[svix], pVal = pVals[pvix]
if (sVal === pVal) return sVal
sVal > pVal ? svix++ : pvix++
}
return -1
}
};",46,46
,"class Solution {
public String[] findWords(String[] words) {
ArrayList<String> ans=new ArrayList<>();
String first = ""qwertyuiop"";
String Secound =""asdfghjkl"";
String Third=""zxcvbnm"";
for(String i : words){
if(isinrow(i,first) || isinrow(i,Secound) || isinrow(i,Third))
ans.add(i);
}
return ans.toArray(new String[0]);
}
private boolean isinrow(String s,String row){
for(char c:s.toCharArray()){
if(row.indexOf(Character.toLowerCase(c))==-1){
return false;
}
}
return true;
}
}",0.0,leetcode,,java,"class Solution {
public String[] findWords(String[] words) {
ArrayList<String> ans=new ArrayList<>();
String first = ""qwertyuiop"";
String Secound =""asdfghjkl"";
String Third=""zxcvbnm"";
for(String i : words){
if(isinrow(i,first) || isinrow(i,Secound) || isinrow(i,Third))
ans.add(i);
}
return ans.toArray(new String[0]);
}
private boolean isinrow(String s,String row){
for(char c:s.toCharArray()){
if(row.indexOf(Character.toLowerCase(c))==-1){
return false;
}
}
return true;
}
}",21,21
,"def maxArea(height):
l, r = 0, len(height) - 1
res = 0
while l < r:
res = max(res, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return res
",1.0,GPT,"Given an array height, find two lines that together with the x-axis form a container,
such that the container contains the most water.",python,"def maxArea(height):
l, r = 0, len(height) - 1
res = 0
while l < r:
res = max(res, min(height[l], height[r]) * (r - l))
if height[l] < height[r]:
l += 1
else:
r -= 1
return res",12,12
,"public class Solution {
public List<List<Integer>> palindromePairs(String[] words) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(words == null || words.length == 0){
return res;
}
//build the map save the key-val pairs: String - idx
HashMap<String, Integer> map = new HashMap<>();
for(int i = 0; i < words.length; i++){
map.put(words[i], i);
}
//special cases: """" can be combine with any palindrome string
if(map.containsKey("""")){
int blankIdx = map.get("""");
for(int i = 0; i < words.length; i++){
if(isPalindrome(words[i])){
if(i == blankIdx) continue;
res.add(Arrays.asList(blankIdx, i));
res.add(Arrays.asList(i, blankIdx));
}
}
}
//find all string and reverse string pairs
for(int i = 0; i < words.length; i++){
String cur_r = reverseStr(words[i]);
if(map.containsKey(cur_r)){
int found = map.get(cur_r);
if(found == i) continue;
res.add(Arrays.asList(i, found));
}
}
//find the pair s1, s2 that
//case1 : s1[0:cut] is palindrome and s1[cut+1:] = reverse(s2) => (s2, s1)
//case2 : s1[cut+1:] is palindrome and s1[0:cut] = reverse(s2) => (s1, s2)
for(int i = 0; i < words.length; i++){
String cur = words[i];
for(int cut = 1; cut < cur.length(); cut++){
if(isPalindrome(cur.substring(0, cut))){
String cut_r = reverseStr(cur.substring(cut));
if(map.containsKey(cut_r)){
int found = map.get(cut_r);
if(found == i) continue;
res.add(Arrays.asList(found, i));
}
}
if(isPalindrome(cur.substring(cut))){
String cut_r = reverseStr(cur.substring(0, cut));
if(map.containsKey(cut_r)){
int found = map.get(cut_r);
if(found == i) continue;
res.add(Arrays.asList(i, found));
}
}
}
}
return res;
}
public String reverseStr(String str){
StringBuilder sb= new StringBuilder(str);
return sb.reverse().toString();
}
public boolean isPalindrome(String s){
int i = 0;
int j = s.length() - 1;
while(i <= j){
if(s.charAt(i) != s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}",0.0,leetcode,,java,"public class Solution {
public List<List<Integer>> palindromePairs(String[] words) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(words == null || words.length == 0){
return res;
}
//build the map save the key-val pairs: String - idx
HashMap<String, Integer> map = new HashMap<>();
for(int i = 0; i < words.length; i++){
map.put(words[i], i);
}
//special cases: """" can be combine with any palindrome string
if(map.containsKey("""")){
int blankIdx = map.get("""");
for(int i = 0; i < words.length; i++){
if(isPalindrome(words[i])){
if(i == blankIdx) continue;
res.add(Arrays.asList(blankIdx, i));
res.add(Arrays.asList(i, blankIdx));
}
}
}
//find all string and reverse string pairs
for(int i = 0; i < words.length; i++){
String cur_r = reverseStr(words[i]);
if(map.containsKey(cur_r)){
int found = map.get(cur_r);
if(found == i) continue;
res.add(Arrays.asList(i, found));
}
}
//find the pair s1, s2 that
//case1 : s1[0:cut] is palindrome and s1[cut+1:] = reverse(s2) => (s2, s1)
//case2 : s1[cut+1:] is palindrome and s1[0:cut] = reverse(s2) => (s1, s2)
for(int i = 0; i < words.length; i++){
String cur = words[i];
for(int cut = 1; cut < cur.length(); cut++){
if(isPalindrome(cur.substring(0, cut))){
String cut_r = reverseStr(cur.substring(cut));
if(map.containsKey(cut_r)){
int found = map.get(cut_r);
if(found == i) continue;
res.add(Arrays.asList(found, i));
}
}
if(isPalindrome(cur.substring(cut))){
String cut_r = reverseStr(cur.substring(0, cut));
if(map.containsKey(cut_r)){
int found = map.get(cut_r);
if(found == i) continue;
res.add(Arrays.asList(i, found));
}
}
}
}
return res;
}
public String reverseStr(String str){
StringBuilder sb= new StringBuilder(str);
return sb.reverse().toString();
}
public boolean isPalindrome(String s){
int i = 0;
int j = s.length() - 1;
while(i <= j){
if(s.charAt(i) != s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}",79,79
,"public int deleteAndEarn(int[] nums) {
var numToCount = new HashMap<Integer, Integer>();
var min = Integer.MAX_VALUE;
var max = Integer.MIN_VALUE;
for (var num : nums) {
numToCount.compute(num, (k, v) -> v == null ? 1 : ++v);
min = Math.min(min, num);
max = Math.max(max, num);
}
var prevIncEarn = 0;
var prevExcEarn = 0;
for (var i = min; i <= max; i++) {
var incEarn = prevExcEarn + i * numToCount.getOrDefault(i, 0);
var excEarn = Math.max(prevIncEarn, prevExcEarn);
prevIncEarn = incEarn;
prevExcEarn = excEarn;
}
return Math.max(prevIncEarn, prevExcEarn);
}",0.0,leetcode,,java,"public int deleteAndEarn(int[] nums) {
var numToCount = new HashMap<Integer, Integer>();
var min = Integer.MAX_VALUE;
var max = Integer.MIN_VALUE;
for (var num : nums) {
numToCount.compute(num, (k, v) -> v == null ? 1 : ++v);
min = Math.min(min, num);
max = Math.max(max, num);
}
var prevIncEarn = 0;
var prevExcEarn = 0;
for (var i = min; i <= max; i++) {
var incEarn = prevExcEarn + i * numToCount.getOrDefault(i, 0);
var excEarn = Math.max(prevIncEarn, prevExcEarn);
prevIncEarn = incEarn;
prevExcEarn = excEarn;
}
return Math.max(prevIncEarn, prevExcEarn);
}",20,20
,"import java.util.UUID;
public class UUIDUtil {
public static String generate() {
return UUID.randomUUID().toString();
}
public static boolean isValid(String uuid) {
try {
UUID.fromString(uuid);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}
",1.0,PERPLEXITY,Implement a Java utility to generate UUID v4 strings and validate their format,java,"import java.util.UUID;
public class UUIDUtil {
public static String generate() {
return UUID.randomUUID().toString();
}
public static boolean isValid(String uuid) {
try {
UUID.fromString(uuid);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
}",14,14
,"class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
count = [0] * 26
for task in tasks:
count[ord(task) - ord('A')] += 1
maxf = max(count)
maxCount = 0
for i in count:
maxCount += 1 if i == maxf else 0
time = (maxf - 1) * (n + 1) + maxCount
return max(len(tasks), time)",0.0,GFG,,python,"class Solution:
def leastInterval(self, tasks: List[str], n: int) -> int:
count = [0] * 26
for task in tasks:
count[ord(task) - ord('A')] += 1
maxf = max(count)
maxCount = 0
for i in count:
maxCount += 1 if i == maxf else 0
time = (maxf - 1) * (n + 1) + maxCount
return max(len(tasks), time)",13,13
,"class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
N = len(grid)
visit = set()
minH = [[grid[0][0], 0, 0]] # (time/max-height, r, c)
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
visit.add((0, 0))
while minH:
t, r, c = heapq.heappop(minH)
if r == N - 1 and c == N - 1:
return t
for dr, dc in directions:
neiR, neiC = r + dr, c + dc
if (neiR < 0 or neiC < 0 or
neiR == N or neiC == N or
(neiR, neiC) in visit
):
continue
visit.add((neiR, neiC))
heapq.heappush(minH, [max(t, grid[neiR][neiC]), neiR, neiC])",0.0,GFG,,python,"class Solution:
def swimInWater(self, grid: List[List[int]]) -> int:
N = len(grid)
visit = set()
minH = [[grid[0][0], 0, 0]] # (time/max-height, r, c)
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
visit.add((0, 0))
while minH:
t, r, c = heapq.heappop(minH)
if r == N - 1 and c == N - 1:
return t
for dr, dc in directions:
neiR, neiC = r + dr, c + dc
if (neiR < 0 or neiC < 0 or
neiR == N or neiC == N or
(neiR, neiC) in visit
):
continue
visit.add((neiR, neiC))
heapq.heappush(minH, [max(t, grid[neiR][neiC]), neiR, neiC])",21,21
,"import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
public class WriterPreferenceReadWriteLock implements ReadWriteLock {
private final Sync sync;
public WriterPreferenceReadWriteLock() {
this.sync = new Sync();
}
private static class Sync extends AbstractQueuedSynchronizer {
private static final int READER_MASK = (1 << 16) - 1;
private static final int WRITER_MASK = ~READER_MASK;
private int readers() {
return getState() & READER_MASK;
}
private int writers() {
return (getState() >>> 16) & READER_MASK;
}
private int incrementReaders() {
return getState() + 1;
}
private int decrementReaders() {
return getState() - 1;
}
private int incrementWriters() {
return getState() + (1 << 16);
}
private int decrementWriters() {
return getState() - (1 << 16);
}
@Override
protected boolean tryAcquire(int arg) {
Thread current = Thread.currentThread();
int state = getState();
// If no readers or writers, try to acquire write lock
if (state == 0) {
if (compareAndSetState(0, 1 << 16)) {
setExclusiveOwnerThread(current);
return true;
}
} else if (getExclusiveOwnerThread() == current) {
// Reentrant write lock
setState(state + (1 << 16));
return true;
}
return false;
}
@Override
protected boolean tryRelease(int arg) {
if (getExclusiveOwnerThread() != Thread.currentThread()) {
throw new IllegalMonitorStateException();
}
int newState = decrementWriters();
boolean free = (newState & WRITER_MASK) == 0;
if (free) {
setExclusiveOwnerThread(null);
}
setState(newState);
return free;
}
@Override
protected int tryAcquireShared(int arg) {
Thread current = Thread.currentThread();
int state = getState();
// If there are waiting writers, don't acquire read lock
if (hasQueuedPredecessors()) {
return -1;
}
// If no writers, try to acquire read lock
if ((state & WRITER_MASK) == 0) {
if (compareAndSetState(state, incrementReaders())) {
return 1;
}
}
return -1;
}
@Override
protected boolean tryReleaseShared(int arg) {
int newState;
int currentState;
do {
currentState = getState();
newState = decrementReaders();
} while (!compareAndSetState(currentState, newState));
return true;
}
@Override
protected boolean isHeldExclusively() {
return getExclusiveOwnerThread() == Thread.currentThread();
}
Condition newCondition() {
return new ConditionObject();
}
}
private static class ReadLock implements Lock {
private final Sync sync;
ReadLock(Sync sync) {
this.sync = sync;
}
@Override
public void lock() {
sync.acquireShared(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
@Override
public boolean tryLock() {
return sync.tryAcquireShared(1) >= 0;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(time));
}
@Override
public void unlock() {
sync.releaseShared(1);
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException(""Read locks don't support conditions"");
}
}
private static class WriteLock implements Lock {
private final Sync sync;
WriteLock(Sync sync) {
this.sync = sync;
}
@Override
public void lock() {
sync.acquire(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
@Override
public boolean tryLock() {
return sync.tryAcquire(1);
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(time));
}
@Override
public void unlock() {
sync.release(1);
}
@Override
public Condition newCondition() {
return sync.newCondition();
}
}
@Override
public Lock readLock() {
return new ReadLock(sync);
}
@Override
public Lock writeLock() {
return new WriteLock(sync);
}
}",1.0,DEEPSEEK,Implement a read-write lock that gives preference to writers to prevent writer starvation.,java,"import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
public class WriterPreferenceReadWriteLock implements ReadWriteLock {
private final Sync sync;
public WriterPreferenceReadWriteLock() {
this.sync = new Sync();
}
private static class Sync extends AbstractQueuedSynchronizer {
private static final int READER_MASK = (1 << 16) - 1;
private static final int WRITER_MASK = ~READER_MASK;
private int readers() {
return getState() & READER_MASK;
}
private int writers() {
return (getState() >>> 16) & READER_MASK;
}
private int incrementReaders() {
return getState() + 1;
}
private int decrementReaders() {
return getState() - 1;
}
private int incrementWriters() {
return getState() + (1 << 16);
}
private int decrementWriters() {
return getState() - (1 << 16);
}
@Override
protected boolean tryAcquire(int arg) {
Thread current = Thread.currentThread();
int state = getState();
// If no readers or writers, try to acquire write lock
if (state == 0) {
if (compareAndSetState(0, 1 << 16)) {
setExclusiveOwnerThread(current);
return true;
... truncated ...
}
private static class WriteLock implements Lock {
private final Sync sync;
WriteLock(Sync sync) {
this.sync = sync;
}
@Override
public void lock() {
sync.acquire(1);
}
@Override
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
@Override
public boolean tryLock() {
return sync.tryAcquire(1);
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(time));
}
@Override
public void unlock() {
sync.release(1);
}
@Override
public Condition newCondition() {
return sync.newCondition();
}
}
@Override
public Lock readLock() {
return new ReadLock(sync);
}
@Override
public Lock writeLock() {
return new WriteLock(sync);
}
}",203,101
,"class Solution {
public int findMaxLength(int[] nums) {
// Map to store first occurrence of diff
HashMap<Integer, Integer> map = new HashMap<>();
int zero = 0, one = 0;
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0)
zero++;
else
one++;
int diff = zero - one;
// If diff == 0, subarray from 0 to i is valid
if (diff == 0) {
res = Math.max(res, i + 1);
}
// If diff not seen before, store index
if (!map.containsKey(diff)) {
map.put(diff, i);
}
// If seen before, calculate length
else {
int idx = map.get(diff);
int len = i - idx;
res = Math.max(res, len);
}
}
return res;
}
}",0.0,leetcode,,java,"class Solution {
public int findMaxLength(int[] nums) {
// Map to store first occurrence of diff
HashMap<Integer, Integer> map = new HashMap<>();
int zero = 0, one = 0;
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0)
zero++;
else
one++;
int diff = zero - one;
// If diff == 0, subarray from 0 to i is valid
if (diff == 0) {
res = Math.max(res, i + 1);
}
// If diff not seen before, store index
if (!map.containsKey(diff)) {
map.put(diff, i);
}
// If seen before, calculate length
else {
int idx = map.get(diff);
int len = i - idx;
res = Math.max(res, len);
}
}
return res;
}
}",37,37
,"public class PalindromeChecker {
public static boolean isPalindrome(String s) {
s = s.toLowerCase().replaceAll(""[^a-z0-9]"", """");
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) return false;
}
return true;
}
}
",1.0,PERPLEXITY,"Write a Java static method to check if a string is a palindrome, ignoring case and non-alphanumeric chars.",java,"public class PalindromeChecker {
public static boolean isPalindrome(String s) {
s = s.toLowerCase().replaceAll(""[^a-z0-9]"", """");
int left = 0, right = s.length() - 1;
while (left < right) {
if (s.charAt(left++) != s.charAt(right--)) return false;
}
return true;
}
}",10,10
,"class Solution {
public int getImportance(List<Employee> employees, int id) {
Map<Integer, Employee> inputMap = new HashMap<>();
// Construct HashMap as getting the employee from id is difficult in a list
for(Employee e : employees) {
inputMap.put(e.id, e);
}
return helper(inputMap, id);
}
private static int helper(Map<Integer, Employee> inputMap, int id) {
//Get the importance of the employee
int imp = inputMap.get(id).importance;
//Add importance of subordinates to employee importance
for(int subId : inputMap.get(id).subordinates) {
imp += helper(inputMap, subId);
}
return imp;
}
}",0.0,leetcode,,java,"class Solution {
public int getImportance(List<Employee> employees, int id) {
Map<Integer, Employee> inputMap = new HashMap<>();
// Construct HashMap as getting the employee from id is difficult in a list
for(Employee e : employees) {
inputMap.put(e.id, e);
}
return helper(inputMap, id);
}
private static int helper(Map<Integer, Employee> inputMap, int id) {
//Get the importance of the employee
int imp = inputMap.get(id).importance;
//Add importance of subordinates to employee importance
for(int subId : inputMap.get(id).subordinates) {
imp += helper(inputMap, subId);
}
return imp;
}
}",22,22
,"import heapq
def swimInWater(grid):
n = len(grid)
heap = [(grid[0][0], 0, 0)]
visited = set()
while heap:
time, r, c = heapq.heappop(heap)
if (r, c) in visited:
continue
visited.add((r, c))
if r == n - 1 and c == n - 1:
return time
for dr, dc in [(1,0), (-1,0), (0,1), (0,-1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n:
heapq.heappush(heap, (max(time, grid[nr][nc]), nr, nc))
",1.0,GPT,"Solve the problem ""Swim in Rising Water"".
Given an n x n grid,
return the minimum time required to swim from top-left to bottom-right.",python,"import heapq
def swimInWater(grid):
n = len(grid)
heap = [(grid[0][0], 0, 0)]
visited = set()
while heap:
time, r, c = heapq.heappop(heap)
if (r, c) in visited:
continue
visited.add((r, c))
if r == n - 1 and c == n - 1:
return time
for dr, dc in [(1,0), (-1,0), (0,1), (0,-1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < n and 0 <= nc < n:
heapq.heappush(heap, (max(time, grid[nr][nc]), nr, nc))",18,18
,"import java.util.*;
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
Map<String, Integer> map = new HashMap<>();
for (String domainCount : cpdomains) {
int spaceIndex = domainCount.indexOf(' ');
int count = Integer.parseInt(domainCount.substring(0, spaceIndex));
String domain = domainCount.substring(spaceIndex + 1);
// Process each subdomain
while (true) {
map.merge(domain, count, Integer::sum);
int dotIndex = domain.indexOf('.');
if (dotIndex == -1) break;
domain = domain.substring(dotIndex + 1);
}
}
List<String> result = new ArrayList<>(map.size());
for (Map.Entry<String, Integer> entry : map.entrySet()) {
result.add(entry.getValue() + "" "" + entry.getKey());
}
return result;
}
}",0.0,leetcode,,java,"import java.util.*;
class Solution {
public List<String> subdomainVisits(String[] cpdomains) {
Map<String, Integer> map = new HashMap<>();
for (String domainCount : cpdomains) {
int spaceIndex = domainCount.indexOf(' ');
int count = Integer.parseInt(domainCount.substring(0, spaceIndex));
String domain = domainCount.substring(spaceIndex + 1);
// Process each subdomain
while (true) {
map.merge(domain, count, Integer::sum);
int dotIndex = domain.indexOf('.');
if (dotIndex == -1) break;
domain = domain.substring(dotIndex + 1);
}
}
List<String> result = new ArrayList<>(map.size());
for (Map.Entry<String, Integer> entry : map.entrySet()) {
result.add(entry.getValue() + "" "" + entry.getKey());
}
return result;
}
}",28,28
,"import hashlib
class Bloom:
def __init__(s,n,k):
s.n,s.k,s.b=n,k,[0]*n
def _h(s,x):
h1=int(hashlib.sha256(x.encode()).hexdigest(),16)
h2=int(hashlib.md5(x.encode()).hexdigest(),16)
return [(h1+i*h2)%s.n for i in range(s.k)]
def add(s,x):
for i in s._h(x): s.b[i]=1
def check(s,x):
return all(s.b[i] for i in s._h(x))
",1.0,GPT,"WRITE THE PYTHON CODE FOR Bloom Filter Implementation with i/o , let the code you provide be efficient and accurate for the results it provide",python,"import hashlib
class Bloom:
def __init__(s,n,k):
s.n,s.k,s.b=n,k,[0]*n
def _h(s,x):
h1=int(hashlib.sha256(x.encode()).hexdigest(),16)
h2=int(hashlib.md5(x.encode()).hexdigest(),16)
return [(h1+i*h2)%s.n for i in range(s.k)]
def add(s,x):
for i in s._h(x): s.b[i]=1
def check(s,x):
return all(s.b[i] for i in s._h(x))",16,16
,"import requests
from bs4 import BeautifulSoup
url = 'https://www.wikipedia.org/'
soup = BeautifulSoup(requests.get(url).text, 'html.parser')
langs = soup.find('ul', class_='languages').find_all('li')
for lang in langs:
name = lang.text.strip()
count = lang.a['title'].split(' ')[0].replace(',', '')
print(f""{name}: {count}"")
",1.0,PERPLEXITY,Write a Python program to list all language names and number of related articles in the order they appear in wikipedia.org.,python,"import requests
from bs4 import BeautifulSoup
url = 'https://www.wikipedia.org/'
soup = BeautifulSoup(requests.get(url).text, 'html.parser')
langs = soup.find('ul', class_='languages').find_all('li')
for lang in langs:
name = lang.text.strip()
count = lang.a['title'].split(' ')[0].replace(',', '')
print(f""{name}: {count}"")",11,11
,"#https://bit.ly/2lVhlLX
# via: https://analytics.usa.gov/
import requests
url = 'https://analytics.usa.gov/data/live/realtime.json'
j = requests.get(url).json()
print(""Number of people visiting a U.S. government website-"")
print(""Active Users Right Now:"")
print(j['data'][0]['active_visitors'])
",0.0,WE3RESOURCE,,python,"#https://bit.ly/2lVhlLX
# via: https://analytics.usa.gov/
import requests
url = 'https://analytics.usa.gov/data/live/realtime.json'
j = requests.get(url).json()
print(""Number of people visiting a U.S. government website-"")
print(""Active Users Right Now:"")
print(j['data'][0]['active_visitors'])",8,8
,"def trap(height):
l, r = 0, len(height) - 1
left_max = right_max = 0
res = 0
while l < r:
if height[l] < height[r]:
left_max = max(left_max, height[l])
res += left_max - height[l]
l += 1
else:
right_max = max(right_max, height[r])
res += right_max - height[r]
r -= 1
return res
",1.0,GPT,"Given an array height representing elevation map,
compute how much water it can trap after raining.",python,"def trap(height):
l, r = 0, len(height) - 1
left_max = right_max = 0
res = 0
while l < r:
if height[l] < height[r]:
left_max = max(left_max, height[l])
res += left_max - height[l]
l += 1
else:
right_max = max(right_max, height[r])
res += right_max - height[r]
r -= 1
return res",16,16
,"class Solution {
public boolean isPossible(int[] nums) {
// freq: counts how many of each number are available to be used
Map<Integer, Integer> freq = new HashMap<>();
// want: counts how many sequences are currently ending at (x-1) and need 'x'
Map<Integer, Integer> want = new HashMap<>();
for (int i : nums) freq.put(i, freq.getOrDefault(i, 0) + 1);
for (int i : nums) {
if (freq.get(i) == 0) continue; // Already consumed by a previous 'new sequence' check
// Option 1: Try to extend an existing sequence
if (want.getOrDefault(i, 0) > 0) {
freq.put(i, freq.get(i) - 1);
want.put(i, want.get(i) - 1);
want.put(i + 1, want.getOrDefault(i + 1, 0) + 1);
}
// Option 2: Try to create a new sequence of length 3
else if (freq.getOrDefault(i + 1, 0) > 0 && freq.getOrDefault(i + 2, 0) > 0) {
freq.put(i, freq.get(i) - 1);
freq.put(i + 1, freq.get(i + 1) - 1);
freq.put(i + 2, freq.get(i + 2) - 1);
// This sequence now ends at i+2, so it looks forward to i+3
want.put(i + 3, want.getOrDefault(i + 3, 0) + 1);
}
// Option 3: Impossible to use 'i' validly
else {
return false;
}
}
return true;
}
}",0.0,leetcode,,java,"class Solution {
public boolean isPossible(int[] nums) {
// freq: counts how many of each number are available to be used
Map<Integer, Integer> freq = new HashMap<>();
// want: counts how many sequences are currently ending at (x-1) and need 'x'
Map<Integer, Integer> want = new HashMap<>();
for (int i : nums) freq.put(i, freq.getOrDefault(i, 0) + 1);
for (int i : nums) {
if (freq.get(i) == 0) continue; // Already consumed by a previous 'new sequence' check
// Option 1: Try to extend an existing sequence
if (want.getOrDefault(i, 0) > 0) {
freq.put(i, freq.get(i) - 1);
want.put(i, want.get(i) - 1);
want.put(i + 1, want.getOrDefault(i + 1, 0) + 1);
}
// Option 2: Try to create a new sequence of length 3
else if (freq.getOrDefault(i + 1, 0) > 0 && freq.getOrDefault(i + 2, 0) > 0) {
freq.put(i, freq.get(i) - 1);
freq.put(i + 1, freq.get(i + 1) - 1);
freq.put(i + 2, freq.get(i + 2) - 1);
// This sequence now ends at i+2, so it looks forward to i+3
want.put(i + 3, want.getOrDefault(i + 3, 0) + 1);
}
// Option 3: Impossible to use 'i' validly
else {
return false;
}
}
return true;
}
}",34,34
,"def maxProfit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
",1.0,GPT,"You are given an array prices where prices[i] is the price of a stock on day i.
You may choose one day to buy and a later day to sell.
Return the maximum profit you can achieve. If no profit is possible, return 0.
Provide:
- An optimal O(n) solution
- Explanation of the approach
- Python implementation",python,"def maxProfit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit",9,9
,"# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root",0.0,GFG,,python,"# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root",20,20
,"from bs4 import BeautifulSoup
import requests
handle = input('Input your account name on Twitter: ')
temp = requests.get('https://twitter.com/'+handle)
bs = BeautifulSoup(temp.text,'lxml')
try:
tweet_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--tweets is-active'})
tweets= tweet_box.find('a').find('span',{'class':'ProfileNav-value'})
print(""{} tweets {} number of tweets."".format(handle,tweets.get('data-count')))
except:
print('Account name not found...')
",0.0,WERESOURCE,,python,"from bs4 import BeautifulSoup
import requests
handle = input('Input your account name on Twitter: ')
temp = requests.get('https://twitter.com/'+handle)
bs = BeautifulSoup(temp.text,'lxml')
try:
tweet_box = bs.find('li',{'class':'ProfileNav-item ProfileNav-item--tweets is-active'})
tweets= tweet_box.find('a').find('span',{'class':'ProfileNav-value'})
print(""{} tweets {} number of tweets."".format(handle,tweets.get('data-count')))
except:
print('Account name not found...')",14,14
,"class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split("" "");
if (pattern.length() != words.length) return false;
Map<Character, String> charWord = new HashMap<>();
Map<String, Character> wordChar = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
String word = words[i];
if (charWord.containsKey(ch)) {
if (!charWord.get(ch).equals(word)) {
return false;
}
} else if (wordChar.containsKey(word)) {
return false;
} else {
charWord.put(ch, word);
wordChar.put(word, ch);
}
}
return true;
}
}",0.0,leetcode,,java,"class Solution {
public boolean wordPattern(String pattern, String s) {
String[] words = s.split("" "");
if (pattern.length() != words.length) return false;
Map<Character, String> charWord = new HashMap<>();
Map<String, Character> wordChar = new HashMap<>();
for (int i = 0; i < pattern.length(); i++) {
char ch = pattern.charAt(i);
String word = words[i];
if (charWord.containsKey(ch)) {
if (!charWord.get(ch).equals(word)) {
return false;
}
} else if (wordChar.containsKey(word)) {
return false;
} else {
charWord.put(ch, word);
wordChar.put(word, ch);
}
}
return true;
}
}",29,29
,"import heapq
# Define a class to represent a node in the graph
class Node:
def __init__(self, state, parent=None, action=None, cost=0, heuristic=0):
self.state = state # Current state
self.parent = parent # Parent node
self.action = action # Action taken to reach this node
self.cost = cost # Cost from start node to this node
self.heuristic = heuristic # Heuristic estimate of cost to goal
# Compare nodes based on total cost (cost + heuristic)
def __lt__(self, other):
return (self.cost + self.heuristic) < (other.cost + other.heuristic)
# Define the A* search function
def astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn):
# Initialize start node
start_node = Node(state=start_state, cost=0, heuristic=heuristic_fn(start_state))
# Priority queue for open nodes
open_nodes = []
heapq.heappush(open_nodes, start_node)
# Set of explored states
explored = set()
while open_nodes:
# Pop node with lowest total cost from priority queue
current_node = heapq.heappop(open_nodes)
# Check if goal state reached
if current_node.state == goal_state:
return get_solution(current_node)
# Add current state to explored set
explored.add(current_node.state)
# Generate successor states
for action in actions(current_node.state): # Fix: Call actions function with current state
next_state = transition_model(current_node.state, action)
if next_state not in explored:
cost = current_node.cost + cost_fn(current_node.state, action, next_state)
heuristic = heuristic_fn(next_state)
next_node = Node(state=next_state, parent=current_node, action=action, cost=cost, heuristic=heuristic)
heapq.heappush(open_nodes, next_node)
return None # No solution found
# Function to reconstruct the solution path
def get_solution(node):
path = []
while node:
path.append((node.state, node.action))
node = node.parent
return list(reversed(path))
# Example usage:
if __name__ == ""__main__"":
# Define example functions and parameters for pathfinding problem
def actions(state):
return ['up', 'down', 'left', 'right']
def transition_model(state, action):
if action == 'up':
return (state[0] - 1, state[1])
elif action == 'down':
return (state[0] + 1, state[1])
elif action == 'left':
return (state[0], state[1] - 1)
elif action == 'right':
return (state[0], state[1] + 1)
def cost_fn(state, action, next_state):
return 1
def heuristic_fn(state):
return abs(state[0] - goal_state[0]) + abs(state[1] - goal_state[1])
# Define start and goal states
start_state = (0, 0)
goal_state = (3, 3)
# Perform A* search
solution = astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn)
print(""Solution:"", solution)
",0.0,W3RESOURCE,,python,"import heapq
# Define a class to represent a node in the graph
class Node:
def __init__(self, state, parent=None, action=None, cost=0, heuristic=0):
self.state = state # Current state
self.parent = parent # Parent node
self.action = action # Action taken to reach this node
self.cost = cost # Cost from start node to this node
self.heuristic = heuristic # Heuristic estimate of cost to goal
# Compare nodes based on total cost (cost + heuristic)
def __lt__(self, other):
return (self.cost + self.heuristic) < (other.cost + other.heuristic)
# Define the A* search function
def astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn):
# Initialize start node
start_node = Node(state=start_state, cost=0, heuristic=heuristic_fn(start_state))
# Priority queue for open nodes
open_nodes = []
heapq.heappush(open_nodes, start_node)
# Set of explored states
explored = set()
while open_nodes:
# Pop node with lowest total cost from priority queue
current_node = heapq.heappop(open_nodes)
# Check if goal state reached
if current_node.state == goal_state:
return get_solution(current_node)
# Add current state to explored set
explored.add(current_node.state)
# Generate successor states
for action in actions(current_node.state): # Fix: Call actions function with current state
next_state = transition_model(current_node.state, action)
if next_state not in explored:
cost = current_node.cost + cost_fn(current_node.state, action, next_state)
heuristic = heuristic_fn(next_state)
next_node = Node(state=next_state, parent=current_node, action=action, cost=cost, heuristic=heuristic)
heapq.heappush(open_nodes, next_node)
return None # No solution found
# Function to reconstruct the solution path
def get_solution(node):
path = []
while node:
path.append((node.state, node.action))
node = node.parent
return list(reversed(path))
# Example usage:
if __name__ == ""__main__"":
# Define example functions and parameters for pathfinding problem
def actions(state):
return ['up', 'down', 'left', 'right']
def transition_model(state, action):
if action == 'up':
return (state[0] - 1, state[1])
elif action == 'down':
return (state[0] + 1, state[1])
elif action == 'left':
return (state[0], state[1] - 1)
elif action == 'right':
return (state[0], state[1] + 1)
def cost_fn(state, action, next_state):
return 1
def heuristic_fn(state):
return abs(state[0] - goal_state[0]) + abs(state[1] - goal_state[1])
# Define start and goal states
start_state = (0, 0)
goal_state = (3, 3)
# Perform A* search
solution = astar_search(start_state, goal_state, actions, transition_model, cost_fn, heuristic_fn)
print(""Solution:"", solution)",86,86
,"class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
ROWS, COLS = len(grid), len(grid[0])
islands = 0
def bfs(r, c):
q = deque()
grid[r][c] = ""0""
q.append((r, c))
while q:
row, col = q.popleft()
for dr, dc in directions:
nr, nc = dr + row, dc + col
if (nr < 0 or nc < 0 or nr >= ROWS or
nc >= COLS or grid[nr][nc] == ""0""
):
continue
q.append((nr, nc))
grid[nr][nc] = ""0""
for r in range(ROWS):
for c in range(COLS):
if grid[r][c] == ""1"":
bfs(r, c)
islands += 1
return islands",0.0,GFG,,python,"class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]
ROWS, COLS = len(grid), len(grid[0])
islands = 0
def bfs(r, c):
q = deque()
grid[r][c] = ""0""
q.append((r, c))
while q:
row, col = q.popleft()
for dr, dc in directions:
nr, nc = dr + row, dc + col
if (nr < 0 or nc < 0 or nr >= ROWS or
nc >= COLS or grid[nr][nc] == ""0""
):
continue
q.append((nr, nc))
grid[nr][nc] = ""0""
for r in range(ROWS):
for c in range(COLS):
if grid[r][c] == ""1"":
bfs(r, c)
islands += 1
return islands",29,29
,"import requests
from requests.exceptions import SSLError, RequestException
url = ""https://www.google.com"" # valid SSL certificate
try:
# By default, verify=True, so SSL certificates are checked
response = requests.get(url, timeout=10)
print(""Status Code:"", response.status_code)
print(""SSL certificate verified successfully."")
except SSLError as ssl_err:
print(""SSL Certificate verification failed!"")
print(ssl_err)
except RequestException as req_err:
print(""Request failed:"")
print(req_err)
",1.0,GPT," Write a Python program to verifiy SSL certificates for HTTPS requests using requests module.
Note: Requests verifies SSL certificates for HTTPS requests, just like a web browser. By default, SSL verification is enabled, and Requests will throw a SSLError if it's unable to verify the certificate",python,"import requests
from requests.exceptions import SSLError, RequestException
url = ""https://www.google.com"" # valid SSL certificate
try:
# By default, verify=True, so SSL certificates are checked
response = requests.get(url, timeout=10)
print(""Status Code:"", response.status_code)
print(""SSL certificate verified successfully."")
except SSLError as ssl_err:
print(""SSL Certificate verification failed!"")
print(ssl_err)
except RequestException as req_err:
print(""Request failed:"")
print(req_err)",18,18
,"public class MergeArrays {
public static int[] merge(int[] a, int[] b) {
int[] result = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) result[k++] = a[i++];
else result[k++] = b[j++];
}
while (i < a.length) result[k++] = a[i++];
while (j < b.length) result[k++] = b[j++];
return result;
}
}
",1.0,PERPLEXITY,Create a Java method that merges two sorted integer arrays into one sorted array without extra space if possible.,java,"public class MergeArrays {
public static int[] merge(int[] a, int[] b) {
int[] result = new int[a.length + b.length];
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) result[k++] = a[i++];
else result[k++] = b[j++];
}
while (i < a.length) result[k++] = a[i++];
while (j < b.length) result[k++] = b[j++];
return result;
}
}",13,13
,"class Solution {
public int nthUglyNumber(int n) {
int[] primes = {2, 3, 5};
PriorityQueue<Long> uglyHeap = new PriorityQueue<>();
HashSet<Long> visited = new HashSet<>();
uglyHeap.add(1L);
visited.add(1L);
long curr = 1L;
for (int i = 0; i < n; i++) {
curr = uglyHeap.poll();
for (int prime : primes) {
long new_ugly = curr * prime;
if (!visited.contains(new_ugly)) {
uglyHeap.add(new_ugly);
visited.add(new_ugly);
}
}
}
return (int)curr;
}
}",0.0,leetcode,,java,"class Solution {
public int nthUglyNumber(int n) {
int[] primes = {2, 3, 5};
PriorityQueue<Long> uglyHeap = new PriorityQueue<>();
HashSet<Long> visited = new HashSet<>();
uglyHeap.add(1L);
visited.add(1L);
long curr = 1L;
for (int i = 0; i < n; i++) {
curr = uglyHeap.poll();
for (int prime : primes) {
long new_ugly = curr * prime;
if (!visited.contains(new_ugly)) {
uglyHeap.add(new_ugly);
visited.add(new_ugly);
}
}
}
return (int)curr;
}
}",23,23
,"public class QuickSort {
public static void sort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
sort(arr, low, pi - 1);
sort(arr, pi + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
}
}
int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp;
return i + 1;
}
}
",1.0,PERPLEXITY,Write a Java quicksort algorithm to sort an integer array in-place using the Lomuto partition scheme,java,"public class QuickSort {
public static void sort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
sort(arr, low, pi - 1);
sort(arr, pi + 1, high);
}
}
private static int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp;
}
}
int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp;
return i + 1;
}
}",21,21
,"import java.util.*;
class Solution {
public int openLock(String[] deadends, String target) {
Set<String> deadendSet = new HashSet<>(Arrays.asList(deadends));
if (deadendSet.contains(""0000"")) {
return -1;
}
Queue<Pair<String, Integer>> queue = new LinkedList<>();
queue.offer(new Pair<>(""0000"", 0));
Set<String> visited = new HashSet<>();
visited.add(""0000"");
while (!queue.isEmpty()) {
Pair<String, Integer> current = queue.poll();
String currentCombination = current.getKey();
int moves = current.getValue();
if (currentCombination.equals(target)) {
return moves;
}
for (int i = 0; i < 4; i++) {
for (int delta : new int[]{-1, 1}) {
int newDigit = (currentCombination.charAt(i) - '0' + delta + 10) % 10;
String newCombination = currentCombination.substring(0, i) +
newDigit +
currentCombination.substring(i + 1);
if (!visited.contains(newCombination) && !deadendSet.contains(newCombination)) {
visited.add(newCombination);
queue.offer(new Pair<>(newCombination, moves + 1));
}
}
}
}
return -1; // Target is not reachable
}
}",0.0,leetcode,,java,"import java.util.*;
class Solution {
public int openLock(String[] deadends, String target) {
Set<String> deadendSet = new HashSet<>(Arrays.asList(deadends));
if (deadendSet.contains(""0000"")) {
return -1;
}
Queue<Pair<String, Integer>> queue = new LinkedList<>();
queue.offer(new Pair<>(""0000"", 0));
Set<String> visited = new HashSet<>();
visited.add(""0000"");
while (!queue.isEmpty()) {
Pair<String, Integer> current = queue.poll();
String currentCombination = current.getKey();
int moves = current.getValue();
if (currentCombination.equals(target)) {
return moves;
}
for (int i = 0; i < 4; i++) {
for (int delta : new int[]{-1, 1}) {
int newDigit = (currentCombination.charAt(i) - '0' + delta + 10) % 10;
String newCombination = currentCombination.substring(0, i) +
newDigit +
currentCombination.substring(i + 1);
if (!visited.contains(newCombination) && !deadendSet.contains(newCombination)) {
visited.add(newCombination);
queue.offer(new Pair<>(newCombination, moves + 1));
}
}
}
}
return -1; // Target is not reachable
}
}",41,41
,"class TreeNode {
int val; TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class TreeTraversal {
public void inorder(TreeNode root, List<Integer> result) {
if (root == null) return;
inorder(root.left, result);
result.add(root.val);
inorder(root.right, result);
}
}
",1.0,PERPLEXITY,"Create a Java method for inorder traversal of a binary tree, collecting values in a List",java,"class TreeNode {
int val; TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class TreeTraversal {
public void inorder(TreeNode root, List<Integer> result) {
if (root == null) return;
inorder(root.left, result);
result.add(root.val);
inorder(root.right, result);
}
}",12,12
,"import requests
from bs4 import BeautifulSoup
res = requests.get('https://hackevents.co/hackathons')
bs = BeautifulSoup(res.text, 'lxml')
hacks_data = bs.find_all('div',{'class':'hackathon '})
for i,f in enumerate(hacks_data,1):
hacks_month = f.find('div',{'class':'date'}).find('div',{'class':'date-month'}).text.strip()
hacks_date = f.find('div',{'class':'date'}).find('div',{'class':'date-day-number'}).text.strip()
hacks_days = f.find('div',{'class':'date'}).find('div',{'class':'date-week-days'}).text.strip()
hacks_final_date = ""{} {}, {} "".format(hacks_date, hacks_month, hacks_days )
hacks_name = f.find('div',{'class':'info'}).find('h2').text.strip()
hacks_city = f.find('div',{'class':'info'}).find('p').find('span',{'class':'city'}).text.strip()
hacks_country = f.find('div',{'class':'info'}).find('p').find('span',{'class':'country'}).text.strip()
print(""{:<5}{:<15}: {:<90}: {}, {}\n "".format(str(i)+')',hacks_final_date, hacks_name.title(), hacks_city, hacks_country))
",0.0,WERESOURCE,,python,"import requests
from bs4 import BeautifulSoup
res = requests.get('https://hackevents.co/hackathons')
bs = BeautifulSoup(res.text, 'lxml')
hacks_data = bs.find_all('div',{'class':'hackathon '})
for i,f in enumerate(hacks_data,1):
hacks_month = f.find('div',{'class':'date'}).find('div',{'class':'date-month'}).text.strip()
hacks_date = f.find('div',{'class':'date'}).find('div',{'class':'date-day-number'}).text.strip()
hacks_days = f.find('div',{'class':'date'}).find('div',{'class':'date-week-days'}).text.strip()
hacks_final_date = ""{} {}, {} "".format(hacks_date, hacks_month, hacks_days )
hacks_name = f.find('div',{'class':'info'}).find('h2').text.strip()
hacks_city = f.find('div',{'class':'info'}).find('p').find('span',{'class':'city'}).text.strip()
hacks_country = f.find('div',{'class':'info'}).find('p').find('span',{'class':'country'}).text.strip()
print(""{:<5}{:<15}: {:<90}: {}, {}\n "".format(str(i)+')',hacks_final_date, hacks_name.title(), hacks_city, hacks_country))",14,14
,"class Solution:
def solve(self, board: List[List[str]]) -> None:
ROWS, COLS = len(board), len(board[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def capture():
q = deque()
for r in range(ROWS):
for c in range(COLS):
if (r == 0 or r == ROWS - 1 or
c == 0 or c == COLS - 1 and
board[r][c] == ""O""
):
q.append((r, c))
while q:
r, c = q.popleft()
if board[r][c] == ""O"":
board[r][c] = ""T""
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < ROWS and 0 <= nc < COLS:
q.append((nr, nc))
capture()
for r in range(ROWS):
for c in range(COLS):
if board[r][c] == ""O"":
board[r][c] = ""X""
elif board[r][c] == ""T"":
board[r][c] = ""O""",0.0,GFG,,python,"class Solution:
def solve(self, board: List[List[str]]) -> None:
ROWS, COLS = len(board), len(board[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
def capture():
q = deque()
for r in range(ROWS):
for c in range(COLS):
if (r == 0 or r == ROWS - 1 or
c == 0 or c == COLS - 1 and
board[r][c] == ""O""
):
q.append((r, c))
while q:
r, c = q.popleft()
if board[r][c] == ""O"":
board[r][c] = ""T""
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < ROWS and 0 <= nc < COLS:
q.append((nr, nc))
capture()
for r in range(ROWS):
for c in range(COLS):
if board[r][c] == ""O"":
board[r][c] = ""X""
elif board[r][c] == ""T"":
board[r][c] = ""O""",30,30
,"import heapq
def minMeetingRooms(intervals):
if not intervals:
return 0
intervals.sort(key=lambda x: x[0])
heap = []
for start, end in intervals:
if heap and heap[0] <= start:
heapq.heappop(heap)
heapq.heappush(heap, end)
return len(heap)
",1.0,GPT,"Solve the problem ""Meeting Rooms II"".
Given an array of meeting time intervals where intervals[i] = [start, end],
return the minimum number of conference rooms required.",python,"import heapq
def minMeetingRooms(intervals):
if not intervals:
return 0
intervals.sort(key=lambda x: x[0])
heap = []
for start, end in intervals:
if heap and heap[0] <= start:
heapq.heappop(heap)
heapq.heappush(heap, end)
return len(heap)",15,15
,"import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.*;
@Mojo(name = ""generate-props"", defaultPhase = LifecyclePhase.GENERATE_RESOURCES)
public class PropertiesGeneratorMojo extends AbstractMojo {
@Parameter(defaultValue = ""${project.build.directory}"")
private String outputDirectory;
public void execute() throws MojoExecutionException {
getLog().info(""Generating properties file..."");
// Generate properties logic here
getLog().info(""Properties file generated successfully"");
}
}
",1.0,PERPLEXITY,Write a basic Maven plugin MOJO class that generates a properties file.,java,"import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.*;
@Mojo(name = ""generate-props"", defaultPhase = LifecyclePhase.GENERATE_RESOURCES)
public class PropertiesGeneratorMojo extends AbstractMojo {
@Parameter(defaultValue = ""${project.build.directory}"")
private String outputDirectory;
public void execute() throws MojoExecutionException {
getLog().info(""Generating properties file..."");
// Generate properties logic here
getLog().info(""Properties file generated successfully"");
}
}",14,14
,"class Solution {
int maxF=0;
List<Integer> maxSumArr = new ArrayList<>();
Map<Integer, Integer> f = new HashMap<>();
public int[] findFrequentTreeSum(TreeNode root) {
solve(root);
int[] arr = new int[maxSumArr.size()];
for(int i=0; i<arr.length; i++){
arr[i] = maxSumArr.get(i);
}
return arr;
}
public int solve(TreeNode root){
if(root == null) return 0;
int sum = root.val + solve(root.left) + solve(root.right);
f.put(sum , f.getOrDefault(sum, 0) + 1);
if(f.get(sum) > maxF){
maxSumArr.clear();
maxSumArr.add(sum);
maxF = f.get(sum);
}else if(f.get(sum) == maxF){
maxSumArr.add(sum);
}
return sum;
}
}",0.0,leetcode,,java,"class Solution {
int maxF=0;
List<Integer> maxSumArr = new ArrayList<>();
Map<Integer, Integer> f = new HashMap<>();
public int[] findFrequentTreeSum(TreeNode root) {
solve(root);
int[] arr = new int[maxSumArr.size()];
for(int i=0; i<arr.length; i++){
arr[i] = maxSumArr.get(i);
}
return arr;
}
public int solve(TreeNode root){
if(root == null) return 0;
int sum = root.val + solve(root.left) + solve(root.right);
f.put(sum , f.getOrDefault(sum, 0) + 1);
if(f.get(sum) > maxF){
maxSumArr.clear();
maxSumArr.add(sum);
maxF = f.get(sum);
}else if(f.get(sum) == maxF){
maxSumArr.add(sum);
}
return sum;
}
}",32,32
,"import numpy as np
x = [1., 2., 3., 4.]
print(""Original array:"")
print(x)
print(""Largest integer smaller or equal to the division of the inputs:"")
print(np.floor_divide(x, 1.5))
",0.0,W3RESOURCE,,python,"import numpy as np
x = [1., 2., 3., 4.]
print(""Original array:"")
print(x)
print(""Largest integer smaller or equal to the division of the inputs:"")
print(np.floor_divide(x, 1.5))",6,6
,"import json
with open('states.json') as f:
state_data= json.load(f)
for state in state_data['states']:
del state['area_codes']
with open('new_states.json', 'w') as f:
json.dump(state_data, f, indent=2)
",0.0,WE3RESOURCE,,python,"import json
with open('states.json') as f:
state_data= json.load(f)
for state in state_data['states']:
del state['area_codes']
with open('new_states.json', 'w') as f:
json.dump(state_data, f, indent=2)",10,10
,"import java.util.Arrays;
public class AnagramDetector {
public static boolean areAnagrams(String s1, String s2) {
s1 = s1.toLowerCase().replaceAll(""\\s"", """");
s2 = s2.toLowerCase().replaceAll(""\\s"", """");
if (s1.length() != s2.length()) return false;
char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray();
Arrays.sort(a1); Arrays.sort(a2);
return Arrays.equals(a1, a2);
}
}
",1.0,PERPLEXITY,"Create a Java function to detect if two strings are anagrams, ignoring case and spaces.",java,"import java.util.Arrays;
public class AnagramDetector {
public static boolean areAnagrams(String s1, String s2) {
s1 = s1.toLowerCase().replaceAll(""\\s"", """");
s2 = s2.toLowerCase().replaceAll(""\\s"", """");
if (s1.length() != s2.length()) return false;
char[] a1 = s1.toCharArray(); char[] a2 = s2.toCharArray();
Arrays.sort(a1); Arrays.sort(a2);
return Arrays.equals(a1, a2);
}
}",11,11
,"public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
slow = head;
while(slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
}",0.0,leetcode,,java,"public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if(slow == fast) {
slow = head;
while(slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
return null;
}
}",22,22
,"class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
l, r = 1, max(piles)
res = r
while l <= r:
k = (l + r) // 2
totalTime = 0
for p in piles:
totalTime += math.ceil(float(p) / k)
if totalTime <= h:
res = k
r = k - 1
else:
l = k + 1
return res",0.0,GFG,,python,"class Solution:
def minEatingSpeed(self, piles: List[int], h: int) -> int:
l, r = 1, max(piles)
res = r
while l <= r:
k = (l + r) // 2
totalTime = 0
for p in piles:
totalTime += math.ceil(float(p) / k)
if totalTime <= h:
res = k
r = k - 1
else:
l = k + 1
return res",17,17
,"import numpy as np
dt = [('name', 'U20'), ('height', 'f4'), ('class', 'i4')]
data = np.array([('Alice', 165, 2), ('Bob', 170.5, 1), ('Charlie', 168.2, 2), ('David', 172, 1), ('Eve', 160.4, 3)], dtype=dt)
print(np.sort(data, order=['class', 'height']))",1.0,DEEPAI,"Write a NumPy program to create a structured array from given student name, height, class and their data types. Now sort by class, then height if class are equal.",python,"import numpy as np
dt = [('name', 'U20'), ('height', 'f4'), ('class', 'i4')]
data = np.array([('Alice', 165, 2), ('Bob', 170.5, 1), ('Charlie', 168.2, 2), ('David', 172, 1), ('Eve', 160.4, 3)], dtype=dt)
print(np.sort(data, order=['class', 'height']))",5,5
,"# Define a function named 'perfect_number' that checks if a number 'n' is a perfect number
def perfect_number(n):
# Initialize a variable 'sum' to store the sum of factors of 'n'
sum = 0
# Iterate through numbers from 1 to 'n-1' using 'x' as the iterator
for x in range(1, n):
# Check if 'x' is a factor of 'n' (divides 'n' without remainder)
if n % x == 0:
# If 'x' is a factor of 'n', add it to the 'sum'
sum += x
# Check if the 'sum' of factors is equal to the original number 'n'
return sum == n
# Print the result of checking if 6 is a perfect number by calling the 'perfect_number' function
print(perfect_number(6))",0.0,W3RESOURCE,,python,"# Define a function named 'perfect_number' that checks if a number 'n' is a perfect number
def perfect_number(n):
# Initialize a variable 'sum' to store the sum of factors of 'n'
sum = 0
# Iterate through numbers from 1 to 'n-1' using 'x' as the iterator
for x in range(1, n):
# Check if 'x' is a factor of 'n' (divides 'n' without remainder)
if n % x == 0:
# If 'x' is a factor of 'n', add it to the 'sum'
sum += x
# Check if the 'sum' of factors is equal to the original number 'n'
return sum == n
# Print the result of checking if 6 is a perfect number by calling the 'perfect_number' function
print(perfect_number(6))",17,17
,"import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
public class RetryExecutor {
private final int maxAttempts;
private final Duration initialDelay;
private final Duration maxDelay;
private final double backoffMultiplier;
private final Predicate<Exception> retryPredicate;
private RetryExecutor(Builder builder) {
this.maxAttempts = builder.maxAttempts;
this.initialDelay = builder.initialDelay;
this.maxDelay = builder.maxDelay;
this.backoffMultiplier = builder.backoffMultiplier;
this.retryPredicate = builder.retryPredicate;
}
public <T> T execute(Callable<T> task) throws Exception {
Exception lastException = null;
Duration currentDelay = initialDelay;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return task.call();
} catch (Exception e) {
lastException = e;
if (attempt == maxAttempts || !shouldRetry(e)) {
throw e;
}
if (attempt < maxAttempts) {
sleepWithJitter(currentDelay);
currentDelay = calculateNextDelay(currentDelay);
}
}
}
throw lastException;
}
private boolean shouldRetry(Exception e) {
return retryPredicate == null || retryPredicate.test(e);
}
private void sleepWithJitter(Duration delay) {
try {
long jitter = ThreadLocalRandom.current().nextLong(
(long) (delay.toMillis() * 0.1)
);
Thread.sleep(delay.toMillis() + jitter);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(""Retry interrupted"", e);
}
}
private Duration calculateNextDelay(Duration currentDelay) {
long nextDelayMillis = (long) (currentDelay.toMillis() * backoffMultiplier);
if (nextDelayMillis > maxDelay.toMillis()) {
nextDelayMillis = maxDelay.toMillis();
}
return Duration.ofMillis(nextDelayMillis);
}
public static class Builder {
private int maxAttempts = 3;
private Duration initialDelay = Duration.ofMillis(100);
private Duration maxDelay = Duration.ofSeconds(30);
private double backoffMultiplier = 2.0;
private Predicate<Exception> retryPredicate;
public Builder maxAttempts(int maxAttempts) {
this.maxAttempts = maxAttempts;
return this;
}
public Builder initialDelay(Duration initialDelay) {
this.initialDelay = initialDelay;
return this;
}
public Builder maxDelay(Duration maxDelay) {
this.maxDelay = maxDelay;
return this;
}
public Builder backoffMultiplier(double backoffMultiplier) {
this.backoffMultiplier = backoffMultiplier;
return this;
}
public Builder retryOn(Predicate<Exception> retryPredicate) {
this.retryPredicate = retryPredicate;
return this;
}
public RetryExecutor build() {
return new RetryExecutor(this);
}
}
}",1.0,DEEPSEEK,Create a retry mechanism that handles transient failures with exponential backoff.,java,"import java.time.Duration;
import java.util.concurrent.Callable;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
public class RetryExecutor {
private final int maxAttempts;
private final Duration initialDelay;
private final Duration maxDelay;
private final double backoffMultiplier;
private final Predicate<Exception> retryPredicate;
private RetryExecutor(Builder builder) {
this.maxAttempts = builder.maxAttempts;
this.initialDelay = builder.initialDelay;
this.maxDelay = builder.maxDelay;
this.backoffMultiplier = builder.backoffMultiplier;
this.retryPredicate = builder.retryPredicate;
}
public <T> T execute(Callable<T> task) throws Exception {
Exception lastException = null;
Duration currentDelay = initialDelay;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return task.call();
} catch (Exception e) {
lastException = e;
if (attempt == maxAttempts || !shouldRetry(e)) {
throw e;
}
if (attempt < maxAttempts) {
sleepWithJitter(currentDelay);
currentDelay = calculateNextDelay(currentDelay);
}
}
}
throw lastException;
}
private boolean shouldRetry(Exception e) {
return retryPredicate == null || retryPredicate.test(e);
}
private void sleepWithJitter(Duration delay) {
try {
... truncated ...
Thread.currentThread().interrupt();
throw new RuntimeException(""Retry interrupted"", e);
}
}
private Duration calculateNextDelay(Duration currentDelay) {
long nextDelayMillis = (long) (currentDelay.toMillis() * backoffMultiplier);
if (nextDelayMillis > maxDelay.toMillis()) {
nextDelayMillis = maxDelay.toMillis();
}
return Duration.ofMillis(nextDelayMillis);
}
public static class Builder {
private int maxAttempts = 3;
private Duration initialDelay = Duration.ofMillis(100);
private Duration maxDelay = Duration.ofSeconds(30);
private double backoffMultiplier = 2.0;
private Predicate<Exception> retryPredicate;
public Builder maxAttempts(int maxAttempts) {
this.maxAttempts = maxAttempts;
return this;
}
public Builder initialDelay(Duration initialDelay) {
this.initialDelay = initialDelay;
return this;
}
public Builder maxDelay(Duration maxDelay) {
this.maxDelay = maxDelay;
return this;
}
public Builder backoffMultiplier(double backoffMultiplier) {
this.backoffMultiplier = backoffMultiplier;
return this;
}
public Builder retryOn(Predicate<Exception> retryPredicate) {
this.retryPredicate = retryPredicate;
return this;
}
public RetryExecutor build() {
return new RetryExecutor(this);
}
}
}",105,101
,"def sum_numbers(numbers):
return sum(numbers)
print(sum_numbers([8, 2, 3, 0, 7])) # Output: 20
",1.0,PERPLEXITY,"Write a Python function to sum all the numbers in a list.
Sample List : (8, 2, 3, 0, 7)
Expected Output : 20",python,"def sum_numbers(numbers):
return sum(numbers)
print(sum_numbers([8, 2, 3, 0, 7])) # Output: 20",4,4
,"static boolean match(String s,String p){
boolean[][] d=new boolean[s.length()+1][p.length()+1];
d[0][0]=true;
for(int j=2;j<=p.length();j++)
if(p.charAt(j-1)=='*') d[0][j]=d[0][j-2];
for(int i=1;i<=s.length();i++)
for(int j=1;j<=p.length();j++)
if(p.charAt(j-1)=='*')
d[i][j]=d[i][j-2]||(d[i-1][j]&&(p.charAt(j-2)=='.'||p.charAt(j-2)==s.charAt(i-1)));
else
d[i][j]=d[i-1][j-1]&&(p.charAt(j-1)=='.'||p.charAt(j-1)==s.charAt(i-1));
return d[s.length()][p.length()];
}
",1.0,GPT,write a java program to Implement regex matcher with . and *. ,java,"static boolean match(String s,String p){
boolean[][] d=new boolean[s.length()+1][p.length()+1];
d[0][0]=true;
for(int j=2;j<=p.length();j++)
if(p.charAt(j-1)=='*') d[0][j]=d[0][j-2];
for(int i=1;i<=s.length();i++)
for(int j=1;j<=p.length();j++)
if(p.charAt(j-1)=='*')
d[i][j]=d[i][j-2]||(d[i-1][j]&&(p.charAt(j-2)=='.'||p.charAt(j-2)==s.charAt(i-1)));
else
d[i][j]=d[i-1][j-1]&&(p.charAt(j-1)=='.'||p.charAt(j-1)==s.charAt(i-1));
return d[s.length()][p.length()];
}",13,13
,"import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class SlidingWindowRateLimiter {
private final int maxRequests;
private final long windowMillis;
private final ConcurrentHashMap<String, Window> userWindows;
private static class Window {
final ConcurrentLinkedQueue<Long> timestamps;
final AtomicInteger currentRequests;
Window() {
this.timestamps = new ConcurrentLinkedQueue<>();
this.currentRequests = new AtomicInteger(0);
}
}
public SlidingWindowRateLimiter(int maxRequests, long windowDuration, TimeUnit timeUnit) {
this.maxRequests = maxRequests;
this.windowMillis = timeUnit.toMillis(windowDuration);
this.userWindows = new ConcurrentHashMap<>();
}
public boolean allowRequest(String userId) {
Window window = userWindows.computeIfAbsent(userId, k -> new Window());
long currentTime = System.currentTimeMillis();
long cutoffTime = currentTime - windowMillis;
// Clean old timestamps
while (!window.timestamps.isEmpty() &&
window.timestamps.peek() < cutoffTime) {
window.timestamps.poll();
window.currentRequests.decrementAndGet();
}
// Check if under limit
if (window.currentRequests.get() >= maxRequests) {
return false;
}
// Add new request
window.timestamps.offer(currentTime);
window.currentRequests.incrementAndGet();
return true;
}
public void reset(String userId) {
userWindows.remove(userId);
}
}",1.0,DEEPSEEK,Create a rate limiter that allows N requests per minute with sliding window algorithm.,java,"import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class SlidingWindowRateLimiter {
private final int maxRequests;
private final long windowMillis;
private final ConcurrentHashMap<String, Window> userWindows;
private static class Window {
final ConcurrentLinkedQueue<Long> timestamps;
final AtomicInteger currentRequests;
Window() {
this.timestamps = new ConcurrentLinkedQueue<>();
this.currentRequests = new AtomicInteger(0);
}
}
public SlidingWindowRateLimiter(int maxRequests, long windowDuration, TimeUnit timeUnit) {
this.maxRequests = maxRequests;
this.windowMillis = timeUnit.toMillis(windowDuration);
this.userWindows = new ConcurrentHashMap<>();
}
public boolean allowRequest(String userId) {
Window window = userWindows.computeIfAbsent(userId, k -> new Window());
long currentTime = System.currentTimeMillis();
long cutoffTime = currentTime - windowMillis;
// Clean old timestamps
while (!window.timestamps.isEmpty() &&
window.timestamps.peek() < cutoffTime) {
window.timestamps.poll();
window.currentRequests.decrementAndGet();
}
// Check if under limit
if (window.currentRequests.get() >= maxRequests) {
return false;
}
// Add new request
window.timestamps.offer(currentTime);
window.currentRequests.incrementAndGet();
return true;
}
public void reset(String userId) {
userWindows.remove(userId);
}
}",53,53
,"# Define a function named 'test' that takes a parameter 'a'
def test(a):
# Define a nested function 'add' that takes a parameter 'b'
def add(b):
# Declare 'a' from the outer scope as nonlocal to modify its value
nonlocal a
# Increment the value of 'a' by 1
a += 1
# Return the sum of 'a' (modified by the nonlocal statement) and 'b'
return a + b
# Return the inner function 'add' and its scope is retained due to closure
return add
# Call the 'test' function with an argument '4' and assign the returned function to 'func'
func = test(4)
# Call the function 'func' with argument '4' and print the result
print(func(4)) ",0.0,W3RESOURCE,,python,"# Define a function named 'test' that takes a parameter 'a'
def test(a):
# Define a nested function 'add' that takes a parameter 'b'
def add(b):
# Declare 'a' from the outer scope as nonlocal to modify its value
nonlocal a
# Increment the value of 'a' by 1
a += 1
# Return the sum of 'a' (modified by the nonlocal statement) and 'b'
return a + b
# Return the inner function 'add' and its scope is retained due to closure
return add
# Call the 'test' function with an argument '4' and assign the returned function to 'func'
func = test(4)
# Call the function 'func' with argument '4' and print the result
print(func(4)) ",21,21
,"class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
k = len(nums) - k
def quickSelect(l, r):
pivot, p = nums[r], l
for i in range(l, r):
if nums[i] <= pivot:
nums[p], nums[i] = nums[i], nums[p]
p += 1
nums[p], nums[r] = nums[r], nums[p]
if p > k:
return quickSelect(l, p - 1)
elif p < k:
return quickSelect(p + 1, r)
else:
return nums[p]
return quickSelect(0, len(nums) - 1)",0.0,GFG,,python,"class Solution:
def findKthLargest(self, nums: List[int], k: int) -> int:
k = len(nums) - k
def quickSelect(l, r):
pivot, p = nums[r], l
for i in range(l, r):
if nums[i] <= pivot:
nums[p], nums[i] = nums[i], nums[p]
p += 1
nums[p], nums[r] = nums[r], nums[p]
if p > k:
return quickSelect(l, p - 1)
elif p < k:
return quickSelect(p + 1, r)
else:
return nums[p]
return quickSelect(0, len(nums) - 1)",21,21
,"def canJump(nums):
max_reach = 0
for i, n in enumerate(nums):
if i > max_reach:
return False
max_reach = max(max_reach, i + n)
return True
",1.0,GPT,"Solve the problem ""Jump Game"".
Given an array nums where nums[i] represents maximum jump length,
return true if you can reach the last index.",python,"def canJump(nums):
max_reach = 0
for i, n in enumerate(nums):
if i > max_reach:
return False
max_reach = max(max_reach, i + n)
return True",7,7
,"class Solution {
public Node cloneGraph(Node node) {
if (node == null) return null;
Map<Node, Node> copiedMap = new HashMap<>();
bfs(node, copiedMap);
return copiedMap.get(node);
}
private void bfs(Node startNode, Map<Node, Node> copiedMap) {
Queue<Node> queue = new ArrayDeque<>(); // include nodes that have been visited (copied) only
// check & copy node at Generation
copiedMap.put(startNode, new Node(startNode.val));
queue.offer(startNode);
while (!queue.isEmpty()) {
Node node = queue.poll();
// copy & link, add neighbors to Queue
for (Node neighbor: node.neighbors) {
// check & copy node at Generation
if (copiedMap.containsKey(neighbor)) { // neighbor is already visited (copied), just link
// IMPORTANT: DON'T JUST CONTINUE!
copiedMap.get(node).neighbors.add(copiedMap.get(neighbor));
} else { // copy, link, add neighbor to queue to be visited
copiedMap.put(neighbor, new Node(neighbor.val));
queue.offer(neighbor);
copiedMap.get(node).neighbors.add(copiedMap.get(neighbor));
}
}
}
}
}",0.0,leetcode,,java,"class Solution {
public Node cloneGraph(Node node) {
if (node == null) return null;
Map<Node, Node> copiedMap = new HashMap<>();
bfs(node, copiedMap);
return copiedMap.get(node);
}
private void bfs(Node startNode, Map<Node, Node> copiedMap) {
Queue<Node> queue = new ArrayDeque<>(); // include nodes that have been visited (copied) only
// check & copy node at Generation
copiedMap.put(startNode, new Node(startNode.val));
queue.offer(startNode);
while (!queue.isEmpty()) {
Node node = queue.poll();
// copy & link, add neighbors to Queue
for (Node neighbor: node.neighbors) {
// check & copy node at Generation
if (copiedMap.containsKey(neighbor)) { // neighbor is already visited (copied), just link
// IMPORTANT: DON'T JUST CONTINUE!
copiedMap.get(node).neighbors.add(copiedMap.get(neighbor));
} else { // copy, link, add neighbor to queue to be visited
copiedMap.put(neighbor, new Node(neighbor.val));
queue.offer(neighbor);
copiedMap.get(node).neighbors.add(copiedMap.get(neighbor));
}
}
}
}
}",34,34
|