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 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609
|
//******************************
// Written by Peter Golde
// Copyright (c) 2004-2007, Wintellect
//
// Use and restribution of this code is subject to the license agreement
// contained in the file "License.txt" accompanying this file.
//******************************
using System;
using System.Collections;
using System.Collections.Generic;
#pragma warning disable 419 // Ambigious cref in XML comment
// Everything should be CLS compliant.
[assembly: CLSCompliant(true)]
namespace Wintellect.PowerCollections
{
/// <summary>
/// The BinaryPredicate delegate type encapsulates a method that takes two
/// items of the same type, and returns a boolean value representating
/// some relationship between them. For example, checking whether two
/// items are equal or equivalent is one kind of binary predicate.
/// </summary>
/// <param name="item1">The first item.</param>
/// <param name="item2">The second item.</param>
/// <returns>Whether item1 and item2 satisfy the relationship that the BinaryPredicate defines.</returns>
public delegate bool BinaryPredicate<T>(T item1, T item2);
/// <summary>
/// Algorithms contains a number of static methods that implement
/// algorithms that work on collections. Most of the methods deal with
/// the standard generic collection interfaces such as IEnumerable<T>,
/// ICollection<T> and IList<T>.
/// </summary>
public static class Algorithms
{
#region Collection wrappers
/// <summary>
/// The class that is used to implement IList<T> to view a sub-range
/// of a list. The object stores a wrapped list, and a start/count indicating
/// a sub-range of the list. Insertion/deletions through the sub-range view
/// cause the count to change also; insertions and deletions directly on
/// the wrapped list do not.
/// </summary>
[Serializable]
private class ListRange<T> : ListBase<T>, ICollection<T>
{
private readonly IList<T> wrappedList;
private readonly int start;
private int count;
/// <summary>
/// Create a sub-range view object on the indicate part
/// of the list.
/// </summary>
/// <param name="wrappedList">List to wrap.</param>
/// <param name="start">The start index of the view in the wrapped list.</param>
/// <param name="count">The number of items in the view.</param>
public ListRange(IList<T> wrappedList, int start, int count)
{
this.wrappedList = wrappedList;
this.start = start;
this.count = count;
}
public override int Count
{
get {
return Math.Min(count, wrappedList.Count - start);
}
}
public override void Clear()
{
if (wrappedList.Count - start < count)
count = wrappedList.Count - start;
while (count > 0) {
wrappedList.RemoveAt(start + count - 1);
--count;
}
}
public override void Insert(int index, T item)
{
if (index < 0 || index > count)
throw new ArgumentOutOfRangeException("index");
wrappedList.Insert(start + index, item);
++count;
}
public override void RemoveAt(int index)
{
if (index < 0 || index >= count)
throw new ArgumentOutOfRangeException("index");
wrappedList.RemoveAt(start + index);
--count;
}
public override bool Remove(T item)
{
if (wrappedList.IsReadOnly)
throw new NotSupportedException(string.Format(Strings.CannotModifyCollection, "Range"));
else
return base.Remove(item);
}
public override T this[int index]
{
get
{
if (index < 0 || index >= count)
throw new ArgumentOutOfRangeException("index");
return wrappedList[start + index];
}
set
{
if (index < 0 || index >= count)
throw new ArgumentOutOfRangeException("index");
wrappedList[start + index] = value;
}
}
bool ICollection<T>.IsReadOnly
{
get
{
return wrappedList.IsReadOnly;
}
}
}
/// <summary>
/// Returns a view onto a sub-range of a list. Items from <paramref name="list"/> are not copied; the
/// returned IList<T> is simply a different view onto the same underlying items. Changes to <paramref name="list"/>
/// are reflected in the view, and vice versa. Insertions and deletions in the view change the size of the
/// view, but insertions and deletions in the underlying list do not.
/// </summary>
/// <remarks>This method can be used to apply an algorithm to a portion of a list. For example:
/// <code>Algorithms.ReverseInPlace(Algorithms.Range(list, 3, 6))</code>
/// will reverse the 6 items beginning at index 3.</remarks>
/// <typeparam name="T">The type of the items in the list.</typeparam>
/// <param name="list">The list to view.</param>
/// <param name="start">The starting index of the view.</param>
/// <param name="count">The number of items in the view.</param>
/// <returns>A list that is a view onto the given sub-list. </returns>
/// <exception cref="ArgumentNullException"><paramref name="list"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> or <paramref name="count"/> is negative.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> + <paramref name="count"/> is greater than the
/// size of <paramref name="list"/>.</exception>
public static IList<T> Range<T>(IList<T> list, int start, int count)
{
if (list == null)
throw new ArgumentOutOfRangeException("list");
if (start < 0 || start > list.Count || (start == list.Count && count != 0))
throw new ArgumentOutOfRangeException("start");
if (count < 0 || count > list.Count || count + start > list.Count)
throw new ArgumentOutOfRangeException("count");
return new ListRange<T>(list, start, count);
}
/// <summary>
/// The class that is used to implement IList<T> to view a sub-range
/// of an array. The object stores a wrapped array, and a start/count indicating
/// a sub-range of the array. Insertion/deletions through the sub-range view
/// cause the count to change up to the size of the underlying array. Elements
/// fall off the end of the underlying array.
/// </summary>
[Serializable]
private class ArrayRange<T> : ListBase<T>
{
private readonly T[] wrappedArray;
private readonly int start;
private int count;
/// <summary>
/// Create a sub-range view object on the indicate part
/// of the array.
/// </summary>
/// <param name="wrappedArray">Array to wrap.</param>
/// <param name="start">The start index of the view in the wrapped list.</param>
/// <param name="count">The number of items in the view.</param>
public ArrayRange(T[] wrappedArray, int start, int count)
{
this.wrappedArray = wrappedArray;
this.start = start;
this.count = count;
}
public override int Count
{
get
{
return count;
}
}
public override void Clear()
{
Array.Copy(wrappedArray, start + count, wrappedArray, start, wrappedArray.Length - (start + count));
Algorithms.FillRange(wrappedArray, wrappedArray.Length - count, count, default(T));
count = 0;
}
public override void Insert(int index, T item)
{
if (index < 0 || index > count)
throw new ArgumentOutOfRangeException("index");
int i = start + index;
if (i + 1 < wrappedArray.Length)
Array.Copy(wrappedArray, i, wrappedArray, i + 1, wrappedArray.Length - i - 1);
if (i < wrappedArray.Length)
wrappedArray[i] = item;
if (start + count < wrappedArray.Length)
++count;
}
public override void RemoveAt(int index)
{
if (index < 0 || index >= count)
throw new ArgumentOutOfRangeException("index");
int i = start + index;
if (i < wrappedArray.Length - 1)
Array.Copy(wrappedArray, i + 1, wrappedArray, i, wrappedArray.Length - i - 1);
wrappedArray[wrappedArray.Length - 1] = default(T);
--count;
}
public override T this[int index]
{
get
{
if (index < 0 || index >= count)
throw new ArgumentOutOfRangeException("index");
return wrappedArray[start + index];
}
set
{
if (index < 0 || index >= count)
throw new ArgumentOutOfRangeException("index");
wrappedArray[start + index] = value;
}
}
}
/// <summary>
/// Returns a view onto a sub-range of an array. Items from <paramref name="array"/> are not copied; the
/// returned IList<T> is simply a different view onto the same underlying items. Changes to <paramref name="array"/>
/// are reflected in the view, and vice versa. Insertions and deletions in the view change the size of the
/// view. After an insertion, the last item in <paramref name="array"/> "falls off the end". After a deletion, the
/// last item in array becomes the default value (0 or null).
/// </summary>
/// <remarks>This method can be used to apply an algorithm to a portion of a array. For example:
/// <code>Algorithms.ReverseInPlace(Algorithms.Range(array, 3, 6))</code>
/// will reverse the 6 items beginning at index 3.</remarks>
/// <param name="array">The array to view.</param>
/// <param name="start">The starting index of the view.</param>
/// <param name="count">The number of items in the view.</param>
/// <returns>A list that is a view onto the given sub-array. </returns>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> or <paramref name="count"/> is negative.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> + <paramref name="count"/> is greater than the
/// size of <paramref name="array"/>.</exception>
public static IList<T> Range<T>(T[] array, int start, int count)
{
if (array == null)
throw new ArgumentOutOfRangeException("array");
if (start < 0 || start > array.Length || (start == array.Length && count != 0))
throw new ArgumentOutOfRangeException("start");
if (count < 0 || count > array.Length || count + start > array.Length)
throw new ArgumentOutOfRangeException("count");
return new ArrayRange<T>(array, start, count);
}
/// <summary>
/// The read-only ICollection<T> implementation that is used by the ReadOnly method.
/// Methods that modify the collection throw a NotSupportedException, methods that don't
/// modify are fowarded through to the wrapped collection.
/// </summary>
[Serializable]
private class ReadOnlyCollection<T> : ICollection<T>
{
private readonly ICollection<T> wrappedCollection; // The collection we are wrapping (never null).
/// <summary>
/// Create a ReadOnlyCollection wrapped around the given collection.
/// </summary>
/// <param name="wrappedCollection">Collection to wrap.</param>
public ReadOnlyCollection(ICollection<T> wrappedCollection)
{
this.wrappedCollection = wrappedCollection;
}
/// <summary>
/// Throws an NotSupportedException stating that this collection cannot be modified.
/// </summary>
private static void MethodModifiesCollection()
{
throw new NotSupportedException(string.Format(Strings.CannotModifyCollection, "read-only collection"));
}
public IEnumerator<T> GetEnumerator()
{ return wrappedCollection.GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator()
{ return ((IEnumerable)wrappedCollection).GetEnumerator(); }
public bool Contains(T item)
{ return wrappedCollection.Contains(item); }
public void CopyTo(T[] array, int arrayIndex)
{ wrappedCollection.CopyTo(array, arrayIndex); }
public int Count
{
get { return wrappedCollection.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public void Add(T item)
{ MethodModifiesCollection(); }
public void Clear()
{ MethodModifiesCollection(); }
public bool Remove(T item)
{ MethodModifiesCollection(); return false; }
}
/// <summary>
/// Returns a read-only view onto a collection. The returned ICollection<T> interface
/// only allows operations that do not change the collection: GetEnumerator, Contains, CopyTo,
/// Count. The ReadOnly property returns false, indicating that the collection is read-only. All other
/// methods on the interface throw a NotSupportedException.
/// </summary>
/// <remarks>The data in the underlying collection is not copied. If the underlying
/// collection is changed, then the read-only view also changes accordingly.</remarks>
/// <typeparam name="T">The type of items in the collection.</typeparam>
/// <param name="collection">The collection to wrap.</param>
/// <returns>A read-only view onto <paramref name="collection"/>. If <paramref name="collection"/> is null, then null is returned.</returns>
public static ICollection<T> ReadOnly<T>(ICollection<T> collection)
{
if (collection == null)
return null;
else
return new ReadOnlyCollection<T>(collection);
}
/// <summary>
/// The read-only IList<T> implementation that is used by the ReadOnly method.
/// Methods that modify the list throw a NotSupportedException, methods that don't
/// modify are fowarded through to the wrapped list.
/// </summary>
[Serializable]
private class ReadOnlyList<T> : IList<T>
{
private readonly IList<T> wrappedList; // The list we are wrapping (never null).
/// <summary>
/// Create a ReadOnlyList wrapped around the given list.
/// </summary>
/// <param name="wrappedList">List to wrap.</param>
public ReadOnlyList(IList<T> wrappedList)
{
this.wrappedList = wrappedList;
}
/// <summary>
/// Throws an NotSupportedException stating that this collection cannot be modified.
/// </summary>
private static void MethodModifiesCollection()
{
throw new NotSupportedException(string.Format(Strings.CannotModifyCollection, "read-only list"));
}
public IEnumerator<T> GetEnumerator()
{ return wrappedList.GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator()
{ return ((IEnumerable)wrappedList).GetEnumerator(); }
public int IndexOf(T item)
{ return wrappedList.IndexOf(item); }
public bool Contains(T item)
{ return wrappedList.Contains(item); }
public void CopyTo(T[] array, int arrayIndex)
{ wrappedList.CopyTo(array, arrayIndex); }
public int Count
{
get { return wrappedList.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public T this[int index]
{
get { return wrappedList[index]; }
set { MethodModifiesCollection(); }
}
public void Add(T item)
{ MethodModifiesCollection(); }
public void Clear()
{ MethodModifiesCollection(); }
public void Insert(int index, T item)
{ MethodModifiesCollection(); }
public void RemoveAt(int index)
{ MethodModifiesCollection(); }
public bool Remove(T item)
{ MethodModifiesCollection(); return false; }
}
/// <summary>
/// Returns a read-only view onto a list. The returned IList<T> interface
/// only allows operations that do not change the list: GetEnumerator, Contains, CopyTo,
/// Count, IndexOf, and the get accessor of the indexer.
/// The IsReadOnly property returns true, indicating that the list is read-only. All other
/// methods on the interface throw a NotSupportedException.
/// </summary>
/// <remarks>The data in the underlying list is not copied. If the underlying
/// list is changed, then the read-only view also changes accordingly.</remarks>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to wrap.</param>
/// <returns>A read-only view onto <paramref name="list"/>. Returns null if <paramref name="list"/> is null.
/// If <paramref name="list"/> is already read-only, returns <paramref name="list"/>.</returns>
public static IList<T> ReadOnly<T>(IList<T> list)
{
if (list == null)
return null;
else if (list.IsReadOnly)
return list;
else
return new ReadOnlyList<T>(list);
}
/// <summary>
/// The private class that implements a read-only wrapped for
/// IDictionary <TKey,TValue>.
/// </summary>
[Serializable]
private class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
// The dictionary that is wrapped
private readonly IDictionary<TKey, TValue> wrappedDictionary;
/// <summary>
/// Create a read-only dictionary wrapped around the given dictionary.
/// </summary>
/// <param name="wrappedDictionary">The IDictionary<TKey,TValue> to wrap.</param>
public ReadOnlyDictionary(IDictionary<TKey, TValue> wrappedDictionary)
{
this.wrappedDictionary = wrappedDictionary;
}
/// <summary>
/// Throws an NotSupportedException stating that this collection cannot be modified.
/// </summary>
private static void MethodModifiesCollection()
{
throw new NotSupportedException(string.Format(Strings.CannotModifyCollection, "read-only dictionary"));
}
public void Add(TKey key, TValue value)
{ MethodModifiesCollection(); }
public bool ContainsKey(TKey key)
{ return wrappedDictionary.ContainsKey(key); }
public ICollection<TKey> Keys
{
get { return ReadOnly(wrappedDictionary.Keys); }
}
public ICollection<TValue> Values
{
get { return ReadOnly(wrappedDictionary.Values); }
}
public bool Remove(TKey key)
{
MethodModifiesCollection();
return false; // never reached
}
public bool TryGetValue(TKey key, out TValue value)
{ return wrappedDictionary.TryGetValue(key, out value); }
public TValue this[TKey key]
{
get { return wrappedDictionary[key];}
set { MethodModifiesCollection(); }
}
public void Add(KeyValuePair<TKey, TValue> item)
{ MethodModifiesCollection(); }
public void Clear()
{ MethodModifiesCollection(); }
public bool Contains(KeyValuePair<TKey, TValue> item)
{ return wrappedDictionary.Contains(item); }
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{ wrappedDictionary.CopyTo(array, arrayIndex); }
public int Count
{
get { return wrappedDictionary.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
MethodModifiesCollection();
return false; // never reached
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{ return wrappedDictionary.GetEnumerator(); }
IEnumerator IEnumerable.GetEnumerator()
{ return ((IEnumerable)wrappedDictionary).GetEnumerator(); }
}
/// <summary>
/// Returns a read-only view onto a dictionary. The returned IDictionary<TKey,TValue> interface
/// only allows operations that do not change the dictionary.
/// The IsReadOnly property returns true, indicating that the dictionary is read-only. All other
/// methods on the interface throw a NotSupportedException.
/// </summary>
/// <remarks>The data in the underlying dictionary is not copied. If the underlying
/// dictionary is changed, then the read-only view also changes accordingly.</remarks>
/// <param name="dictionary">The dictionary to wrap.</param>
/// <returns>A read-only view onto <paramref name="dictionary"/>. Returns null if <paramref name="dictionary"/> is null.
/// If <paramref name="dictionary"/> is already read-only, returns <paramref name="dictionary"/>.</returns>
public static IDictionary<TKey,TValue> ReadOnly<TKey,TValue>(IDictionary<TKey,TValue> dictionary)
{
if (dictionary == null)
return null;
else if (dictionary.IsReadOnly)
return dictionary;
else
return new ReadOnlyDictionary<TKey,TValue>(dictionary);
}
/// <summary>
/// The class that provides a typed IEnumerator<T>
/// view onto an untyped IEnumerator interface.
/// </summary>
[Serializable]
private class TypedEnumerator<T> : IEnumerator<T>
{
private readonly IEnumerator wrappedEnumerator;
/// <summary>
/// Create a typed IEnumerator<T>
/// view onto an untyped IEnumerator interface
/// </summary>
/// <param name="wrappedEnumerator">IEnumerator to wrap.</param>
public TypedEnumerator(IEnumerator wrappedEnumerator)
{
this.wrappedEnumerator = wrappedEnumerator;
}
T IEnumerator<T>.Current
{
get { return (T) wrappedEnumerator.Current; }
}
void IDisposable.Dispose()
{
if (wrappedEnumerator is IDisposable)
((IDisposable)wrappedEnumerator).Dispose();
}
object IEnumerator.Current
{
get { return wrappedEnumerator.Current; }
}
bool IEnumerator.MoveNext()
{
return wrappedEnumerator.MoveNext();
}
void IEnumerator.Reset()
{
wrappedEnumerator.Reset();
}
}
/// <summary>
/// The class that provides a typed IEnumerable<T> view
/// onto an untyped IEnumerable interface.
/// </summary>
[Serializable]
private class TypedEnumerable<T> : IEnumerable<T>
{
private readonly IEnumerable wrappedEnumerable;
/// <summary>
/// Create a typed IEnumerable<T> view
/// onto an untyped IEnumerable interface.
/// </summary>
/// <param name="wrappedEnumerable">IEnumerable interface to wrap.</param>
public TypedEnumerable(IEnumerable wrappedEnumerable)
{
this.wrappedEnumerable = wrappedEnumerable;
}
public IEnumerator<T> GetEnumerator()
{
return new TypedEnumerator<T>(wrappedEnumerable.GetEnumerator());
}
IEnumerator IEnumerable.GetEnumerator()
{
return wrappedEnumerable.GetEnumerator();
}
}
/// <summary>
/// Given a non-generic IEnumerable interface, wrap a generic IEnumerable<T>
/// interface around it. The generic interface will enumerate the same objects as the
/// underlying non-generic collection, but can be used in places that require a generic interface.
/// The underlying non-generic collection must contain only items that
/// are of type <typeparamref name="T"/> or a type derived from it. This method is useful
/// when interfacing older, non-generic collections to newer code that uses generic interfaces.
/// </summary>
/// <remarks>Some collections implement both generic and non-generic interfaces. For efficiency,
/// this method will first attempt to cast <paramref name="untypedCollection"/> to IEnumerable<T>.
/// If that succeeds, it is returned; otherwise, a wrapper object is created.</remarks>
/// <typeparam name="T">The item type of the wrapper collection.</typeparam>
/// <param name="untypedCollection">An untyped collection. This collection should only contain
/// items of type <typeparamref name="T"/> or a type derived from it. </param>
/// <returns>A generic IEnumerable<T> wrapper around <paramref name="untypedCollection"/>.
/// If <paramref name="untypedCollection"/> is null, then null is returned.</returns>
public static IEnumerable<T> TypedAs<T>(IEnumerable untypedCollection)
{
if (untypedCollection == null)
return null;
else if (untypedCollection is IEnumerable<T>)
return (IEnumerable<T>)untypedCollection;
else
return new TypedEnumerable<T>(untypedCollection);
}
/// <summary>
/// The class that provides a typed ICollection<T> view
/// onto an untyped ICollection interface. The ICollection<T>
/// is read-only.
/// </summary>
[Serializable]
private class TypedCollection<T> : ICollection<T>
{
private readonly ICollection wrappedCollection;
/// <summary>
/// Create a typed ICollection<T> view
/// onto an untyped ICollection interface.
/// </summary>
/// <param name="wrappedCollection">ICollection interface to wrap.</param>
public TypedCollection(ICollection wrappedCollection)
{
this.wrappedCollection = wrappedCollection;
}
/// <summary>
/// Throws an NotSupportedException stating that this collection cannot be modified.
/// </summary>
private static void MethodModifiesCollection()
{
throw new NotSupportedException(string.Format(Strings.CannotModifyCollection, "strongly-typed Collection"));
}
public void Add(T item)
{ MethodModifiesCollection(); }
public void Clear()
{ MethodModifiesCollection(); }
public bool Remove(T item)
{ MethodModifiesCollection(); return false; }
public bool Contains(T item)
{
IEqualityComparer<T> equalityComparer = EqualityComparer<T>.Default;
foreach (object obj in wrappedCollection) {
if (obj is T && equalityComparer.Equals(item, (T)obj))
return true;
}
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{ wrappedCollection.CopyTo(array, arrayIndex); }
public int Count
{
get { return wrappedCollection.Count; }
}
public bool IsReadOnly
{
get { return true; }
}
public IEnumerator<T> GetEnumerator()
{ return new TypedEnumerator<T>(wrappedCollection.GetEnumerator()); }
IEnumerator IEnumerable.GetEnumerator()
{ return wrappedCollection.GetEnumerator(); }
}
/// <summary>
/// Given a non-generic ICollection interface, wrap a generic ICollection<T>
/// interface around it. The generic interface will enumerate the same objects as the
/// underlying non-generic collection, but can be used in places that require a generic interface.
/// The underlying non-generic collection must contain only items that
/// are of type <typeparamref name="T"/> or a type derived from it. This method is useful
/// when interfacing older, non-generic collections to newer code that uses generic interfaces.
/// </summary>
/// <remarks><para>Some collections implement both generic and non-generic interfaces. For efficiency,
/// this method will first attempt to cast <paramref name="untypedCollection"/> to ICollection<T>.
/// If that succeeds, it is returned; otherwise, a wrapper object is created.</para>
/// <para>Unlike the generic interface, the non-generic ICollection interfaces does
/// not contain methods for adding or removing items from the collection. For this reason,
/// the returned ICollection<T> will be read-only.</para></remarks>
/// <typeparam name="T">The item type of the wrapper collection.</typeparam>
/// <param name="untypedCollection">An untyped collection. This collection should only contain
/// items of type <typeparamref name="T"/> or a type derived from it. </param>
/// <returns>A generic ICollection<T> wrapper around <paramref name="untypedCollection"/>.
/// If <paramref name="untypedCollection"/> is null, then null is returned.</returns>
public static ICollection<T> TypedAs<T>(ICollection untypedCollection)
{
if (untypedCollection == null)
return null;
else if (untypedCollection is ICollection<T>)
return (ICollection<T>) untypedCollection;
else
return new TypedCollection<T>(untypedCollection);
}
/// <summary>
/// The class used to create a typed IList<T> view onto
/// an untype IList interface.
/// </summary>
[Serializable]
private class TypedList<T> : IList<T>
{
private readonly IList wrappedList;
/// <summary>
/// Create a typed IList<T> view onto
/// an untype IList interface.
/// </summary>
/// <param name="wrappedList">The IList to wrap.</param>
public TypedList(IList wrappedList)
{
this.wrappedList = wrappedList;
}
public IEnumerator<T> GetEnumerator()
{ return new TypedEnumerator<T>(wrappedList.GetEnumerator()); }
IEnumerator IEnumerable.GetEnumerator()
{ return wrappedList.GetEnumerator(); }
public int IndexOf(T item)
{ return wrappedList.IndexOf(item); }
public void Insert(int index, T item)
{ wrappedList.Insert(index, item); }
public void RemoveAt(int index)
{ wrappedList.RemoveAt(index); }
public void Add(T item)
{ wrappedList.Add(item); }
public void Clear()
{ wrappedList.Clear(); }
public bool Contains(T item)
{ return wrappedList.Contains(item); }
public void CopyTo(T[] array, int arrayIndex)
{ wrappedList.CopyTo(array, arrayIndex); }
public T this[int index]
{
get { return (T)wrappedList[index]; }
set { wrappedList[index] = value; }
}
public int Count
{
get { return wrappedList.Count ; }
}
public bool IsReadOnly
{
get { return wrappedList.IsReadOnly; }
}
public bool Remove(T item)
{
if (wrappedList.Contains(item)) {
wrappedList.Remove(item);
return true;
}
else {
return false;
}
}
}
/// <summary>
/// Given a non-generic IList interface, wrap a generic IList<T>
/// interface around it. The generic interface will enumerate the same objects as the
/// underlying non-generic list, but can be used in places that require a generic interface.
/// The underlying non-generic list must contain only items that
/// are of type <typeparamref name="T"/> or a type derived from it. This method is useful
/// when interfacing older, non-generic lists to newer code that uses generic interfaces.
/// </summary>
/// <remarks>Some collections implement both generic and non-generic interfaces. For efficiency,
/// this method will first attempt to cast <paramref name="untypedList"/> to IList<T>.
/// If that succeeds, it is returned; otherwise, a wrapper object is created.</remarks>
/// <typeparam name="T">The item type of the wrapper list.</typeparam>
/// <param name="untypedList">An untyped list. This list should only contain
/// items of type <typeparamref name="T"/> or a type derived from it. </param>
/// <returns>A generic IList<T> wrapper around <paramref name="untypedList"/>.
/// If <paramref name="untypedList"/> is null, then null is returned.</returns>
public static IList<T> TypedAs<T>(IList untypedList)
{
if (untypedList == null)
return null;
else if (untypedList is IList<T>)
return (IList<T>)untypedList;
else
return new TypedList<T>(untypedList);
}
/// <summary>
/// The class that is used to provide an untyped ICollection
/// view onto a typed ICollection<T> interface.
/// </summary>
[Serializable]
private class UntypedCollection<T> : ICollection
{
private readonly ICollection<T> wrappedCollection;
/// <summary>
/// Create an untyped ICollection
/// view onto a typed ICollection<T> interface.
/// </summary>
/// <param name="wrappedCollection">The ICollection<T> to wrap.</param>
public UntypedCollection(ICollection<T> wrappedCollection)
{
this.wrappedCollection = wrappedCollection;
}
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
int i = 0;
int count = wrappedCollection.Count;
if (index < 0)
throw new ArgumentOutOfRangeException("index", index, Strings.ArgMustNotBeNegative);
if (index >= array.Length || count > array.Length - index)
throw new ArgumentException("index", Strings.ArrayTooSmall);
foreach (T item in wrappedCollection) {
if (i >= count)
break;
array.SetValue(item, index);
++index;
++i;
}
}
public int Count
{
get { return wrappedCollection.Count; }
}
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { return this; }
}
public IEnumerator GetEnumerator()
{
return ((IEnumerable)wrappedCollection).GetEnumerator();
}
}
/// <summary>
/// Given a generic ICollection<T> interface, wrap a non-generic (untyped)
/// ICollection interface around it. The non-generic interface will contain the same objects as the
/// underlying generic collection, but can be used in places that require a non-generic interface.
/// This method is useful when interfacing generic interfaces with older code that uses non-generic interfaces.
/// </summary>
/// <remarks>Many generic collections already implement the non-generic interfaces directly. This
/// method will first attempt to simply cast <paramref name="typedCollection"/> to ICollection. If that
/// succeeds, it is returned; if it fails, then a wrapper object is created.</remarks>
/// <typeparam name="T">The item type of the underlying collection.</typeparam>
/// <param name="typedCollection">A typed collection to wrap.</param>
/// <returns>A non-generic ICollection wrapper around <paramref name="typedCollection"/>.
/// If <paramref name="typedCollection"/> is null, then null is returned.</returns>
public static ICollection Untyped<T>(ICollection<T> typedCollection)
{
if (typedCollection == null)
return null;
else if (typedCollection is ICollection)
return (ICollection)typedCollection;
else
return new UntypedCollection<T>(typedCollection);
}
/// <summary>
/// The class that implements a non-generic IList wrapper
/// around a generic IList<T> interface.
/// </summary>
[Serializable]
private class UntypedList<T> : IList
{
private readonly IList<T> wrappedList;
/// <summary>
/// Create a non-generic IList wrapper
/// around a generic IList<T> interface.
/// </summary>
/// <param name="wrappedList">The IList<T> interface to wrap.</param>
public UntypedList(IList<T> wrappedList)
{
this.wrappedList = wrappedList;
}
/// <summary>
/// Convert the given parameter to T. Throw an ArgumentException
/// if it isn't.
/// </summary>
/// <param name="name">parameter name</param>
/// <param name="value">parameter value</param>
private static T ConvertToItemType(string name, object value)
{
try {
return (T)value;
}
catch (InvalidCastException) {
throw new ArgumentException(string.Format(Strings.WrongType, value, typeof(T)), name);
}
}
public int Add(object value)
{
// We assume that Add always adds to the end. Is this true?
wrappedList.Add(ConvertToItemType("value", value));
return wrappedList.Count - 1;
}
public void Clear()
{ wrappedList.Clear(); }
public bool Contains(object value)
{
if (value is T)
return wrappedList.Contains((T)value);
else
return false;
}
public int IndexOf(object value)
{
if (value is T)
return wrappedList.IndexOf((T)value);
else
return -1;
}
public void Insert(int index, object value)
{ wrappedList.Insert(index, ConvertToItemType("value", value)); }
public bool IsFixedSize
{
get { return false; }
}
public bool IsReadOnly
{
get { return wrappedList.IsReadOnly; }
}
public void Remove(object value)
{
if (value is T)
wrappedList.Remove((T)value);
}
public void RemoveAt(int index)
{ wrappedList.RemoveAt(index);}
public object this[int index]
{
get { return wrappedList[index]; }
set { wrappedList[index] = ConvertToItemType("value", value); }
}
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException("array");
int i = 0;
int count = wrappedList.Count;
if (index < 0)
throw new ArgumentOutOfRangeException("index", index, Strings.ArgMustNotBeNegative);
if (index >= array.Length || count > array.Length - index)
throw new ArgumentException("index", Strings.ArrayTooSmall);
foreach (T item in wrappedList) {
if (i >= count)
break;
array.SetValue(item, index);
++index;
++i;
}
}
public int Count
{
get { return wrappedList.Count; }
}
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { return this; }
}
public IEnumerator GetEnumerator()
{ return ((IEnumerable)wrappedList).GetEnumerator(); }
}
/// <summary>
/// Given a generic IList<T> interface, wrap a non-generic (untyped)
/// IList interface around it. The non-generic interface will contain the same objects as the
/// underlying generic list, but can be used in places that require a non-generic interface.
/// This method is useful when interfacing generic interfaces with older code that uses non-generic interfaces.
/// </summary>
/// <remarks>Many generic collections already implement the non-generic interfaces directly. This
/// method will first attempt to simply cast <paramref name="typedList"/> to IList. If that
/// succeeds, it is returned; if it fails, then a wrapper object is created.</remarks>
/// <typeparam name="T">The item type of the underlying list.</typeparam>
/// <param name="typedList">A typed list to wrap.</param>
/// <returns>A non-generic IList wrapper around <paramref name="typedList"/>.
/// If <paramref name="typedList"/> is null, then null is returned.</returns>
public static IList Untyped<T>(IList<T> typedList)
{
if (typedList == null)
return null;
else if (typedList is IList)
return (IList)typedList;
else
return new UntypedList<T>(typedList);
}
/// <summary>
/// The class that is used to implement IList<T> to view an array
/// in a read-write way. Insertions cause the last item in the array
/// to fall off, deletions replace the last item with the default value.
/// </summary>
[Serializable]
private class ArrayWrapper<T> : ListBase<T>, IList
{
private readonly T[] wrappedArray;
/// <summary>
/// Create a list wrapper object on an array.
/// </summary>
/// <param name="wrappedArray">Array to wrap.</param>
public ArrayWrapper(T[] wrappedArray)
{
this.wrappedArray = wrappedArray;
}
public override int Count
{
get
{
return wrappedArray.Length;
}
}
public override void Clear()
{
int count = wrappedArray.Length;
for (int i = 0; i < count; ++i)
wrappedArray[i] = default(T);
}
public override void Insert(int index, T item)
{
if (index < 0 || index > wrappedArray.Length)
throw new ArgumentOutOfRangeException("index");
if (index + 1 < wrappedArray.Length)
Array.Copy(wrappedArray, index, wrappedArray, index + 1, wrappedArray.Length - index - 1);
if (index < wrappedArray.Length)
wrappedArray[index] = item;
}
public override void RemoveAt(int index)
{
if (index < 0 || index >= wrappedArray.Length)
throw new ArgumentOutOfRangeException("index");
if (index < wrappedArray.Length - 1)
Array.Copy(wrappedArray, index + 1, wrappedArray, index, wrappedArray.Length - index - 1);
wrappedArray[wrappedArray.Length - 1] = default(T);
}
public override T this[int index]
{
get
{
if (index < 0 || index >= wrappedArray.Length)
throw new ArgumentOutOfRangeException("index");
return wrappedArray[index];
}
set
{
if (index < 0 || index >= wrappedArray.Length)
throw new ArgumentOutOfRangeException("index");
wrappedArray[index] = value;
}
}
public override void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (array.Length < wrappedArray.Length)
throw new ArgumentException("array is too short", "array");
if (arrayIndex < 0 || arrayIndex >= array.Length)
throw new ArgumentOutOfRangeException("arrayIndex");
if (array.Length + arrayIndex < wrappedArray.Length)
throw new ArgumentOutOfRangeException("arrayIndex");
Array.Copy(wrappedArray, 0, array, arrayIndex, wrappedArray.Length);
}
public override IEnumerator<T> GetEnumerator()
{
return ((IList<T>)wrappedArray).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IList)wrappedArray).GetEnumerator();
}
/// <summary>
/// Return true, to indicate that the list is fixed size.
/// </summary>
bool IList.IsFixedSize
{
get
{
return true;
}
}
}
/// <summary>
/// <para>Creates a read-write IList<T> wrapper around an array. When an array is
/// implicitely converted to an IList<T>, changes to the items in the array cannot
/// be made through the interface. This method creates a read-write IList<T> wrapper
/// on an array that can be used to make changes to the array. </para>
/// <para>Use this method when you need to pass an array to an algorithms that takes an
/// IList<T> and that tries to modify items in the list. Algorithms in this class generally do not
/// need this method, since they have been design to operate on arrays even when they
/// are passed as an IList<T>.</para>
/// </summary>
/// <remarks>Since arrays cannot be resized, inserting an item causes the last item in the array to be automatically
/// removed. Removing an item causes the last item in the array to be replaced with a default value (0 or null). Clearing
/// the list causes all the items to be replaced with a default value.</remarks>
/// <param name="array">The array to wrap.</param>
/// <returns>An IList<T> wrapper onto <paramref name="array"/>.</returns>
public static IList<T> ReadWriteList<T>(T[] array)
{
if (array == null)
throw new ArgumentNullException("array");
return new ArrayWrapper<T>(array);
}
#endregion Collection wrappers
#region Replacing
/// <summary>
/// Replace all items in a collection equal to a particular value with another values, yielding another collection.
/// </summary>
/// <remarks>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</remarks>
/// <param name="collection">The collection to process.</param>
/// <param name="itemFind">The value to find and replace within <paramref name="collection"/>.</param>
/// <param name="replaceWith">The new value to replace with.</param>
/// <returns>An new collection with the items from <paramref name="collection"/>, in the same order,
/// with the appropriate replacements made.</returns>
public static IEnumerable<T> Replace<T>(IEnumerable<T> collection, T itemFind, T replaceWith)
{
return Replace(collection, itemFind, replaceWith, EqualityComparer<T>.Default);
}
/// <summary>
/// Replace all items in a collection equal to a particular value with another values, yielding another collection. A passed
/// IEqualityComparer is used to determine equality.
/// </summary>
/// <param name="collection">The collection to process.</param>
/// <param name="itemFind">The value to find and replace within <paramref name="collection"/>.</param>
/// <param name="replaceWith">The new value to replace with.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality. Only the Equals method will be called.</param>
/// <returns>An new collection with the items from <paramref name="collection"/>, in the same order,
/// with the appropriate replacements made.</returns>
public static IEnumerable<T> Replace<T>(IEnumerable<T> collection, T itemFind, T replaceWith, IEqualityComparer<T> equalityComparer)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
foreach (T item in collection) {
if (equalityComparer.Equals(item, itemFind))
yield return replaceWith;
else
yield return item;
}
}
/// <summary>
/// Replace all items in a collection that a predicate evalues at true with a value, yielding another collection. .
/// </summary>
/// <param name="collection">The collection to process.</param>
/// <param name="predicate">The predicate used to evaluate items with the collection. If the predicate returns true for a particular
/// item, the item is replaces with <paramref name="replaceWith"/>.</param>
/// <param name="replaceWith">The new value to replace with.</param>
/// <returns>An new collection with the items from <paramref name="collection"/>, in the same order,
/// with the appropriate replacements made.</returns>
public static IEnumerable<T> Replace<T>(IEnumerable<T> collection, Predicate<T> predicate, T replaceWith)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (predicate == null)
throw new ArgumentNullException("predicate");
foreach (T item in collection) {
if (predicate(item))
yield return replaceWith;
else
yield return item;
}
}
/// <summary>
/// Replace all items in a list or array equal to a particular value with another value. The replacement is done in-place, changing
/// the list.
/// </summary>
/// <remarks><para>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</para>
/// <para>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</para></remarks>
/// <param name="list">The list or array to process.</param>
/// <param name="itemFind">The value to find and replace within <paramtype name="T"/>.</param>
/// <param name="replaceWith">The new value to replace with.</param>
public static void ReplaceInPlace<T>(IList<T> list, T itemFind, T replaceWith)
{
ReplaceInPlace(list, itemFind, replaceWith, EqualityComparer<T>.Default);
}
/// <summary>
/// Replace all items in a list or array equal to a particular value with another values.
/// The replacement is done in-place, changing
/// the list. A passed IEqualityComparer is used to determine equality.
/// </summary>
/// <remarks>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</remarks>
/// <param name="list">The list or array to process.</param>
/// <param name="itemFind">The value to find and replace within <paramtype name="T"/>.</param>
/// <param name="replaceWith">The new value to replace with.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality. Only the Equals method will be called.</param>
public static void ReplaceInPlace<T>(IList<T> list, T itemFind, T replaceWith, IEqualityComparer<T> equalityComparer)
{
if (list == null)
throw new ArgumentNullException("list");
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
if (list is T[])
list = new ArrayWrapper<T>((T[])list);
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
int listCount = list.Count;
for (int index = 0; index < listCount; ++index) {
if (equalityComparer.Equals(list[index], itemFind))
list[index] = replaceWith;
}
}
/// <summary>
/// Replace all items in a list or array that a predicate evaluates at true with a value. The replacement is done in-place, changing
/// the list.
/// </summary>
/// <remarks>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</remarks>
/// <param name="list">The list or array to process.</param>
/// <param name="predicate">The predicate used to evaluate items with the collection. If the predicate returns true for a particular
/// item, the item is replaces with <paramref name="replaceWith"/>.</param>
/// <param name="replaceWith">The new value to replace with.</param>
public static void ReplaceInPlace<T>(IList<T> list, Predicate<T> predicate, T replaceWith)
{
if (list == null)
throw new ArgumentNullException("list");
if (predicate == null)
throw new ArgumentNullException("predicate");
if (list is T[])
list = new ArrayWrapper<T>((T[])list);
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
int listCount = list.Count;
for (int index = 0; index < listCount; ++index) {
if (predicate(list[index]))
list[index] = replaceWith;
}
}
#endregion Replacing
#region Consecutive items
/// <summary>
/// Remove consecutive equal items from a collection, yielding another collection. In each run of consecutive equal items
/// in the collection, all items after the first item in the run are removed.
/// </summary>
/// <remarks>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</remarks>
/// <param name="collection">The collection to process.</param>
/// <returns>An new collection with the items from <paramref name="collection"/>, in the same order,
/// with consecutive duplicates removed.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
public static IEnumerable<T> RemoveDuplicates<T>(IEnumerable<T> collection)
{
return RemoveDuplicates(collection, EqualityComparer<T>.Default);
}
/// <summary>
/// Remove consecutive equal items from a collection, yielding another collection. In each run of consecutive equal items
/// in the collection, all items after the first item in the run are removed. A passed
/// IEqualityComparer is used to determine equality.
/// </summary>
/// <param name="collection">The collection to process.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality. Only the Equals method will be called.</param>
/// <returns>An new collection with the items from <paramref name="collection"/>, in the same order,
/// with consecutive duplicates removed.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> or <paramref name="equalityComparer"/> is null.</exception>
public static IEnumerable<T> RemoveDuplicates<T>(IEnumerable<T> collection, IEqualityComparer<T> equalityComparer)
{
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
return RemoveDuplicates(collection, equalityComparer.Equals);
}
/// <summary>
/// Remove consecutive "equal" items from a collection, yielding another collection. In each run of consecutive equal items
/// in the collection, all items after the first item in the run are removed. The passed
/// BinaryPredicate is used to determine if two items are "equal".
/// </summary>
/// <remarks>Since an arbitrary BinaryPredicate is passed to this function, what is being removed need not be true equality. </remarks>
/// <param name="collection">The collection to process.</param>
/// <param name="predicate">The BinaryPredicate used to compare items for "equality". An item <c>current</c> is removed if <c>predicate(first, current)==true</c>, where
/// <c>first</c> is the first item in the group of "duplicate" items.</param>
/// <returns>An new collection with the items from <paramref name="collection"/>, in the same order,
/// with consecutive "duplicates" removed.</returns>
public static IEnumerable<T> RemoveDuplicates<T>(IEnumerable<T> collection, BinaryPredicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (predicate == null)
throw new ArgumentNullException("predicate");
T current = default(T);
bool atBeginning = true;
foreach (T item in collection) {
// Is the new item different from the current item?
if (atBeginning || !predicate(current, item)) {
current = item;
yield return item;
}
atBeginning = false;
}
}
/// <summary>
/// Remove consecutive equal items from a list or array. In each run of consecutive equal items
/// in the list, all items after the first item in the run are removed. The removal is done in-place, changing
/// the list.
/// </summary>
/// <remarks><para>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</para>
/// <para>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</para></remarks>
/// <param name="list">The list or array to process.</param>
public static void RemoveDuplicatesInPlace<T>(IList<T> list)
{
RemoveDuplicatesInPlace(list, EqualityComparer<T>.Default);
}
/// <summary>
/// Remove subsequent consecutive equal items from a list or array. In each run of consecutive equal items
/// in the list, all items after the first item in the run are removed.
/// The replacement is done in-place, changing
/// the list. A passed IEqualityComparer is used to determine equality.
/// </summary>
/// <remarks>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</remarks>
/// <param name="list">The list or array to process.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality. Only the Equals method will be called.</param>
public static void RemoveDuplicatesInPlace<T>(IList<T> list, IEqualityComparer<T> equalityComparer)
{
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
RemoveDuplicatesInPlace(list, equalityComparer.Equals);
}
/// <summary>
/// Remove consecutive "equal" items from a list or array. In each run of consecutive equal items
/// in the list, all items after the first item in the run are removed. The replacement is done in-place, changing
/// the list. The passed BinaryPredicate is used to determine if two items are "equal".
/// </summary>
/// <remarks><para>Since an arbitrary BinaryPredicate is passed to this function, what is being tested for need not be true equality. </para>
/// <para>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</para></remarks>
/// <param name="list">The list or array to process.</param>
/// <param name="predicate">The BinaryPredicate used to compare items for "equality". </param>
public static void RemoveDuplicatesInPlace<T>(IList<T> list, BinaryPredicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (predicate == null)
throw new ArgumentNullException("predicate");
if (list is T[])
list = new ArrayWrapper<T>((T[])list);
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
T current = default(T);
T item;
int i = -1, j = 0;
int listCount = list.Count;
// Remove duplicates, compressing items to lower in the list.
while (j < listCount) {
item = list[j];
if (i < 0 || !predicate(current, item)) {
current = item;
++i;
if (i != j)
list[i] = current;
}
++j;
}
++i;
if (i < listCount) {
// remove items from the end.
if (list is ArrayWrapper<T> || (list is IList && ((IList)list).IsFixedSize)) {
// An array or similar. Null out the last elements.
while (i < listCount)
list[i++] = default(T);
}
else {
// Normal list.
while (i < listCount) {
list.RemoveAt(listCount - 1);
--listCount;
}
}
}
}
/// <summary>
/// Finds the first occurence of <paramref name="count"/> consecutive equal items in the
/// list.
/// </summary>
/// <remarks>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</remarks>
/// <param name="list">The list to examine.</param>
/// <param name="count">The number of consecutive equal items to look for. The count must be at least 1.</param>
/// <returns>The index of the first item in the first run of <paramref name="count"/> consecutive equal items, or -1 if no such run exists..</returns>
public static int FirstConsecutiveEqual<T>(IList<T> list, int count)
{
return FirstConsecutiveEqual(list, count, EqualityComparer<T>.Default);
}
/// <summary>
/// Finds the first occurence of <paramref name="count"/> consecutive equal items in the
/// list. A passed IEqualityComparer is used to determine equality.
/// </summary>
/// <param name="list">The list to examine.</param>
/// <param name="count">The number of consecutive equal items to look for. The count must be at least 1.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality. Only the Equals method will be called.</param>
/// <returns>The index of the first item in the first run of <paramref name="count"/> consecutive equal items, or -1 if no such run exists.</returns>
public static int FirstConsecutiveEqual<T>(IList<T> list, int count, IEqualityComparer<T> equalityComparer)
{
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
return FirstConsecutiveEqual(list, count, equalityComparer.Equals);
}
/// <summary>
/// Finds the first occurence of <paramref name="count"/> consecutive "equal" items in the
/// list. The passed BinaryPredicate is used to determine if two items are "equal".
/// </summary>
/// <remarks>Since an arbitrary BinaryPredicate is passed to this function, what is being tested for need not be true equality. </remarks>
/// <param name="list">The list to examine.</param>
/// <param name="count">The number of consecutive equal items to look for. The count must be at least 1.</param>
/// <param name="predicate">The BinaryPredicate used to compare items for "equality". </param>
/// <returns>The index of the first item in the first run of <paramref name="count"/> consecutive equal items, or -1 if no such run exists.</returns>
public static int FirstConsecutiveEqual<T>(IList<T> list, int count, BinaryPredicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (predicate == null)
throw new ArgumentNullException("predicate");
if (count < 1)
throw new ArgumentOutOfRangeException("count");
int listCount = list.Count;
if (listCount < count)
return -1; // Can't find run longer than the list itself.
if (count == 1)
return 0; // Run of 1 must be the first item in the list.
int start = 0, index = 0;
T current = default(T);
int runLength = 0;
// Go through the list, looking for a run of the given length.
foreach (T item in list) {
if (index > 0 && predicate(current, item)) {
++runLength;
if (runLength >= count)
return start;
}
else {
current = item;
start = index;
runLength = 1;
}
++index;
}
return -1;
}
/// <summary>
/// Finds the first occurence of <paramref name="count"/> consecutive items in the
/// list for which a given predicate returns true.
/// </summary>
/// <param name="list">The list to examine.</param>
/// <param name="count">The number of consecutive items to look for. The count must be at least 1.</param>
/// <param name="predicate">The predicate used to test each item.</param>
/// <returns>The index of the first item in the first run of <paramref name="count"/> items where <paramref name="predicate"/>
/// returns true for all items in the run, or -1 if no such run exists.</returns>
public static int FirstConsecutiveWhere<T>(IList<T> list, int count, Predicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (predicate == null)
throw new ArgumentNullException("predicate");
if (count < 1)
throw new ArgumentOutOfRangeException("count");
int listCount = list.Count;
if (count > listCount)
return -1; // Can't find run longer than the list itself.
int index = 0, start = -1;
int runLength = 0;
// Scan the list in order, looking for the number of consecutive true items.
foreach (T item in list) {
if (predicate(item)) {
if (start < 0)
start = index;
++runLength;
if (runLength >= count)
return start;
}
else {
runLength = 0;
start = -1;
}
++index;
}
return -1;
}
#endregion Consecutive items
#region Find and SearchForSubsequence
/// <summary>
/// Finds the first item in a collection that satisfies the condition
/// defined by <paramref name="predicate"/>.
/// </summary>
/// <remarks>If the default value for T could be present in the collection, and
/// would be matched by the predicate, then this method is inappropriate, because
/// you cannot disguish whether the default value for T was actually present in the collection,
/// or no items matched the predicate. In this case, use TryFindFirstWhere.</remarks>
/// <param name="collection">The collection to search.</param>
/// <param name="predicate">A delegate that defined the condition to check for.</param>
/// <returns>The first item in the collection that matches the condition, or the default value for T (0 or null) if no
/// item that matches the condition is found.</returns>
/// <seealso cref="Algorithms.TryFindFirstWhere{T}"/>
public static T FindFirstWhere<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
T retval;
if (Algorithms.TryFindFirstWhere(collection, predicate, out retval))
return retval;
else
return default(T);
}
/// <summary>
/// Finds the first item in a collection that satisfies the condition
/// defined by <paramref name="predicate"/>.
/// </summary>
/// <param name="collection">The collection to search.</param>
/// <param name="predicate">A delegate that defined the condition to check for.</param>
/// <param name="foundItem">Outputs the first item in the collection that matches the condition, if the method returns true.</param>
/// <returns>True if an item satisfying the condition was found. False if no such item exists in the collection.</returns>
/// <seealso cref="FindFirstWhere{T}"/>
public static bool TryFindFirstWhere<T>(IEnumerable<T> collection, Predicate<T> predicate, out T foundItem)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (predicate == null)
throw new ArgumentNullException("predicate");
foreach (T item in collection) {
if (predicate(item)) {
foundItem = item;
return true;
}
}
// didn't find any item that matches.
foundItem = default(T);
return false;
}
/// <summary>
/// Finds the last item in a collection that satisfies the condition
/// defined by <paramref name="predicate"/>.
/// </summary>
/// <remarks><para>If the collection implements IList<T>, then the list is scanned in reverse until a
/// matching item is found. Otherwise, the entire collection is iterated in the forward direction.</para>
/// <para>If the default value for T could be present in the collection, and
/// would be matched by the predicate, then this method is inappropriate, because
/// you cannot disguish whether the default value for T was actually present in the collection,
/// or no items matched the predicate. In this case, use TryFindFirstWhere.</para></remarks>
/// <param name="collection">The collection to search.</param>
/// <param name="predicate">A delegate that defined the condition to check for.</param>
/// <returns>The last item in the collection that matches the condition, or the default value for T (0 or null) if no
/// item that matches the condition is found.</returns>
/// <seealso cref="TryFindLastWhere{T}"/>
public static T FindLastWhere<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
T retval;
if (Algorithms.TryFindLastWhere(collection, predicate, out retval))
return retval;
else
return default(T);
}
/// <summary>
/// Finds the last item in a collection that satisfies the condition
/// defined by <paramref name="predicate"/>.
/// </summary>
/// <remarks>If the collection implements IList<T>, then the list is scanned in reverse until a
/// matching item is found. Otherwise, the entire collection is iterated in the forward direction.</remarks>
/// <param name="collection">The collection to search.</param>
/// <param name="predicate">A delegate that defined the condition to check for.</param>
/// <param name="foundItem">Outputs the last item in the collection that matches the condition, if the method returns true.</param>
/// <returns>True if an item satisfying the condition was found. False if no such item exists in the collection.</returns>
/// <seealso cref="FindLastWhere{T}"/>
public static bool TryFindLastWhere<T>(IEnumerable<T> collection, Predicate<T> predicate, out T foundItem)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (predicate == null)
throw new ArgumentNullException("predicate");
IList<T> list = collection as IList<T>;
if (list != null) {
// If it's a list, we can iterate in reverse.
for (int index = list.Count - 1; index >= 0; --index) {
T item = list[index];
if (predicate(item)) {
foundItem = item;
return true;
}
}
// didn't find any item that matches.
foundItem = default(T);
return false;
}
else {
// Otherwise, iterate the whole thing and remember the last matching one.
bool found = false;
foundItem = default(T);
foreach (T item in collection) {
if (predicate(item)) {
foundItem = item;
found = true;
}
}
return found;
}
}
/// <summary>
/// Enumerates all the items in <paramref name="collection"/> that satisfy the condition defined
/// by <paramref name="predicate"/>.
/// </summary>
/// <param name="collection">The collection to check all the items in.</param>
/// <param name="predicate">A delegate that defines the condition to check for.</param>
/// <returns>An IEnumerable<T> that enumerates the items that satisfy the condition.</returns>
public static IEnumerable<T> FindWhere<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (predicate == null)
throw new ArgumentNullException("predicate");
foreach (T item in collection) {
if (predicate(item)) {
yield return item;
}
}
}
/// <summary>
/// Finds the index of the first item in a list that satisfies the condition
/// defined by <paramref name="predicate"/>.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="predicate">A delegate that defined the condition to check for.</param>
/// <returns>The index of the first item satisfying the condition. -1 if no such item exists in the list.</returns>
public static int FindFirstIndexWhere<T>(IList<T> list, Predicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (predicate == null)
throw new ArgumentNullException("predicate");
int index = 0;
foreach (T item in list) {
if (predicate(item)) {
return index;
}
++index;
}
// didn't find any item that matches.
return -1;
}
/// <summary>
/// Finds the index of the last item in a list that satisfies the condition
/// defined by <paramref name="predicate"/>.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="predicate">A delegate that defined the condition to check for.</param>
/// <returns>The index of the last item satisfying the condition. -1 if no such item exists in the list.</returns>
public static int FindLastIndexWhere<T>(IList<T> list, Predicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (predicate == null)
throw new ArgumentNullException("predicate");
for (int index = list.Count - 1; index >= 0; --index) {
if (predicate(list[index])) {
return index;
}
}
// didn't find any item that matches.
return -1;
}
/// <summary>
/// Enumerates the indices of all the items in <paramref name="list"/> that satisfy the condition defined
/// by <paramref name="predicate"/>.
/// </summary>
/// <param name="list">The list to check all the items in.</param>
/// <param name="predicate">A delegate that defines the condition to check for.</param>
/// <returns>An IEnumerable<T> that enumerates the indices of items that satisfy the condition.</returns>
public static IEnumerable<int> FindIndicesWhere<T>(IList<T> list, Predicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (predicate == null)
throw new ArgumentNullException("predicate");
int index = 0;
foreach (T item in list) {
if (predicate(item)) {
yield return index;
}
++index;
}
}
/// <summary>
/// Finds the index of the first item in a list equal to a given item.
/// </summary>
/// <remarks>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</remarks>
/// <param name="list">The list to search.</param>
/// <param name="item">The item to search for.</param>
/// <returns>The index of the first item equal to <paramref name="item"/>. -1 if no such item exists in the list.</returns>
public static int FirstIndexOf<T>(IList<T> list, T item)
{
return FirstIndexOf(list, item, EqualityComparer<T>.Default);
}
/// <summary>
/// Finds the index of the first item in a list equal to a given item. A passed
/// IEqualityComparer is used to determine equality.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="item">The item to search for.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality. Only the Equals method will be called.</param>
/// <returns>The index of the first item equal to <paramref name="item"/>. -1 if no such item exists in the list.</returns>
public static int FirstIndexOf<T>(IList<T> list, T item, IEqualityComparer<T> equalityComparer)
{
if (list == null)
throw new ArgumentNullException("list");
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
int index = 0;
foreach (T x in list) {
if (equalityComparer.Equals(x, item)) {
return index;
}
++index;
}
// didn't find any item that matches.
return -1;
}
/// <summary>
/// Finds the index of the last item in a list equal to a given item.
/// </summary>
/// <remarks>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</remarks>
/// <param name="list">The list to search.</param>
/// <param name="item">The item to search for.</param>
/// <returns>The index of the last item equal to <paramref name="item"/>. -1 if no such item exists in the list.</returns>
public static int LastIndexOf<T>(IList<T> list, T item)
{
return LastIndexOf(list, item, EqualityComparer<T>.Default);
}
/// <summary>
/// Finds the index of the last item in a list equal to a given item. A passed
/// IEqualityComparer is used to determine equality.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="item">The item to search for.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality. Only the Equals method will be called.</param>
/// <returns>The index of the last item equal to <paramref name="item"/>. -1 if no such item exists in the list.</returns>
public static int LastIndexOf<T>(IList<T> list, T item, IEqualityComparer<T> equalityComparer)
{
if (list == null)
throw new ArgumentNullException("list");
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
for (int index = list.Count - 1; index >= 0; --index) {
if (equalityComparer.Equals(list[index], item)) {
return index;
}
}
// didn't find any item that matches.
return -1;
}
/// <summary>
/// Enumerates the indices of all the items in a list equal to a given item.
/// </summary>
/// <remarks>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</remarks>
/// <param name="list">The list to search.</param>
/// <param name="item">The item to search for.</param>
/// <returns>An IEnumerable<T> that enumerates the indices of items equal to <paramref name="item"/>. </returns>
public static IEnumerable<int> IndicesOf<T>(IList<T> list, T item)
{
return IndicesOf(list, item, EqualityComparer<T>.Default);
}
/// <summary>
/// Enumerates the indices of all the items in a list equal to a given item. A passed
/// IEqualityComparer is used to determine equality.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="item">The item to search for.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality. Only the Equals method will be called.</param>
/// <returns>An IEnumerable<T> that enumerates the indices of items equal to <paramref name="item"/>. </returns>
public static IEnumerable<int> IndicesOf<T>(IList<T> list, T item, IEqualityComparer<T> equalityComparer)
{
if (list == null)
throw new ArgumentNullException("list");
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
int index = 0;
foreach (T x in list) {
if (equalityComparer.Equals(x, item)) {
yield return index;
}
++index;
}
}
/// <summary>
/// Finds the index of the first item in a list "equal" to one of several given items. The passed
/// BinaryPredicate is used to determine if two items are "equal".
/// </summary>
/// <remarks>Since an arbitrary BinaryPredicate is passed to this function, what is being removed need not be true equality. This methods finds
/// first item X which satisfies BinaryPredicate(X,Y), where Y is one of the items in <paramref name="itemsToLookFor"/></remarks>
/// <param name="list">The list to search.</param>
/// <param name="itemsToLookFor">The items to search for.</param>
/// <param name="predicate">The BinaryPredicate used to compare items for "equality". </param>
/// <returns>The index of the first item "equal" to any of the items in the collection <paramref name="itemsToLookFor"/>, using
/// <paramtype name="BinaryPredicate{T}"/> as the test for equality.
/// -1 if no such item exists in the list.</returns>
public static int FirstIndexOfMany<T>(IList<T> list, IEnumerable<T> itemsToLookFor, BinaryPredicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (itemsToLookFor == null)
throw new ArgumentNullException("itemsToLookFor");
if (predicate == null)
throw new ArgumentNullException("predicate");
// Scan the list for the items.
int index = 0;
foreach (T x in list) {
foreach (T y in itemsToLookFor) {
if (predicate(x, y)) {
return index;
}
}
++index;
}
// didn't find any item that matches.
return -1;
}
/// <summary>
/// Finds the index of the last item in a list "equal" to one of several given items. The passed
/// BinaryPredicate is used to determine if two items are "equal".
/// </summary>
/// <remarks>Since an arbitrary BinaryPredicate is passed to this function, what is being removed need not be true equality. This methods finds
/// last item X which satisfies BinaryPredicate(X,Y), where Y is one of the items in <paramref name="itemsToLookFor"/></remarks>
/// <param name="list">The list to search.</param>
/// <param name="itemsToLookFor">The items to search for.</param>
/// <param name="predicate">The BinaryPredicate used to compare items for "equality". </param>
/// <returns>The index of the last item "equal" to any of the items in the collection <paramref name="itemsToLookFor"/>, using
/// <paramtype name="BinaryPredicate"/> as the test for equality.
/// -1 if no such item exists in the list.</returns>
public static int LastIndexOfMany<T>(IList<T> list, IEnumerable<T> itemsToLookFor, BinaryPredicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (itemsToLookFor == null)
throw new ArgumentNullException("itemsToLookFor");
if (predicate == null)
throw new ArgumentNullException("predicate");
// Scan the list
for (int index = list.Count - 1; index >= 0; --index) {
foreach (T y in itemsToLookFor) {
if (predicate(list[index], y)) {
return index;
}
}
}
// didn't find any item that matches.
return -1;
}
/// <summary>
/// Enumerates the indices of all the items in a list equal to one of several given items. The passed
/// BinaryPredicate is used to determine if two items are "equal".
/// </summary>
/// <remarks>Since an arbitrary BinaryPredicate is passed to this function, what is being removed need not be true equality. This methods finds
/// last item X which satisfies BinaryPredicate(X,Y), where Y is one of the items in <paramref name="itemsToLookFor"/></remarks>
/// <param name="list">The list to search.</param>
/// <param name="itemsToLookFor">A collection of items to search for.</param>
/// <param name="predicate">The BinaryPredicate used to compare items for "equality". </param>
/// <returns>An IEnumerable<T> that enumerates the indices of items "equal" to any of the items
/// in the collection <paramref name="itemsToLookFor"/>, using
/// <paramtest name="BinaryPredicate"/> as the test for equality. </returns>
public static IEnumerable<int> IndicesOfMany<T>(IList<T> list, IEnumerable<T> itemsToLookFor, BinaryPredicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (itemsToLookFor == null)
throw new ArgumentNullException("itemsToLookFor");
if (predicate == null)
throw new ArgumentNullException("predicate");
// Scan the list for the items.
int index = 0;
foreach (T x in list) {
foreach (T y in itemsToLookFor) {
if (predicate(x, y)) {
yield return index;
}
}
++index;
}
}
/// <summary>
/// Searchs a list for a sub-sequence of items that match a particular pattern. A subsequence
/// of <paramref name="list"/> matches pattern at index i if list[i] is equal to the first item
/// in <paramref name="pattern"/>, list[i+1] is equal to the second item in <paramref name="pattern"/>,
/// and so forth for all the items in <paramref name="pattern"/>.
/// </summary>
/// <remarks>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</remarks>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <param name="pattern">The sequence of items to search for.</param>
/// <returns>The first index with <paramref name="list"/> that matches the items in <paramref name="pattern"/>.</returns>
public static int SearchForSubsequence<T>(IList<T> list, IEnumerable<T> pattern)
{
return SearchForSubsequence(list, pattern, EqualityComparer<T>.Default);
}
/// <summary>
/// Searchs a list for a sub-sequence of items that match a particular pattern. A subsequence
/// of <paramref name="list"/> matches pattern at index i if list[i] is "equal" to the first item
/// in <paramref name="pattern"/>, list[i+1] is "equal" to the second item in <paramref name="pattern"/>,
/// and so forth for all the items in <paramref name="pattern"/>. The passed
/// BinaryPredicate is used to determine if two items are "equal".
/// </summary>
/// <remarks>Since an arbitrary BinaryPredicate is passed to this function, what is being tested
/// for in the pattern need not be equality. </remarks>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <param name="pattern">The sequence of items to search for.</param>
/// <param name="predicate">The BinaryPredicate used to compare items for "equality". </param>
/// <returns>The first index with <paramref name="list"/> that matches the items in <paramref name="pattern"/>.</returns>
public static int SearchForSubsequence<T>(IList<T> list, IEnumerable<T> pattern, BinaryPredicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (pattern == null)
throw new ArgumentNullException("pattern");
if (predicate == null)
throw new ArgumentNullException("predicate");
// Put the pattern into an array for performance (don't keep allocating enumerators).
T[] patternArray = Algorithms.ToArray(pattern);
int listCount = list.Count, patternCount = patternArray.Length;
if (patternCount == 0)
return 0; // A zero-length pattern occurs anywhere.
if (listCount == 0)
return -1; // no room for a pattern;
for (int start = 0; start <= listCount - patternCount; ++start) {
for (int count = 0; count < patternCount; ++count) {
if (!predicate(list[start + count], patternArray[count]))
goto NOMATCH;
}
// Got through the whole pattern. We have a match.
return start;
NOMATCH:
/* no match found at start. */
;
}
// no match found anywhere.
return -1;
}
/// <summary>
/// Searchs a list for a sub-sequence of items that match a particular pattern. A subsequence
/// of <paramref name="list"/> matches pattern at index i if list[i] is equal to the first item
/// in <paramref name="pattern"/>, list[i+1] is equal to the second item in <paramref name="pattern"/>,
/// and so forth for all the items in <paramref name="pattern"/>. The passed
/// instance of IEqualityComparer<T> is used for determining if two items are equal.
/// </summary>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <param name="pattern">The sequence of items to search for.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality. Only the Equals method will be called.</param>
/// <returns>The first index with <paramref name="list"/> that matches the items in <paramref name="pattern"/>.</returns>
public static int SearchForSubsequence<T>(IList<T> list, IEnumerable<T> pattern, IEqualityComparer<T> equalityComparer)
{
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
return SearchForSubsequence(list, pattern, equalityComparer.Equals);
}
#endregion Find and SearchForSubsequence
#region Set operations (coded except EqualSets)
/// <summary>
/// Determines if one collection is a subset of another, considered as sets. The first set is a subset
/// of the second set if every item in the first set also occurs in the second set. If an item appears X times in the first set,
/// it must appear at least X times in the second set.
/// </summary>
/// <remarks>
/// <para>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</para>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the IsSubsetOf method on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection.</param>
/// <param name="collection2">The second collection.</param>
/// <returns>True if <paramref name="collection1"/> is a subset of <paramref name="collection2"/>, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static bool IsSubsetOf<T>(IEnumerable<T> collection1, IEnumerable<T> collection2)
{
return IsSubsetOf(collection1, collection2, EqualityComparer<T>.Default);
}
/// <summary>
/// Determines if one collection is a subset of another, considered as sets. The first set is a subset
/// of the second set if every item in the first set also occurs in the second set. If an item appears X times in the first set,
/// it must appear at least X times in the second set.
/// </summary>
/// <remarks>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the IsSubsetOf method on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection.</param>
/// <param name="collection2">The second collection.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality.</param>
/// <returns>True if <paramref name="collection1"/> is a subset of <paramref name="collection2"/>, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static bool IsSubsetOf<T>(IEnumerable<T> collection1, IEnumerable<T> collection2, IEqualityComparer<T> equalityComparer)
{
if (collection1 == null)
throw new ArgumentNullException("collection1");
if (collection2 == null)
throw new ArgumentNullException("collection2");
if (equalityComparer == null)
throw new ArgumentException("equalityComparer");
Bag<T> bag1 = new Bag<T>(collection1, equalityComparer);
Bag<T> bag2 = new Bag<T>(collection2, equalityComparer);
return bag2.IsSupersetOf(bag1);
}
/// <summary>
/// Determines if one collection is a proper subset of another, considered as sets. The first set is a proper subset
/// of the second set if every item in the first set also occurs in the second set, and the first set is strictly smaller than
/// the second set. If an item appears X times in the first set,
/// it must appear at least X times in the second set.
/// </summary>
/// <remarks>
/// <para>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</para>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the IsSubsetOf method on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection.</param>
/// <param name="collection2">The second collection.</param>
/// <returns>True if <paramref name="collection1"/> is a subset of <paramref name="collection2"/>, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static bool IsProperSubsetOf<T>(IEnumerable<T> collection1, IEnumerable<T> collection2)
{
return IsProperSubsetOf(collection1, collection2, EqualityComparer<T>.Default);
}
/// <summary>
/// Determines if one collection is a proper subset of another, considered as sets. The first set is a proper subset
/// of the second set if every item in the first set also occurs in the second set, and the first set is strictly smaller than
/// the second set. If an item appears X times in the first set,
/// it must appear at least X times in the second set.
/// </summary>
/// <remarks>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the IsSubsetOf method on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection.</param>
/// <param name="collection2">The second collection.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality.
/// Only the Equals and GetHashCode member functions of this interface are called.</param>
/// <returns>True if <paramref name="collection1"/> is a proper subset of <paramref name="collection2"/>, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static bool IsProperSubsetOf<T>(IEnumerable<T> collection1, IEnumerable<T> collection2, IEqualityComparer<T> equalityComparer)
{
if (collection1 == null)
throw new ArgumentNullException("collection1");
if (collection2 == null)
throw new ArgumentNullException("collection2");
if (equalityComparer == null)
throw new ArgumentException("equalityComparer");
Bag<T> bag1 = new Bag<T>(collection1, equalityComparer);
Bag<T> bag2 = new Bag<T>(collection2, equalityComparer);
return bag2.IsProperSupersetOf(bag1);
}
/// <summary>
/// Determines if two collections are equal, considered as sets. Two sets are equal if they
/// have have the same items, with order not being significant.
/// </summary>
/// <remarks>
/// <para>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</para>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the EqualTo method on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection.</param>
/// <param name="collection2">The second collection.</param>
/// <returns>True if <paramref name="collection1"/> are <paramref name="collection2"/> are equal, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static bool EqualSets<T>(IEnumerable<T> collection1, IEnumerable<T> collection2)
{
return EqualSets(collection1, collection2, EqualityComparer<T>.Default);
}
/// <summary>
/// Determines if two collections are equal, considered as sets. Two sets are equal if they
/// have have the same items, with order not being significant.
/// </summary>
/// <remarks>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the EqualTo method on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection.</param>
/// <param name="collection2">The second collection.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality.
/// Only the Equals and GetHashCode member functions of this interface are called.</param>
/// <returns>True if <paramref name="collection1"/> are <paramref name="collection2"/> are equal, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static bool EqualSets<T>(IEnumerable<T> collection1, IEnumerable<T> collection2, IEqualityComparer<T> equalityComparer)
{
if (collection1 == null)
throw new ArgumentNullException("collection1");
if (collection2 == null)
throw new ArgumentNullException("collection2");
if (equalityComparer == null)
throw new ArgumentException("equalityComparer");
Bag<T> bag1 = new Bag<T>(collection1, equalityComparer);
Bag<T> bag2 = new Bag<T>(collection2, equalityComparer);
return bag2.IsEqualTo(bag1);
}
/// <summary>
/// Computes the set-theoretic intersection of two collections. The intersection of two sets
/// is all items that appear in both of the sets. If an item appears X times in one set,
/// and Y times in the other set, the intersection contains the item Minimum(X,Y) times.
/// The source collections are not changed.
/// A new collection is created with the intersection of the collections; the order of the
/// items in this collection is undefined.
/// </summary>
/// <remarks>
/// <para>When equal items appear in both collections, the returned collection will include an arbitrary choice of one of the
/// two equal items.</para>
/// <para>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</para>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the Intersection or IntersectionWith methods on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection to intersect.</param>
/// <param name="collection2">The second collection to intersect.</param>
/// <returns>The intersection of the two collections, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static IEnumerable<T> SetIntersection<T>(IEnumerable<T> collection1, IEnumerable<T> collection2)
{
return SetIntersection(collection1, collection2, EqualityComparer<T>.Default);
}
/// <summary>
/// Computes the set-theoretic intersection of two collections. The intersection of two sets
/// is all items that appear in both of the sets. If an item appears X times in one set,
/// and Y times in the other set, the intersection contains the item Minimum(X,Y) times.
/// The source collections are not changed.
/// A new collection is created with the intersection of the collections; the order of the
/// items in this collection is undefined.
/// </summary>
/// <remarks>
/// <para>When equal items appear in both collections, the returned collection will include an arbitrary choice of one of the
/// two equal items.</para>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the Intersection or IntersectionWith methods on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection to intersect.</param>
/// <param name="collection2">The second collection to intersect.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality.
/// Only the Equals and GetHashCode member functions of this interface are called.</param>
/// <returns>The intersection of the two collections, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static IEnumerable<T> SetIntersection<T>(IEnumerable<T> collection1, IEnumerable<T> collection2, IEqualityComparer<T> equalityComparer)
{
if (collection1 == null)
throw new ArgumentNullException("collection1");
if (collection2 == null)
throw new ArgumentNullException("collection2");
if (equalityComparer == null)
throw new ArgumentException("equalityComparer");
Bag<T> bag1 = new Bag<T>(collection1, equalityComparer);
Bag<T> bag2 = new Bag<T>(collection2, equalityComparer);
return Util.CreateEnumerableWrapper(bag1.Intersection(bag2));
}
/// <summary>
/// Computes the set-theoretic union of two collections. The union of two sets
/// is all items that appear in either of the sets. If an item appears X times in one set,
/// and Y times in the other set, the union contains the item Maximum(X,Y) times.
/// The source collections are not changed.
/// A new collection is created with the union of the collections; the order of the
/// items in this collection is undefined.
/// </summary>
/// <remarks>
/// <para>When equal items appear in both collections, the returned collection will include an arbitrary choice of one of the
/// two equal items.</para>
/// <para>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</para>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the Union or UnionWith methods on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection to union.</param>
/// <param name="collection2">The second collection to union.</param>
/// <returns>The union of the two collections, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static IEnumerable<T> SetUnion<T>(IEnumerable<T> collection1, IEnumerable<T> collection2)
{
return SetUnion(collection1, collection2, EqualityComparer<T>.Default);
}
/// <summary>
/// Computes the set-theoretic union of two collections. The union of two sets
/// is all items that appear in either of the sets. If an item appears X times in one set,
/// and Y times in the other set, the union contains the item Maximum(X,Y) times.
/// The source collections are not changed.
/// A new collection is created with the union of the collections; the order of the
/// items in this collection is undefined.
/// </summary>
/// <remarks>
/// <para>When equal items appear in both collections, the returned collection will include an arbitrary choice of one of the
/// two equal items.</para>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the union or unionWith methods on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection to union.</param>
/// <param name="collection2">The second collection to union.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality.
/// Only the Equals and GetHashCode member functions of this interface are called.</param>
/// <returns>The union of the two collections, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static IEnumerable<T> SetUnion<T>(IEnumerable<T> collection1, IEnumerable<T> collection2, IEqualityComparer<T> equalityComparer)
{
if (collection1 == null)
throw new ArgumentNullException("collection1");
if (collection2 == null)
throw new ArgumentNullException("collection2");
if (equalityComparer == null)
throw new ArgumentException("equalityComparer");
Bag<T> bag1 = new Bag<T>(collection1, equalityComparer);
Bag<T> bag2 = new Bag<T>(collection2, equalityComparer);
if (bag1.Count > bag2.Count) {
bag1.UnionWith(bag2);
return Util.CreateEnumerableWrapper(bag1);
}
else {
bag2.UnionWith(bag1);
return Util.CreateEnumerableWrapper(bag2);
}
}
/// <summary>
/// Computes the set-theoretic difference of two collections. The difference of two sets
/// is all items that appear in the first set, but not in the second. If an item appears X times in the first set,
/// and Y times in the second set, the difference contains the item X - Y times (0 times if X < Y).
/// The source collections are not changed.
/// A new collection is created with the difference of the collections; the order of the
/// items in this collection is undefined.
/// </summary>
/// <remarks>
/// <para>When equal items appear in both collections, the returned collection will include an arbitrary choice of one of the
/// two equal items.</para>
/// <para>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</para>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the Difference or DifferenceWith methods on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection to difference.</param>
/// <param name="collection2">The second collection to difference.</param>
/// <returns>The difference of <paramref name="collection1"/> and <paramref name="collection2"/>, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static IEnumerable<T> SetDifference<T>(IEnumerable<T> collection1, IEnumerable<T> collection2)
{
return SetDifference(collection1, collection2, EqualityComparer<T>.Default);
}
/// <summary>
/// Computes the set-theoretic difference of two collections. The difference of two sets
/// is all items that appear in the first set, but not in the second. If an item appears X times in the first set,
/// and Y times in the second set, the difference contains the item X - Y times (0 times if X < Y).
/// The source collections are not changed.
/// A new collection is created with the difference of the collections; the order of the
/// items in this collection is undefined.
/// </summary>
/// <remarks>
/// <para>When equal items appear in both collections, the returned collection will include an arbitrary choice of one of the
/// two equal items.</para>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the difference or differenceWith methods on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection to difference.</param>
/// <param name="collection2">The second collection to difference.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality.
/// Only the Equals and GetHashCode member functions of this interface are called.</param>
/// <returns>The difference of <paramref name="collection1"/> and <paramref name="collection2"/>, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static IEnumerable<T> SetDifference<T>(IEnumerable<T> collection1, IEnumerable<T> collection2, IEqualityComparer<T> equalityComparer)
{
if (collection1 == null)
throw new ArgumentNullException("collection1");
if (collection2 == null)
throw new ArgumentNullException("collection2");
if (equalityComparer == null)
throw new ArgumentException("equalityComparer");
Bag<T> bag1 = new Bag<T>(collection1, equalityComparer);
Bag<T> bag2 = new Bag<T>(collection2, equalityComparer);
bag1.DifferenceWith(bag2);
return Util.CreateEnumerableWrapper(bag1);
}
/// <summary>
/// Computes the set-theoretic symmetric difference of two collections. The symmetric difference of two sets
/// is all items that appear in the one of the sets, but not in the other. If an item appears X times in the one set,
/// and Y times in the other set, the symmetric difference contains the item AbsoluteValue(X - Y) times.
/// The source collections are not changed.
/// A new collection is created with the symmetric difference of the collections; the order of the
/// items in this collection is undefined.
/// </summary>
/// <remarks>
/// <para>When equal items appear in both collections, the returned collection will include an arbitrary choice of one of the
/// two equal items.</para>
/// <para>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</para>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the SymmetricDifference or SymmetricDifferenceWith methods on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection to symmetric difference.</param>
/// <param name="collection2">The second collection to symmetric difference.</param>
/// <returns>The symmetric difference of <paramref name="collection1"/> and <paramref name="collection2"/>, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static IEnumerable<T> SetSymmetricDifference<T>(IEnumerable<T> collection1, IEnumerable<T> collection2)
{
return SetSymmetricDifference(collection1, collection2, EqualityComparer<T>.Default);
}
/// <summary>
/// Computes the set-theoretic symmetric difference of two collections. The symmetric difference of two sets
/// is all items that appear in the one of the sets, but not in the other. If an item appears X times in the one set,
/// and Y times in the other set, the symmetric difference contains the item AbsoluteValue(X - Y) times.
/// The source collections are not changed.
/// A new collection is created with the symmetric difference of the collections; the order of the
/// items in this collection is undefined.
/// </summary>
/// <remarks>
/// <para>When equal items appear in both collections, the returned collection will include an arbitrary choice of one of the
/// two equal items.</para>
/// <para>If both collections are Set, Bag, OrderedSet, or OrderedBag
/// collections, it is more efficient to use the symmetric difference or symmetric differenceWith methods on that class.</para>
/// </remarks>
/// <param name="collection1">The first collection to symmetric difference.</param>
/// <param name="collection2">The second collection to symmetric difference.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality.
/// Only the Equals and GetHashCode member functions of this interface are called.</param>
/// <returns>The symmetric difference of <paramref name="collection1"/> and <paramref name="collection2"/>, considered as sets.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/> or <paramref name="collection2"/> is null.</exception>
public static IEnumerable<T> SetSymmetricDifference<T>(IEnumerable<T> collection1, IEnumerable<T> collection2, IEqualityComparer<T> equalityComparer)
{
if (collection1 == null)
throw new ArgumentNullException("collection1");
if (collection2 == null)
throw new ArgumentNullException("collection2");
if (equalityComparer == null)
throw new ArgumentException("equalityComparer");
Bag<T> bag1 = new Bag<T>(collection1, equalityComparer);
Bag<T> bag2 = new Bag<T>(collection2, equalityComparer);
if (bag1.Count > bag2.Count) {
bag1.SymmetricDifferenceWith(bag2);
return Util.CreateEnumerableWrapper(bag1);
}
else {
bag2.SymmetricDifferenceWith(bag1);
return Util.CreateEnumerableWrapper(bag2);
}
}
/// <summary>
/// Computes the cartestian product of two collections: all possible pairs of items, with the first item taken from the first collection and
/// the second item taken from the second collection. If the first collection has N items, and the second collection has M items, the cartesian
/// product will have N * M pairs.
/// </summary>
/// <typeparam name="TFirst">The type of items in the first collection.</typeparam>
/// <typeparam name="TSecond">The type of items in the second collection.</typeparam>
/// <param name="first">The first collection.</param>
/// <param name="second">The second collection.</param>
/// <returns>An IEnumerable<Pair<TFirst, TSecond>> that enumerates the cartesian product of the two collections.</returns>
public static IEnumerable<Pair<TFirst, TSecond>> CartesianProduct<TFirst, TSecond>(IEnumerable<TFirst> first, IEnumerable<TSecond> second)
{
if (first == null)
throw new ArgumentNullException("first");
if (second == null)
throw new ArgumentNullException("second");
foreach (TFirst itemFirst in first)
foreach (TSecond itemSecond in second)
yield return new Pair<TFirst, TSecond>(itemFirst, itemSecond);
}
#endregion Set operations
#region String representations (not yet coded)
/// <summary>
/// Gets a string representation of the elements in the collection.
/// The string representation starts with "{", has a list of items separated
/// by commas (","), and ends with "}". Each item in the collection is
/// converted to a string by calling its ToString method (null is represented by "null").
/// Contained collections (except strings) are recursively converted to strings by this method.
/// </summary>
/// <param name="collection">A collection to get the string representation of.</param>
/// <returns>The string representation of the collection. If <paramref name="collection"/> is null, then the string "null" is returned.</returns>
public static string ToString<T>(IEnumerable<T> collection)
{
return ToString(collection, true, "{", ",", "}");
}
/// <summary>
/// Gets a string representation of the elements in the collection.
/// The string to used at the beginning and end, and to separate items,
/// and supplied by parameters. Each item in the collection is
/// converted to a string by calling its ToString method (null is represented by "null").
/// </summary>
/// <param name="collection">A collection to get the string representation of.</param>
/// <param name="recursive">If true, contained collections (except strings) are converted to strings by a recursive call to this method, instead
/// of by calling ToString.</param>
/// <param name="start">The string to appear at the beginning of the output string.</param>
/// <param name="separator">The string to appear between each item in the string.</param>
/// <param name="end">The string to appear at the end of the output string.</param>
/// <returns>The string representation of the collection. If <paramref name="collection"/> is null, then the string "null" is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="start"/>, <paramref name="separator"/>, or <paramref name="end"/>
/// is null.</exception>
public static string ToString<T>(IEnumerable<T> collection, bool recursive, string start, string separator, string end)
{
if (start == null)
throw new ArgumentNullException("start");
if (separator == null)
throw new ArgumentNullException("separator");
if (end == null)
throw new ArgumentNullException("end");
if (collection == null)
return "null";
bool firstItem = true;
System.Text.StringBuilder builder = new System.Text.StringBuilder();
builder.Append(start);
// Call ToString on each item and put it in.
foreach (T item in collection) {
if (!firstItem)
builder.Append(separator);
if (item == null)
builder.Append("null");
else if (recursive && item is IEnumerable && !(item is string))
builder.Append(Algorithms.ToString(Algorithms.TypedAs<object>((IEnumerable)item), recursive, start, separator, end));
else
builder.Append(item.ToString());
firstItem = false;
}
builder.Append(end);
return builder.ToString();
}
/// <summary>
/// Gets a string representation of the mappings in a dictionary.
/// The string representation starts with "{", has a list of mappings separated
/// by commas (", "), and ends with "}". Each mapping is represented
/// by "key->value". Each key and value in the dictionary is
/// converted to a string by calling its ToString method (null is represented by "null").
/// Contained collections (except strings) are recursively converted to strings by this method.
/// </summary>
/// <param name="dictionary">A dictionary to get the string representation of.</param>
/// <returns>The string representation of the collection, or "null"
/// if <paramref name="dictionary"/> is null.</returns>
public static string ToString<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
{
bool firstItem = true;
if (dictionary == null)
return "null";
System.Text.StringBuilder builder = new System.Text.StringBuilder();
builder.Append("{");
// Call ToString on each item and put it in.
foreach (KeyValuePair<TKey, TValue> pair in dictionary) {
if (!firstItem)
builder.Append(", ");
if (pair.Key == null)
builder.Append("null");
else if (pair.Key is IEnumerable && !(pair.Key is string))
builder.Append(Algorithms.ToString(Algorithms.TypedAs<object>((IEnumerable)pair.Key), true, "{", ",", "}"));
else
builder.Append(pair.Key.ToString());
builder.Append("->");
if (pair.Value == null)
builder.Append("null");
else if (pair.Value is IEnumerable && !(pair.Value is string))
builder.Append(Algorithms.ToString(Algorithms.TypedAs<object>((IEnumerable)pair.Value), true, "{", ",", "}"));
else
builder.Append(pair.Value.ToString());
firstItem = false;
}
builder.Append("}");
return builder.ToString();
}
#endregion String representations
#region Shuffles and Permutations
private static volatile Random myRandomGenerator;
/// <summary>
/// Return a private random number generator to use if the user
/// doesn't supply one.
/// </summary>
/// <returns>The private random number generator. Only one is ever created
/// and is always returned.</returns>
private static Random GetRandomGenerator()
{
if (myRandomGenerator == null) {
lock (typeof(Algorithms)) {
if (myRandomGenerator == null)
myRandomGenerator = new Random();
}
}
return myRandomGenerator;
}
/// <summary>
/// Randomly shuffles the items in a collection, yielding a new collection.
/// </summary>
/// <typeparam name="T">The type of the items in the collection.</typeparam>
/// <param name="collection">The collection to shuffle.</param>
/// <returns>An array with the same size and items as <paramref name="collection"/>, but the items in a randomly chosen order.</returns>
public static T[] RandomShuffle<T>(IEnumerable<T> collection)
{
return RandomShuffle(collection, GetRandomGenerator());
}
/// <summary>
/// Randomly shuffles the items in a collection, yielding a new collection.
/// </summary>
/// <typeparam name="T">The type of the items in the collection.</typeparam>
/// <param name="collection">The collection to shuffle.</param>
/// <param name="randomGenerator">The random number generator to use to select the random order.</param>
/// <returns>An array with the same size and items as <paramref name="collection"/>, but the items in a randomly chosen order.</returns>
public static T[] RandomShuffle<T>(IEnumerable<T> collection, Random randomGenerator)
{
// We have to copy all items anyway, and there isn't a way to produce the items
// on the fly that is linear. So copying to an array and shuffling it is an efficient as we can get.
if (collection == null)
throw new ArgumentNullException("collection");
if (randomGenerator == null)
throw new ArgumentNullException("randomGenerator");
T[] array = Algorithms.ToArray(collection);
int count = array.Length;
for (int i = count - 1; i >= 1; --i) {
// Pick an random number 0 through i inclusive.
int j = randomGenerator.Next(i + 1);
// Swap array[i] and array[j]
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
/// <summary>
/// Randomly shuffles the items in a list or array, in place.
/// </summary>
/// <remarks>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</remarks>
/// <param name="list">The list or array to shuffle.</param>
public static void RandomShuffleInPlace<T>(IList<T> list)
{
RandomShuffleInPlace(list, GetRandomGenerator());
}
/// <summary>
/// Randomly shuffles the items in a list or array, in place.
/// </summary>
/// <remarks>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</remarks>
/// <param name="list">The list or array to shuffle.</param>
/// <param name="randomGenerator">The random number generator to use to select the random order.</param>
public static void RandomShuffleInPlace<T>(IList<T> list, Random randomGenerator)
{
if (list == null)
throw new ArgumentNullException("list");
if (randomGenerator == null)
throw new ArgumentNullException("randomGenerator");
if (list is T[])
list = new ArrayWrapper<T>((T[])list);
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
int count = list.Count;
for (int i = count - 1; i >= 1; --i) {
// Pick an random number 0 through i inclusive.
int j = randomGenerator.Next(i + 1);
// Swap list[i] and list[j]
T temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
/// <summary>
/// Picks a random subset of <paramref name="count"/> items from <paramref name="collection"/>, and places
/// those items into a random order. No item is selected more than once.
/// </summary>
/// <remarks>If the collection implements IList<T>, then this method takes time O(<paramref name="count"/>).
/// Otherwise, this method takes time O(N), where N is the number of items in the collection.</remarks>
/// <typeparam name="T">The type of items in the collection.</typeparam>
/// <param name="collection">The collection of items to select from. This collection is not changed.</param>
/// <param name="count">The number of items in the subset to choose.</param>
/// <returns>An array of <paramref name="count"/> items, selected at random from <paramref name="collection"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is negative or greater than <paramref name="collection"/>.Count.</exception>
public static T[] RandomSubset<T>(IEnumerable<T> collection, int count)
{
return RandomSubset(collection, count, GetRandomGenerator());
}
/// <summary>
/// Picks a random subset of <paramref name="count"/> items from <paramref name="collection"/>, and places
/// those items into a random order. No item is selected more than once.
/// </summary>
/// <remarks>If the collection implements IList<T>, then this method takes time O(<paramref name="count"/>).
/// Otherwise, this method takes time O(N), where N is the number of items in the collection.</remarks>
/// <typeparam name="T">The type of items in the collection.</typeparam>
/// <param name="collection">The collection of items to select from. This collection is not changed.</param>
/// <param name="count">The number of items in the subset to choose.</param>
/// <param name="randomGenerator">The random number generates used to make the selection.</param>
/// <returns>An array of <paramref name="count"/> items, selected at random from <paramref name="collection"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is negative or greater than <paramref name="collection"/>.Count.</exception>
/// <exception cref="ArgumentNullException"><paramref name="randomGenerator"/> is null.</exception>
public static T[] RandomSubset<T>(IEnumerable<T> collection, int count, Random randomGenerator)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (randomGenerator == null)
throw new ArgumentNullException("randomGenerator");
// We need random access to the items in the collection. If it's not already an
// IList<T>, copy to a temporary list.
IList<T> list = collection as IList<T>;
if (list == null) {
list = new List<T>(collection);
}
int listCount = list.Count;
if (count < 0 || count > listCount)
throw new ArgumentOutOfRangeException("count");
T[] result = new T[count]; // the result array.
Dictionary<int, T> swappedValues = new Dictionary<int, T>(count); // holds swapped values from the list.
for (int i = 0; i < count; ++i) {
// Set j to the index of the item to swap with, and value to the value to swap with.
T value;
int j = randomGenerator.Next(listCount - i) + i;
// Swap values of i and j in the list. The list isn't actually changed; instead,
// swapped values are stored in the dictionary swappedValues.
if (!swappedValues.TryGetValue(j, out value))
value = list[j];
result[i] = value;
if (i != j) {
if (swappedValues.TryGetValue(i, out value))
swappedValues[j] = value;
else
swappedValues[j] = list[i];
}
}
return result;
}
/// <summary>
/// Generates all the possible permutations of the items in <paramref name="collection"/>. If <paramref name="collection"/>
/// has N items, then N factorial permutations will be generated. This method does not compare the items to determine if
/// any of them are equal. If some items are equal, the same permutation may be generated more than once. For example,
/// if the collections contains the three items A, A, and B, then this method will generate the six permutations, AAB, AAB,
/// ABA, ABA, BAA, BAA (not necessarily in that order). To take equal items into account, use the GenerateSortedPermutations
/// method.
/// </summary>
/// <typeparam name="T">The type of items to permute.</typeparam>
/// <param name="collection">The collection of items to permute.</param>
/// <returns>An IEnumerable<T[]> that enumerations all the possible permutations of the
/// items in <paramref name="collection"/>. Each permutations is returned as an array. The items in the array
/// should be copied if they need to be used after the next permutation is generated; each permutation may
/// reuse the same array instance.</returns>
public static IEnumerable<T[]> GeneratePermutations<T>(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
T[] array = Algorithms.ToArray(collection);
if (array.Length == 0)
yield break;
int[] state = new int[array.Length - 1];
int maxLength = state.Length;
yield return array;
if (array.Length == 1)
yield break;
// The following algorithm makes two swaps for each
// permutation generated.
// This is not optimal in terms of number of swaps, but
// is still O(1), and shorter and clearer to understand.
int i = 0;
T temp;
for (; ; ) {
if (state[i] < i + 1) {
if (state[i] > 0) {
temp = array[i + 1];
array[i + 1] = array[state[i] - 1];
array[state[i] - 1] = temp;
}
temp = array[i + 1];
array[i + 1] = array[state[i]];
array[state[i]] = temp;
yield return array;
++state[i];
i = 0;
}
else {
temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
state[i] = 0;
++i;
if (i >= maxLength)
yield break;
}
}
}
/// <summary>
/// Generates all the possible permutations of the items in <paramref name="collection"/>, in lexicographical order.
/// Even if some items are equal, the same permutation will not be generated more than once. For example,
/// if the collections contains the three items A, A, and B, then this method will generate only the three permutations, AAB, ABA,
/// BAA.
/// </summary>
/// <typeparam name="T">The type of items to permute.</typeparam>
/// <param name="collection">The collection of items to permute.</param>
/// <returns>An IEnumerable<T[]> that enumerations all the possible permutations of the
/// items in <paramref name="collection"/>. Each permutations is returned as an array. The items in the array
/// should be copied if they need to be used after the next permutation is generated; each permutation may
/// reuse the same array instance.</returns>
public static IEnumerable<T[]> GenerateSortedPermutations<T>(IEnumerable<T> collection)
where T: IComparable<T>
{
return GenerateSortedPermutations(collection, Comparer<T>.Default);
}
/// <summary>
/// Generates all the possible permutations of the items in <paramref name="collection"/>, in lexicographical order. A
/// supplied IComparer<T> instance is used to compare the items.
/// Even if some items are equal, the same permutation will not be generated more than once. For example,
/// if the collections contains the three items A, A, and B, then this method will generate only the three permutations, AAB, ABA,
/// BAA.
/// </summary>
/// <typeparam name="T">The type of items to permute.</typeparam>
/// <param name="collection">The collection of items to permute.</param>
/// <param name="comparer">The IComparer<T> used to compare the items.</param>
/// <returns>An IEnumerable<T[]> that enumerations all the possible permutations of the
/// items in <paramref name="collection"/>. Each permutations is returned as an array. The items in the array
/// should be copied if they need to be used after the next permutation is generated; each permutation may
/// reuse the same array instance.</returns>
public static IEnumerable<T[]> GenerateSortedPermutations<T>(IEnumerable<T> collection, IComparer<T> comparer)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (comparer == null)
throw new ArgumentNullException("comparer");
T[] array = Algorithms.ToArray(collection);
int length = array.Length;
if (length == 0)
yield break;
Array.Sort(array, comparer);
yield return array;
if (length == 1)
yield break;
// Keep generating the next permutation until we're done. Algorithm is
// due to Jeffrey A. Johnson ("SEPA - a Simple Efficient Permutation Algorithm")
int key, swap, i, j;
T temp;
for (; ; ) {
// Find the key point -- where array[key]<array[key+1]. Everything after the
// key is the tail.
key = length - 2;
while (comparer.Compare(array[key], array[key+1]) >= 0) {
--key;
if (key < 0)
yield break;
}
// Find the last item in the tail less than key.
swap = length - 1;
while (comparer.Compare(array[swap], array[key]) <= 0)
--swap;
// Swap it with the key.
temp = array[key];
array[key] = array[swap];
array[swap] = temp;
// Reverse the tail.
i = key + 1;
j = length - 1;
while (i < j) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
++i; --j;
}
yield return array;
}
}
/// <summary>
/// Generates all the possible permutations of the items in <paramref name="collection"/>, in lexicographical order. A
/// supplied Comparison<T> delegate is used to compare the items.
/// Even if some items are equal, the same permutation will not be generated more than once. For example,
/// if the collections contains the three items A, A, and B, then this method will generate only the three permutations, AAB, ABA,
/// BAA.
/// </summary>
/// <typeparam name="T">The type of items to permute.</typeparam>
/// <param name="collection">The collection of items to permute.</param>
/// <param name="comparison">The Comparison<T> delegate used to compare the items.</param>
/// <returns>An IEnumerable<T[]> that enumerations all the possible permutations of the
/// items in <paramref name="collection"/>. Each permutations is returned as an array. The items in the array
/// should be copied if they need to be used after the next permutation is generated; each permutation may
/// reuse the same array instance.</returns>
public static IEnumerable<T[]> GenerateSortedPermutations<T>(IEnumerable<T> collection, Comparison<T> comparison)
{
return GenerateSortedPermutations(collection, Comparers.ComparerFromComparison(comparison));
}
#endregion Shuffles and Permutations
#region Minimum and Maximum
/// <summary>
/// Finds the maximum value in a collection.
/// </summary>
/// <remarks>Values in the collection are compared by using the IComparable<T>
/// interfaces implementation on the type T.</remarks>
/// <typeparam name="T">The type of items in the collection.</typeparam>
/// <param name="collection">The collection to search.</param>
/// <returns>The largest item in the collection. </returns>
/// <exception cref="InvalidOperationException">The collection is empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
public static T Maximum<T>(IEnumerable<T> collection)
where T : IComparable<T>
{
return Maximum(collection, Comparer<T>.Default);
}
/// <summary>
/// Finds the maximum value in a collection. A supplied IComparer<T> is used
/// to compare the items in the collection.
/// </summary>
/// <typeparam name="T">The type of items in the collection.</typeparam>
/// <param name="collection">The collection to search.</param>
/// <param name="comparer">The comparer instance used to compare items in the collection.</param>
/// <returns>The largest item in the collection.</returns>
/// <exception cref="InvalidOperationException">The collection is empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> or <paramref name="comparer"/> is null.</exception>
public static T Maximum<T>(IEnumerable<T> collection, IComparer<T> comparer)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (comparer == null)
throw new ArgumentNullException("comparer");
T maxSoFar = default(T);
bool foundOne = false;
// Go through the collection, keeping the maximum found so far.
foreach (T item in collection) {
if (!foundOne || comparer.Compare(maxSoFar, item) < 0) {
maxSoFar = item;
}
foundOne = true;
}
// If the collection was empty, throw an exception.
if (!foundOne)
throw new InvalidOperationException(Strings.CollectionIsEmpty);
else
return maxSoFar;
}
/// <summary>
/// Finds the maximum value in a collection. A supplied Comparison<T> delegate is used
/// to compare the items in the collection.
/// </summary>
/// <typeparam name="T">The type of items in the collection.</typeparam>
/// <param name="collection">The collection to search.</param>
/// <param name="comparison">The comparison used to compare items in the collection.</param>
/// <returns>The largest item in the collection.</returns>
/// <exception cref="InvalidOperationException">The collection is empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> or <paramref name="comparison"/> is null.</exception>
public static T Maximum<T>(IEnumerable<T> collection, Comparison<T> comparison)
{
return Maximum(collection, Comparers.ComparerFromComparison(comparison));
}
/// <summary>
/// Finds the minimum value in a collection.
/// </summary>
/// <remarks>Values in the collection are compared by using the IComparable<T>
/// interfaces implementation on the type T.</remarks>
/// <typeparam name="T">The type of items in the collection.</typeparam>
/// <param name="collection">The collection to search.</param>
/// <returns>The smallest item in the collection.</returns>
/// <exception cref="InvalidOperationException">The collection is empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
public static T Minimum<T>(IEnumerable<T> collection)
where T : IComparable<T>
{
return Minimum(collection, Comparer<T>.Default);
}
/// <summary>
/// Finds the minimum value in a collection. A supplied IComparer<T> is used
/// to compare the items in the collection.
/// </summary>
/// <typeparam name="T">The type of items in the collection.</typeparam>
/// <param name="collection">The collection to search.</param>
/// <param name="comparer">The comparer instance used to compare items in the collection.</param>
/// <returns>The smallest item in the collection.</returns>
/// <exception cref="InvalidOperationException">The collection is empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> or <paramref name="comparer"/> is null.</exception>
public static T Minimum<T>(IEnumerable<T> collection, IComparer<T> comparer)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (comparer == null)
throw new ArgumentNullException("comparer");
T minSoFar = default(T);
bool foundOne = false;
// Go through the collection, keeping the minimum found so far.
foreach (T item in collection) {
if (!foundOne || comparer.Compare(minSoFar, item) > 0) {
minSoFar = item;
}
foundOne = true;
}
// If the collection was empty, throw an exception.
if (!foundOne)
throw new InvalidOperationException(Strings.CollectionIsEmpty);
else
return minSoFar;
}
/// <summary>
/// Finds the minimum value in a collection. A supplied Comparison<T> delegate is used
/// to compare the items in the collection.
/// </summary>
/// <typeparam name="T">The type of items in the collection.</typeparam>
/// <param name="collection">The collection to search.</param>
/// <param name="comparison">The comparison used to compare items in the collection.</param>
/// <returns>The smallest item in the collection.</returns>
/// <exception cref="InvalidOperationException">The collection is empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> or <paramref name="comparison"/> is null.</exception>
public static T Minimum<T>(IEnumerable<T> collection, Comparison<T> comparison)
{
return Minimum(collection, Comparers.ComparerFromComparison(comparison));
}
/// <summary>
/// Finds the index of the maximum value in a list.
/// </summary>
/// <remarks>Values in the list are compared by using the IComparable<T>
/// interfaces implementation on the type T.</remarks>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <returns>The index of the largest item in the list. If the maximum value appears
/// multiple times, the index of the first appearance is used. If the list is empty, -1 is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="list"/> is null.</exception>
public static int IndexOfMaximum<T>(IList<T> list)
where T : IComparable<T>
{
return IndexOfMaximum(list, Comparer<T>.Default);
}
/// <summary>
/// Finds the index of the maximum value in a list. A supplied IComparer<T> is used
/// to compare the items in the collection.
/// </summary>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <param name="comparer">The comparer instance used to compare items in the collection.</param>
/// <returns>The index of the largest item in the list. If the maximum value appears
/// multiple times, the index of the first appearance is used. If the list is empty, -1 is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="list"/> or <paramref name="comparer"/> is null.</exception>
public static int IndexOfMaximum<T>(IList<T> list, IComparer<T> comparer)
{
if (list == null)
throw new ArgumentNullException("list");
if (comparer == null)
throw new ArgumentNullException("comparer");
T maxSoFar = default(T);
int indexSoFar = -1;
// Go through the collection, keeping the maximum found so far.
int i = 0;
foreach (T item in list) {
if (indexSoFar < 0 || comparer.Compare(maxSoFar, item) < 0) {
maxSoFar = item;
indexSoFar = i;
}
++i;
}
return indexSoFar;
}
/// <summary>
/// Finds the index of the maximum value in a list. A supplied Comparison<T> delegate is used
/// to compare the items in the collection.
/// </summary>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <param name="comparison">The comparison used to compare items in the collection.</param>
/// <returns>The index of the largest item in the list. If the maximum value appears
/// multiple times, the index of the first appearance is used. If the list is empty, -1 is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="list"/> or <paramref name="comparison"/> is null.</exception>
public static int IndexOfMaximum<T>(IList<T> list, Comparison<T> comparison)
{
return IndexOfMaximum(list, Comparers.ComparerFromComparison(comparison));
}
/// <summary>
/// Finds the index of the minimum value in a list.
/// </summary>
/// <remarks>Values in the list are compared by using the IComparable<T>
/// interfaces implementation on the type T.</remarks>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <returns>The index of the smallest item in the list. If the minimum value appears
/// multiple times, the index of the first appearance is used.</returns>
/// <exception cref="InvalidOperationException">The collection is empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="list"/> is null.</exception>
public static int IndexOfMinimum<T>(IList<T> list)
where T : IComparable<T>
{
return IndexOfMinimum(list, Comparer<T>.Default);
}
/// <summary>
/// Finds the index of the minimum value in a list. A supplied IComparer<T> is used
/// to compare the items in the collection.
/// </summary>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <param name="comparer">The comparer instance used to compare items in the collection.</param>
/// <returns>The index of the smallest item in the list. If the minimum value appears
/// multiple times, the index of the first appearance is used.</returns>
/// <exception cref="InvalidOperationException">The collection is empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="list"/> or <paramref name="comparer"/> is null.</exception>
public static int IndexOfMinimum<T>(IList<T> list, IComparer<T> comparer)
{
if (list == null)
throw new ArgumentNullException("list");
if (comparer == null)
throw new ArgumentNullException("comparer");
T minSoFar = default(T);
int indexSoFar = -1;
// Go through the collection, keeping the minimum found so far.
int i = 0;
foreach (T item in list) {
if (indexSoFar < 0 || comparer.Compare(minSoFar, item) > 0) {
minSoFar = item;
indexSoFar = i;
}
++i;
}
return indexSoFar;
}
/// <summary>
/// Finds the index of the minimum value in a list. A supplied Comparison<T> delegate is used
/// to compare the items in the collection.
/// </summary>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to search.</param>
/// <param name="comparison">The comparison delegate used to compare items in the collection.</param>
/// <returns>The index of the smallest item in the list. If the minimum value appears
/// multiple times, the index of the first appearance is used.</returns>
/// <exception cref="InvalidOperationException">The collection is empty.</exception>
/// <exception cref="ArgumentNullException"><paramref name="list"/> or <paramref name="comparison"/> is null.</exception>
public static int IndexOfMinimum<T>(IList<T> list, Comparison<T> comparison)
{
return IndexOfMinimum(list, Comparers.ComparerFromComparison(comparison));
}
#endregion Minimum and Maximum
#region Sorting and operations on sorted collections
/// <summary>
/// Creates a sorted version of a collection.
/// </summary>
/// <remarks>Values are compared by using the IComparable<T>
/// interfaces implementation on the type T.</remarks>
/// <param name="collection">The collection to sort.</param>
/// <returns>An array containing the sorted version of the collection.</returns>
public static T[] Sort<T>(IEnumerable<T> collection)
where T : IComparable<T>
{
return Sort(collection, Comparer<T>.Default);
}
/// <summary>
/// Creates a sorted version of a collection. A supplied IComparer<T> is used
/// to compare the items in the collection.
/// </summary>
/// <param name="collection">The collection to sort.</param>
/// <param name="comparer">The comparer instance used to compare items in the collection. Only
/// the Compare method is used.</param>
/// <returns>An array containing the sorted version of the collection.</returns>
public static T[] Sort<T>(IEnumerable<T> collection, IComparer<T> comparer)
{
T[] array;
if (collection == null)
throw new ArgumentNullException("collection");
if (comparer == null)
throw new ArgumentNullException("comparer");
array = Algorithms.ToArray(collection);
Array.Sort(array, comparer);
return array;
}
/// <summary>
/// Creates a sorted version of a collection. A supplied Comparison<T> delegate is used
/// to compare the items in the collection.
/// </summary>
/// <param name="collection">The collection to sort.</param>
/// <param name="comparison">The comparison delegate used to compare items in the collection.</param>
/// <returns>An array containing the sorted version of the collection.</returns>
public static T[] Sort<T>(IEnumerable<T> collection, Comparison<T> comparison)
{
return Sort(collection, Comparers.ComparerFromComparison(comparison));
}
/// <summary>
/// Sorts a list or array in place.
/// </summary>
/// <remarks><para>The Quicksort algorithms is used to sort the items. In virtually all cases,
/// this takes time O(N log N), where N is the number of items in the list.</para>
/// <para>Values are compared by using the IComparable<T>
/// interfaces implementation on the type T.</para>
/// <para>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</para></remarks>
/// <param name="list">The list or array to sort.</param>
public static void SortInPlace<T>(IList<T> list)
where T : IComparable<T>
{
SortInPlace(list, Comparer<T>.Default);
}
/// <summary>
/// Sorts a list or array in place. A supplied IComparer<T> is used
/// to compare the items in the list.
/// </summary>
/// <remarks><para>The Quicksort algorithms is used to sort the items. In virtually all cases,
/// this takes time O(N log N), where N is the number of items in the list.</para>
/// <para>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</para></remarks>
/// <param name="list">The list or array to sort.</param>
/// <param name="comparer">The comparer instance used to compare items in the collection. Only
/// the Compare method is used.</param>
public static void SortInPlace<T>(IList<T> list, IComparer<T> comparer)
{
if (list == null)
throw new ArgumentNullException("list");
if (comparer == null)
throw new ArgumentNullException("comparer");
// If we have an array, use the built-in array sort (faster than going through IList accessors
// with virtual calls).
if (list is T[]) {
Array.Sort((T[])list, comparer);
return;
}
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
// Instead of a recursive procedure, we use an explicit stack to hold
// ranges that we still need to sort.
int[] leftStack = new int[32], rightStack = new int[32];
int stackPtr = 0;
int l = 0; // the inclusive left edge of the current range we are sorting.
int r = list.Count - 1; // the inclusive right edge of the current range we are sorting.
T partition; // The partition value.
// Loop until we have nothing left to sort. On each iteration, l and r contains the bounds
// of something to sort (unless r <= l), and leftStack/rightStack have a stack of unsorted
// pieces (unles stackPtr == 0).
for (; ; ) {
if (l == r - 1) {
// We have exactly 2 elements to sort. Compare them and swap if needed.
T e1, e2;
e1 = list[l];
e2 = list[r];
if (comparer.Compare(e1, e2) > 0) {
list[r] = e1;
list[l] = e2;
}
l = r; // sort complete, find other work from the stack.
}
else if (l < r) {
// Sort the items in the inclusive range l .. r
// Get the left, middle, and right-most elements and sort them, yielding e1=smallest, e2=median, e3=largest
int m = l + (r - l) / 2;
T e1 = list[l], e2 = list[m], e3 = list[r], temp;
if (comparer.Compare(e1, e2) > 0) {
temp = e1; e1 = e2; e2 = temp;
}
if (comparer.Compare(e1, e3) > 0) {
temp = e3; e3 = e2; e2 = e1; e1 = temp;
}
else if (comparer.Compare(e2, e3) > 0) {
temp = e2; e2 = e3; e3 = temp;
}
if (l == r - 2) {
// We have exactly 3 elements to sort, and we've done that. Store back and we're done.
list[l] = e1; list[m] = e2; list[r] = e3;
l = r; // sort complete, find other work from the stack.
}
else {
// Put the smallest at the left, largest in the middle, and the median at the right (which is the partitioning value)
list[l] = e1;
list[m] = e3;
list[r] = partition = e2;
// Partition into three parts, items <= partition, items == partition, and items >= partition
int i = l, j = r;
T item_i, item_j;
for (; ; ) {
do {
++i;
item_i = list[i];
} while (comparer.Compare(item_i, partition) < 0);
do {
--j;
item_j = list[j];
} while (comparer.Compare(item_j, partition) > 0);
if (j < i)
break;
list[i] = item_j; list[j] = item_i; // swap items to continue the partition.
}
// Move the partition value into place.
list[r] = item_i;
list[i] = partition;
++i;
// We have partitioned the list.
// Items in the inclusive range l .. j are <= partition.
// Items in the inclusive range i .. r are >= partition.
// Items in the inclusive range j+1 .. i - 1 are == partition (and in the correct final position).
// We now need to sort l .. j and i .. r.
// To do this, we stack one of the lists for later processing, and change l and r to the other list.
// If we always stack the larger of the two sub-parts, the stack cannot get greater
// than log2(Count) in size; i.e., a 32-element stack is enough for the maximum list size.
if ((j - l) > (r - i)) {
// The right partition is smaller. Stack the left, and get ready to sort the right.
leftStack[stackPtr] = l;
rightStack[stackPtr] = j;
l = i;
}
else {
// The left partition is smaller. Stack the right, and get ready to sort the left.
leftStack[stackPtr] = i;
rightStack[stackPtr] = r;
r = j;
}
++stackPtr;
}
}
else if (stackPtr > 0) {
// We have a stacked sub-list to sort. Pop it off and sort it.
--stackPtr;
l = leftStack[stackPtr];
r = rightStack[stackPtr];
}
else {
// We have nothing left to sort.
break;
}
}
}
/// <summary>
/// Sorts a list or array in place. A supplied Comparison<T> delegate is used
/// to compare the items in the list.
/// </summary>
/// <remarks><para>The Quicksort algorithms is used to sort the items. In virtually all cases,
/// this takes time O(N log N), where N is the number of items in the list.</para>
/// <para>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</para></remarks>
/// <param name="list">The list or array to sort.</param>
/// <param name="comparison">The comparison delegate used to compare items in the collection.</param>
public static void SortInPlace<T>(IList<T> list, Comparison<T> comparison)
{
SortInPlace(list, Comparers.ComparerFromComparison(comparison));
}
/// <summary>
/// Creates a sorted version of a collection. The sort is stable, which means that if items X and Y are equal,
/// and X precedes Y in the unsorted collection, X will precede Y is the sorted collection.
/// </summary>
/// <remarks>Values are compared by using the IComparable<T>
/// interfaces implementation on the type T.</remarks>
/// <param name="collection">The collection to sort.</param>
/// <returns>An array containing the sorted version of the collection.</returns>
public static T[] StableSort<T>(IEnumerable<T> collection)
where T : IComparable<T>
{
return StableSort(collection, Comparer<T>.Default);
}
/// <summary>
/// Creates a sorted version of a collection. The sort is stable, which means that if items X and Y are equal,
/// and X precedes Y in the unsorted collection, X will precede Y is the sorted collection. A supplied IComparer<T> is used
/// to compare the items in the collection.
/// </summary>
/// <param name="collection">The collection to sort.</param>
/// <param name="comparer">The comparer instance used to compare items in the collection. Only
/// the Compare method is used.</param>
/// <returns>An array containing the sorted version of the collection.</returns>
public static T[] StableSort<T>(IEnumerable<T> collection, IComparer<T> comparer)
{
T[] array;
if (collection == null)
throw new ArgumentNullException("collection");
if (comparer == null)
throw new ArgumentNullException("comparer");
array = Algorithms.ToArray(collection);
StableSortInPlace(Algorithms.ReadWriteList(array), comparer);
return array;
}
/// <summary>
/// Creates a sorted version of a collection. The sort is stable, which means that if items X and Y are equal,
/// and X precedes Y in the unsorted collection, X will precede Y is the sorted collection.
/// A supplied Comparison<T> delegate is used
/// to compare the items in the collection.
/// </summary>
/// <remarks>Values are compared by using the IComparable<T>
/// interfaces implementation on the type T.</remarks>
/// <param name="collection">The collection to sort.</param>
/// <param name="comparison">The comparison delegate used to compare items in the collection.</param>
/// <returns>An array containing the sorted version of the collection.</returns>
public static T[] StableSort<T>(IEnumerable<T> collection, Comparison<T> comparison)
{
return StableSort(collection, Comparers.ComparerFromComparison(comparison));
}
/// <summary>
/// Sorts a list or array in place. The sort is stable, which means that if items X and Y are equal,
/// and X precedes Y in the unsorted collection, X will precede Y is the sorted collection.
/// </summary>
/// <remarks><para>Values are compared by using the IComparable<T>
/// interfaces implementation on the type T.</para>
/// <para>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</para></remarks>
/// <param name="list">The list or array to sort.</param>
public static void StableSortInPlace<T>(IList<T> list)
where T : IComparable<T>
{
StableSortInPlace(list, Comparer<T>.Default);
}
/// <summary>
/// Sorts a list or array in place. The sort is stable, which means that if items X and Y are equal,
/// and X precedes Y in the unsorted collection, X will precede Y is the sorted collection.
/// A supplied IComparer<T> is used
/// to compare the items in the list.
/// </summary>
/// <remarks>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</remarks>
/// <param name="list">The list or array to sort.</param>
/// <param name="comparer">The comparer instance used to compare items in the collection. Only
/// the Compare method is used.</param>
public static void StableSortInPlace<T>(IList<T> list, IComparer<T> comparer)
{
if (list == null)
throw new ArgumentNullException("list");
if (comparer == null)
throw new ArgumentNullException("comparer");
if (list is T[])
list = new ArrayWrapper<T>((T[])list);
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
// The stable sort algorithms also uses QuickSort. An additional array of indices (order) is
// used to maintain the original order of items in the array, and that array is used
// as a secondary compare when the primary compare returns equal.
int[] order = new int[list.Count];
for (int x = 0; x < order.Length; ++x)
order[x] = x;
// Instead of a recursive procedure, we use an explicit stack to hold
// ranges that we still need to sort.
int[] leftStack = new int[32], rightStack = new int[32];
int stackPtr = 0;
int l = 0; // the inclusive left edge of the current range we are sorting.
int r = list.Count - 1; // the inclusive right edge of the current range we are sorting.
T partition; // The partition value.
int order_partition; // The order of the partition value;
int c; // holds the result of a comparison temporarily.
// Loop until we have nothing left to sort. On each iteration, l and r contains the bounds
// of something to sort (unless r <= l), and leftStack/rightStack have a stack of unsorted
// pieces (unles stackPtr == 0).
for (; ; ) {
if (l == r - 1) {
// We have exactly 2 elements to sort. Compare them and swap if needed.
T e1, e2;
int o1, o2;
e1 = list[l]; o1 = order[l];
e2 = list[r]; o2 = order[r];
if ((c = comparer.Compare(e1, e2)) > 0 || (c == 0 && o1 > o2)) {
list[r] = e1; order[r] = o1;
list[l] = e2; order[l] = o2;
}
l = r; // sort complete, find other work from the stack.
}
else if (l < r) {
// Sort the items in the inclusive range l .. r
// Get the left, middle, and right-most elements and sort them, yielding e1=smallest, e2=median, e3=largest
int m = l + (r - l) / 2;
T e1 = list[l], e2 = list[m], e3 = list[r], temp;
int o1 = order[l], o2 = order[m], o3 = order[r], otemp;
if ((c = comparer.Compare(e1, e2)) > 0 || (c == 0 && o1 > o2)) {
temp = e1; e1 = e2; e2 = temp;
otemp = o1; o1 = o2; o2 = otemp;
}
if ((c = comparer.Compare(e1, e3)) > 0 || (c == 0 && o1 > o3)) {
temp = e3; e3 = e2; e2 = e1; e1 = temp;
otemp = o3; o3 = o2; o2 = o1; o1 = otemp;
}
else if ((c = comparer.Compare(e2, e3)) > 0 || (c == 0 && o2 > o3)) {
temp = e2; e2 = e3; e3 = temp;
otemp = o2; o2 = o3; o3 = otemp;
}
if (l == r - 2) {
// We have exactly 3 elements to sort, and we've done that. Store back and we're done.
list[l] = e1; list[m] = e2; list[r] = e3;
order[l] = o1; order[m] = o2; order[r] = o3;
l = r; // sort complete, find other work from the stack.
}
else {
// Put the smallest at the left, largest in the middle, and the median at the right (which is the partitioning value)
list[l] = e1; order[l] = o1;
list[m] = e3; order[m] = o3;
list[r] = partition = e2; order[r] = order_partition = o2;
// Partition into three parts, items <= partition, items == partition, and items >= partition
int i = l, j = r;
T item_i, item_j;
int order_i, order_j;
for (; ; ) {
do {
++i;
item_i = list[i]; order_i = order[i];
} while ((c = comparer.Compare(item_i, partition)) < 0 || (c == 0 && order_i < order_partition));
do {
--j;
item_j = list[j]; order_j = order[j];
} while ((c = comparer.Compare(item_j, partition)) > 0 || (c == 0 && order_j > order_partition));
if (j < i)
break;
list[i] = item_j; list[j] = item_i; // swap items to continue the partition.
order[i] = order_j; order[j] = order_i;
}
// Move the partition value into place.
list[r] = item_i; order[r] = order_i;
list[i] = partition; order[i] = order_partition;
++i;
// We have partitioned the list.
// Items in the inclusive range l .. j are <= partition.
// Items in the inclusive range i .. r are >= partition.
// Items in the inclusive range j+1 .. i - 1 are == partition (and in the correct final position).
// We now need to sort l .. j and i .. r.
// To do this, we stack one of the lists for later processing, and change l and r to the other list.
// If we always stack the larger of the two sub-parts, the stack cannot get greater
// than log2(Count) in size; i.e., a 32-element stack is enough for the maximum list size.
if ((j - l) > (r - i)) {
// The right partition is smaller. Stack the left, and get ready to sort the right.
leftStack[stackPtr] = l;
rightStack[stackPtr] = j;
l = i;
}
else {
// The left partition is smaller. Stack the right, and get ready to sort the left.
leftStack[stackPtr] = i;
rightStack[stackPtr] = r;
r = j;
}
++stackPtr;
}
}
else if (stackPtr > 0) {
// We have a stacked sub-list to sort. Pop it off and sort it.
--stackPtr;
l = leftStack[stackPtr];
r = rightStack[stackPtr];
}
else {
// We have nothing left to sort.
break;
}
}
}
/// <summary>
/// Sorts a list or array in place. The sort is stable, which means that if items X and Y are equal,
/// and X precedes Y in the unsorted collection, X will precede Y is the sorted collection.
/// A supplied Comparison<T> delegate is used
/// to compare the items in the list.
/// </summary>
/// <remarks>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</remarks>
/// <param name="list">The list or array to sort.</param>
/// <param name="comparison">The comparison delegate used to compare items in the collection.</param>
public static void StableSortInPlace<T>(IList<T> list, Comparison<T> comparison)
{
StableSortInPlace(list, Comparers.ComparerFromComparison(comparison));
}
/// <summary>
/// Searches a sorted list for an item via binary search. The list must be sorted
/// by the natural ordering of the type (it's implementation of IComparable<T>).
/// </summary>
/// <param name="list">The sorted list to search.</param>
/// <param name="item">The item to search for.</param>
/// <param name="index">Returns the first index at which the item can be found. If the return
/// value is zero, indicating that <paramref name="item"/> was not present in the list, then this
/// returns the index at which <paramref name="item"/> could be inserted to maintain the sorted
/// order of the list.</param>
/// <returns>The number of items equal to <paramref name="item"/> that appear in the list.</returns>
public static int BinarySearch<T>(IList<T> list, T item, out int index)
where T: IComparable<T>
{
return BinarySearch(list, item, Comparer<T>.Default, out index);
}
/// <summary>
/// Searches a sorted list for an item via binary search. The list must be sorted
/// by the ordering in the passed instance of IComparer<T>.
/// </summary>
/// <param name="list">The sorted list to search.</param>
/// <param name="item">The item to search for.</param>
/// <param name="comparer">The comparer instance used to sort the list. Only
/// the Compare method is used.</param>
/// <param name="index">Returns the first index at which the item can be found. If the return
/// value is zero, indicating that <paramref name="item"/> was not present in the list, then this
/// returns the index at which <paramref name="item"/> could be inserted to maintain the sorted
/// order of the list.</param>
/// <returns>
/// The number of items equal to <paramref name="item"/> that appear in the list.
/// </returns>
public static int BinarySearch<T>(IList<T> list, T item, IComparer<T> comparer, out int index)
{
if (list == null)
throw new ArgumentNullException("list");
if (comparer == null)
throw new ArgumentNullException("comparer");
int l = 0;
int r = list.Count;
while (r > l) {
int m = l + (r - l) / 2;
T middleItem = list[m];
int comp = comparer.Compare(middleItem, item);
if (comp < 0) {
// middleItem < item
l = m + 1;
}
else if (comp > 0) {
r = m;
}
else {
// Found something equal to item at m. Now we need to find the start and end of this run of equal items.
int lFound = l, rFound = r, found = m;
// Find the start of the run.
l = lFound;
r = found;
while (r > l) {
m = l + (r - l) / 2;
middleItem = list[m];
comp = comparer.Compare(middleItem, item);
if (comp < 0) {
// middleItem < item
l = m + 1;
}
else {
r = m;
}
}
System.Diagnostics.Debug.Assert(l == r, "Left and Right were not equal");
index = l;
// Find the end of the run.
l = found;
r = rFound;
while (r > l) {
m = l + (r - l) / 2;
middleItem = list[m];
comp = comparer.Compare(middleItem, item);
if (comp <= 0) {
// middleItem <= item
l = m + 1;
}
else {
r = m;
}
}
System.Diagnostics.Debug.Assert(l == r, "Left and Right were not equal");
return l - index;
}
}
// We did not find the item. l and r must be equal.
System.Diagnostics.Debug.Assert(l == r);
index = l;
return 0;
}
/// <summary>
/// Searches a sorted list for an item via binary search. The list must be sorted
/// by the ordering in the passed Comparison<T> delegate.
/// </summary>
/// <param name="list">The sorted list to search.</param>
/// <param name="item">The item to search for.</param>
/// <param name="comparison">The comparison delegate used to sort the list.</param>
/// <param name="index">Returns the first index at which the item can be found. If the return
/// value is zero, indicating that <paramref name="item"/> was not present in the list, then this
/// returns the index at which <paramref name="item"/> could be inserted to maintain the sorted
/// order of the list.</param>
/// <returns>The number of items equal to <paramref name="item"/> that appear in the list.</returns>
public static int BinarySearch<T>(IList<T> list, T item, Comparison<T> comparison, out int index)
{
return BinarySearch(list, item, Comparers.ComparerFromComparison(comparison), out index);
}
/// <summary>
/// Merge several sorted collections into a single sorted collection. Each input collection must be sorted
/// by the natural ordering of the type (it's implementation of IComparable<T>). The merging
/// is stable; equal items maintain their ordering, and equal items in different collections are placed
/// in the order of the collections.
/// </summary>
/// <param name="collections">The set of collections to merge. In many languages, this parameter
/// can be specified as several individual parameters.</param>
/// <returns>An IEnumerable<T> that enumerates all the items in all the collections
/// in sorted order. </returns>
public static IEnumerable<T> MergeSorted<T>(params IEnumerable<T>[] collections)
where T : IComparable<T>
{
return MergeSorted(Comparer<T>.Default, collections);
}
/// <summary>
/// Merge several sorted collections into a single sorted collection. Each input collection must be sorted
/// by the ordering in the passed instance of IComparer<T>. The merging
/// is stable; equal items maintain their ordering, and equal items in different collections are placed
/// in the order of the collections.
/// </summary>
/// <param name="collections">The set of collections to merge. In many languages, this parameter
/// can be specified as several individual parameters.</param>
/// <param name="comparer">The comparer instance used to sort the list. Only
/// the Compare method is used.</param>
/// <returns>An IEnumerable<T> that enumerates all the items in all the collections
/// in sorted order. </returns>
public static IEnumerable<T> MergeSorted<T>(IComparer<T> comparer, params IEnumerable<T>[] collections)
{
if (collections == null)
throw new ArgumentNullException("collections");
if (comparer == null)
throw new ArgumentNullException("comparer");
IEnumerator<T>[] enumerators = new IEnumerator<T>[collections.Length];
bool[] more = new bool[collections.Length];
T smallestItem = default(T);
int smallestItemIndex;
try {
// Get enumerators from each collection, and advance to the first element.
for (int i = 0; i < collections.Length; ++i) {
if (collections[i] != null) {
enumerators[i] = collections[i].GetEnumerator();
more[i] = enumerators[i].MoveNext();
}
}
for (; ; ) {
// Find the smallest item, and which collection it is in.
smallestItemIndex = -1; // -1 indicates no smallest yet.
for (int i = 0; i < enumerators.Length; ++i) {
if (more[i]) {
T item = enumerators[i].Current;
if (smallestItemIndex < 0 || comparer.Compare(smallestItem, item) > 0) {
smallestItemIndex = i;
smallestItem = item;
}
}
}
// If no smallest item found, we're done.
if (smallestItemIndex == -1)
yield break;
// Yield the smallest item.
yield return smallestItem;
// Advance the enumerator it came from.
more[smallestItemIndex] = enumerators[smallestItemIndex].MoveNext();
}
}
finally {
// Dispose all enumerators.
foreach (IEnumerator<T> e in enumerators) {
if (e != null)
e.Dispose();
}
}
}
/// <summary>
/// Merge several sorted collections into a single sorted collection. Each input collection must be sorted
/// by the ordering in the passed Comparison<T> delegate. The merging
/// is stable; equal items maintain their ordering, and equal items in different collections are placed
/// in the order of the collections.
/// </summary>
/// <param name="collections">The set of collections to merge. In many languages, this parameter
/// can be specified as several individual parameters.</param>
/// <param name="comparison">The comparison delegate used to sort the collections.</param>
/// <returns>An IEnumerable<T> that enumerates all the items in all the collections
/// in sorted order. </returns>
public static IEnumerable<T> MergeSorted<T>(Comparison<T> comparison, params IEnumerable<T>[] collections)
{
return MergeSorted(Comparers.ComparerFromComparison(comparison), collections);
}
/// <summary>
/// Performs a lexicographical comparison of two sequences of values. A lexicographical comparison compares corresponding
/// pairs of elements from two sequences in order. If the first element of sequence1 is less than the first element of sequence2,
/// then the comparison ends and the first sequence is lexicographically less than the second. If the first elements of each sequence
/// are equal, then the comparison proceeds to the second element of each sequence. If one sequence is shorter than the other,
/// but corresponding elements are all equal, then the shorter sequence is considered less than the longer one.
/// </summary>
/// <remarks>T must implement either IComparable<T> and this implementation is used
/// to compare the items. </remarks>
/// <typeparam name="T">Types of items to compare. This type must implement IComparable<T> to allow
/// items to be compared.</typeparam>
/// <param name="sequence1">The first sequence to compare.</param>
/// <param name="sequence2">The second sequence to compare.</param>
/// <returns>Less than zero if <paramref name="sequence1"/> is lexicographically less than <paramref name="sequence2"/>.
/// Greater than zero if <paramref name="sequence1"/> is lexicographically greater than <paramref name="sequence2"/>.
/// Zero if <paramref name="sequence1"/> is equal to <paramref name="sequence2"/>.</returns>
/// <exception cref="NotSupportedException">T does not implement IComparable<T> or IComparable.</exception>
public static int LexicographicalCompare<T>(IEnumerable<T> sequence1, IEnumerable<T> sequence2)
where T : IComparable<T>
{
return LexicographicalCompare(sequence1, sequence2, Comparer<T>.Default);
}
/// <summary>
/// Performs a lexicographical comparison of two sequences of values, using a supplied comparison delegate. A lexicographical comparison compares corresponding
/// pairs of elements from two sequences in order. If the first element of sequence1 is less than the first element of sequence2,
/// then the comparison ends and the first sequence is lexicographically less than the second. If the first elements of each sequence
/// are equal, then the comparison proceeds to the second element of each sequence. If one sequence is shorter than the other,
/// but corresponding elements are all equal, then the shorter sequence is considered less than the longer one.
/// </summary>
/// <typeparam name="T">Types of items to compare.</typeparam>
/// <param name="sequence1">The first sequence to compare.</param>
/// <param name="sequence2">The second sequence to compare.</param>
/// <param name="comparison">The IComparison<T> delegate to compare items.
/// Only the Compare member function of this interface is called.</param>
/// <returns>Less than zero if <paramref name="sequence1"/> is lexicographically less than <paramref name="sequence2"/>.
/// Greater than zero if <paramref name="sequence1"/> is lexicographically greater than <paramref name="sequence2"/>.
/// Zero if <paramref name="sequence1"/> is equal to <paramref name="sequence2"/>.</returns>
public static int LexicographicalCompare<T>(IEnumerable<T> sequence1, IEnumerable<T> sequence2, Comparison<T> comparison)
{
return LexicographicalCompare(sequence1, sequence2, Comparers.ComparerFromComparison(comparison));
}
/// <summary>
/// Performs a lexicographical comparison of two sequences of values, using a supplied comparer interface. A lexicographical comparison compares corresponding
/// pairs of elements from two sequences in order. If the first element of sequence1 is less than the first element of sequence2,
/// then the comparison ends and the first sequence is lexicographically less than the second. If the first elements of each sequence
/// are equal, then the comparison proceeds to the second element of each sequence. If one sequence is shorter than the other,
/// but corresponding elements are all equal, then the shorter sequence is considered less than the longer one.
/// </summary>
/// <typeparam name="T">Types of items to compare.</typeparam>
/// <param name="sequence1">The first sequence to compare.</param>
/// <param name="sequence2">The second sequence to compare.</param>
/// <param name="comparer">The IComparer<T> used to compare items.
/// Only the Compare member function of this interface is called.</param>
/// <returns>Less than zero if <paramref name="sequence1"/> is lexicographically less than <paramref name="sequence2"/>.
/// Greater than zero if <paramref name="sequence1"/> is lexicographically greater than <paramref name="sequence2"/>.
/// Zero if <paramref name="sequence1"/> is equal to <paramref name="sequence2"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="sequence1"/>, <paramref name="sequence2"/>, or
/// <paramref name="comparer"/> is null.</exception>
public static int LexicographicalCompare<T>(IEnumerable<T> sequence1, IEnumerable<T> sequence2, IComparer<T> comparer)
{
if (sequence1 == null)
throw new ArgumentNullException("sequence1");
if (sequence2 == null)
throw new ArgumentNullException("sequence2");
if (comparer == null)
throw new ArgumentNullException("comparer");
using (IEnumerator<T> enum1 = sequence1.GetEnumerator(), enum2 = sequence2.GetEnumerator()) {
bool continue1, continue2;
for (; ; ) {
continue1 = enum1.MoveNext(); continue2 = enum2.MoveNext();
if (!continue1 || !continue2)
break;
int compare = comparer.Compare(enum1.Current, enum2.Current);
if (compare != 0)
return compare;
}
// If both continue1 and continue2 are false, we reached the end of both sequences at the same
// time and the sequences are equal. Otherwise, the shorter sequence is considered first.
if (continue1 == continue2)
return 0;
else if (continue1)
return 1;
else
return -1;
}
}
#endregion Sorting
#region Comparers/Comparison utilities
/// <summary>
/// A private class used by the LexicographicalComparer method to compare sequences
/// (IEnumerable) of T by there Lexicographical ordering.
/// </summary>
[Serializable]
private class LexicographicalComparerClass<T> : IComparer<IEnumerable<T>>
{
readonly IComparer<T> itemComparer;
/// <summary>
/// Creates a new instance that comparer sequences of T by their lexicographical
/// ordered.
/// </summary>
/// <param name="itemComparer">The IComparer used to compare individual items of type T.</param>
public LexicographicalComparerClass(IComparer<T> itemComparer)
{
this.itemComparer = itemComparer;
}
public int Compare(IEnumerable<T> x, IEnumerable<T> y)
{
return LexicographicalCompare(x, y, itemComparer);
}
// For comparing this comparer to others.
public override bool Equals(object obj)
{
if (obj is LexicographicalComparerClass<T>)
return this.itemComparer.Equals(((LexicographicalComparerClass<T>)obj).itemComparer);
else
return false;
}
public override int GetHashCode()
{
return itemComparer.GetHashCode();
}
}
/// <summary>
/// Creates an IComparer instance that can be used for comparing ordered
/// sequences of type T; that is IEnumerable<Tgt;. This comparer can be used
/// for collections or algorithms that use sequences of T as an item type. The Lexicographical
/// ordered of sequences is for comparison.
/// </summary>
/// <remarks>T must implement either IComparable<T> and this implementation is used
/// to compare the items. </remarks>
/// <returns>At IComparer<IEnumerable<T>> that compares sequences of T.</returns>
public static IComparer<IEnumerable<T>> GetLexicographicalComparer<T>()
where T: IComparable<T>
{
return GetLexicographicalComparer(Comparer<T>.Default);
}
/// <summary>
/// Creates an IComparer instance that can be used for comparing ordered
/// sequences of type T; that is IEnumerable<Tgt;. This comparer can be uses
/// for collections or algorithms that use sequences of T as an item type. The Lexicographics
/// ordered of sequences is for comparison.
/// </summary>
/// <param name="comparer">A comparer instance used to compare individual items of type T.</param>
/// <returns>At IComparer<IEnumerable<T>> that compares sequences of T.</returns>
public static IComparer<IEnumerable<T>> GetLexicographicalComparer<T>(IComparer<T> comparer)
{
if (comparer == null)
throw new ArgumentNullException("comparer");
return new LexicographicalComparerClass<T>(comparer);
}
/// <summary>
/// Creates an IComparer instance that can be used for comparing ordered
/// sequences of type T; that is IEnumerable<Tgt;. This comparer can be uses
/// for collections or algorithms that use sequences of T as an item type. The Lexicographics
/// ordered of sequences is for comparison.
/// </summary>
/// <param name="comparison">A comparison delegate used to compare individual items of type T.</param>
/// <returns>At IComparer<IEnumerable<T>> that compares sequences of T.</returns>
public static IComparer<IEnumerable<T>> GetLexicographicalComparer<T>(Comparison<T> comparison)
{
if (comparison == null)
throw new ArgumentNullException("comparison");
return new LexicographicalComparerClass<T>(Comparers.ComparerFromComparison(comparison));
}
/// <summary>
/// An IComparer instance that can be used to reverse the sense of
/// a wrapped IComparer instance.
/// </summary>
[Serializable]
private class ReverseComparerClass<T> : IComparer<T>
{
readonly IComparer<T> comparer;
/// <summary>
/// </summary>
/// <param name="comparer">The comparer to reverse.</param>
public ReverseComparerClass(IComparer<T> comparer)
{
this.comparer = comparer;
}
public int Compare(T x, T y)
{
return - comparer.Compare(x, y);
}
// For comparing this comparer to others.
public override bool Equals(object obj)
{
if (obj is ReverseComparerClass<T>)
return this.comparer.Equals(((ReverseComparerClass<T>)obj).comparer);
else
return false;
}
public override int GetHashCode()
{
return comparer.GetHashCode();
}
}
/// <summary>
/// Reverses the order of comparison of an IComparer<T>. The resulting comparer can be used,
/// for example, to sort a collection in descending order. Equality and hash codes are unchanged.
/// </summary>
/// <typeparam name="T">The type of items thta are being compared.</typeparam>
/// <param name="comparer">The comparer to reverse.</param>
/// <returns>An IComparer<T> that compares items in the reverse order of <paramref name="comparer"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="comparer"/> is null.</exception>
public static IComparer<T> GetReverseComparer<T>(IComparer<T> comparer)
{
if (comparer == null)
throw new ArgumentNullException("comparer");
return new ReverseComparerClass<T>(comparer);
}
/// <summary>
/// A class, implementing IEqualityComparer<T>, that compares objects
/// for object identity only. Only Equals and GetHashCode can be used;
/// this implementation is not appropriate for ordering.
/// </summary>
[Serializable]
private class IdentityComparer<T> : IEqualityComparer<T>
where T:class
{
public bool Equals(T x, T y)
{
return (x == y);
}
public int GetHashCode(T obj)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj);
}
// For comparing two IComparers to see if they compare the same thing.
public override bool Equals(object obj)
{
return (obj != null && obj is IdentityComparer<T>);
}
// For comparing two IComparers to see if they compare the same thing.
public override int GetHashCode()
{
return 0x7143DDEF;
}
}
/// <summary>
/// Gets an IEqualityComparer<T> instance that can be used to compare objects
/// of type T for object identity only. Two objects compare equal only if they
/// are references to the same object.
/// </summary>
/// <returns>An IEqualityComparer<T> instance for identity comparison.</returns>
public static IEqualityComparer<T> GetIdentityComparer<T>()
where T : class
{
return new IdentityComparer<T>();
}
/// <summary>
/// Reverses the order of comparison of an Comparison<T>. The resulting comparison can be used,
/// for example, to sort a collection in descending order.
/// </summary>
/// <typeparam name="T">The type of items that are being compared.</typeparam>
/// <param name="comparison">The comparison to reverse.</param>
/// <returns>A Comparison<T> that compares items in the reverse order of <paramref name="comparison"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="comparison"/> is null.</exception>
public static Comparison<T> GetReverseComparison<T>(Comparison<T> comparison)
{
if (comparison == null)
throw new ArgumentNullException("comparison");
return delegate(T x, T y) { return -comparison(x, y); };
}
/// <summary>
/// Given a comparison delegate that compares two items of type T, gets an
/// IComparer<T> instance that performs the same comparison.
/// </summary>
/// <param name="comparison">The comparison delegate to use.</param>
/// <returns>An IComparer<T> that performs the same comparing operation
/// as <paramref name="comparison"/>.</returns>
public static IComparer<T> GetComparerFromComparison<T>(Comparison<T> comparison)
{
if (comparison == null)
throw new ArgumentNullException("comparison");
return Comparers.ComparerFromComparison(comparison);
}
/// <summary>
/// Given in IComparer<T> instenace that comparers two items from type T,
/// gets a Comparison delegate that performs the same comparison.
/// </summary>
/// <param name="comparer">The IComparer<T> instance to use.</param>
/// <returns>A Comparison<T> delegate that performans the same comparing
/// operation as <paramref name="comparer"/>.</returns>
public static Comparison<T> GetComparisonFromComparer<T>(IComparer<T> comparer)
{
if (comparer == null)
throw new ArgumentNullException("comparer");
return comparer.Compare;
}
/// <summary>
/// A private class used to implement GetCollectionEqualityComparer(). This
/// class implements IEqualityComparer<IEnumerable<T>gt; to compare
/// two enumerables for equality, where order is significant.
/// </summary>
[Serializable]
private class CollectionEqualityComparer<T> : IEqualityComparer<IEnumerable<T>>
{
private readonly IEqualityComparer<T> equalityComparer;
public CollectionEqualityComparer(IEqualityComparer<T> equalityComparer)
{
this.equalityComparer = equalityComparer;
}
public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
{
return Algorithms.EqualCollections(x, y, equalityComparer);
}
public int GetHashCode(IEnumerable<T> obj)
{
int hash = 0x374F293E;
foreach (T t in obj) {
int itemHash = Util.GetHashCode(t, equalityComparer);
hash += itemHash;
hash = (hash << 9) | (hash >> 23);
}
return hash & 0x7FFFFFFF;
}
}
/// <summary>
/// Gets an IEqualityComparer<IEnumerable<T>> implementation
/// that can be used to compare collections of elements (of type T). Two collections
/// of T's are equal if they have the same number of items, and corresponding
/// items are equal, considered in order. This is the same notion of equality as
/// in Algorithms.EqualCollections, but encapsulated in an IEqualityComparer<IEnumerable<T>> implementation.
/// </summary>
/// <example>
/// The following code creates a Dictionary where the keys are a collection of strings.
/// <code>
/// Dictionary<IEnumerable<string>, int> =
/// new Dictionary<IEnumerable<string>, int>(Algorithms.GetCollectionEqualityComparer<string>());
/// </code>
/// </example>
/// <returns>IEqualityComparer<IEnumerable<T>> implementation suitable for
/// comparing collections of T for equality.</returns>
/// <seealso cref="Algorithms.EqualCollections{T}"/>
public static IEqualityComparer<IEnumerable<T>> GetCollectionEqualityComparer<T>()
{
return GetCollectionEqualityComparer(EqualityComparer<T>.Default);
}
/// <summary>
/// <para>Gets an IEqualityComparer<IEnumerable<T>> implementation
/// that can be used to compare collections of elements (of type T). Two collections
/// of T's are equal if they have the same number of items, and corresponding
/// items are equal, considered in order. This is the same notion of equality as
/// in Algorithms.EqualCollections, but encapsulated in an IEqualityComparer<IEnumerable<T>> implementation.</para>
/// <para>An IEqualityComparer<T> is used to determine if individual T's are equal</para>
/// </summary>
/// <example>
/// The following code creates a Dictionary where the keys are a collection of strings, compared in a case-insensitive way
/// <code>
/// Dictionary<IEnumerable<string>, int> =
/// new Dictionary<IEnumerable<string>, int>(Algorithms.GetCollectionEqualityComparer<string>(StringComparer.CurrentCultureIgnoreCase));
/// </code>
/// </example>
/// <param name="equalityComparer">An IEqualityComparer<T> implementation used to compare individual T's.</param>
/// <returns>IEqualityComparer<IEnumerable<T>> implementation suitable for
/// comparing collections of T for equality.</returns>
/// <seealso cref="Algorithms.EqualCollections{T}"/>
public static IEqualityComparer<IEnumerable<T>> GetCollectionEqualityComparer<T>(IEqualityComparer<T> equalityComparer)
{
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
return new CollectionEqualityComparer<T>(equalityComparer);
}
/// <summary>
/// A private class used to implement GetSetEqualityComparer(). This
/// class implements IEqualityComparer<IEnumerable<T>gt; to compare
/// two enumerables for equality, where order is not significant.
/// </summary>
[Serializable]
private class SetEqualityComparer<T> : IEqualityComparer<IEnumerable<T>>
{
private readonly IEqualityComparer<T> equalityComparer;
public SetEqualityComparer(IEqualityComparer<T> equalityComparer)
{
this.equalityComparer = equalityComparer;
}
public bool Equals(IEnumerable<T> x, IEnumerable<T> y)
{
return Algorithms.EqualSets(x, y, equalityComparer);
}
public int GetHashCode(IEnumerable<T> obj)
{
int hash = 0x624F273C;
foreach (T t in obj) {
int itemHash = Util.GetHashCode(t, equalityComparer);
hash += itemHash;
}
return hash & 0x7FFFFFFF;
}
}
/// <summary>
/// <para>Gets an IEqualityComparer<IEnumerable<T>> implementation
/// that can be used to compare collections of elements (of type T). Two collections
/// of T's are equal if they have the same number of items, and corresponding
/// items are equal, without regard to order. This is the same notion of equality as
/// in Algorithms.EqualSets, but encapsulated in an IEqualityComparer<IEnumerable<T>> implementation.</para>
/// <para>An IEqualityComparer<T> is used to determine if individual T's are equal</para>
/// </summary>
/// <example>
/// The following code creates a Dictionary where the keys are a set of strings, without regard to order
/// <code>
/// Dictionary<IEnumerable<string>, int> =
/// new Dictionary<IEnumerable<string>, int>(Algorithms.GetSetEqualityComparer<string>(StringComparer.CurrentCultureIgnoreCase));
/// </code>
/// </example>
/// <returns>IEqualityComparer<IEnumerable<T>> implementation suitable for
/// comparing collections of T for equality, without regard to order.</returns>
/// <seealso cref="Algorithms.EqualSets{T}"/>
public static IEqualityComparer<IEnumerable<T>> GetSetEqualityComparer<T>()
{
return GetSetEqualityComparer(EqualityComparer<T>.Default);
}
/// <summary>
/// Gets an IEqualityComparer<IEnumerable<T>> implementation
/// that can be used to compare collections of elements (of type T). Two collections
/// of T's are equal if they have the same number of items, and corresponding
/// items are equal, without regard to order. This is the same notion of equality as
/// in Algorithms.EqualSets, but encapsulated in an IEqualityComparer<IEnumerable<T>> implementation.
/// </summary>
/// <example>
/// The following code creates a Dictionary where the keys are a set of strings, without regard to order
/// <code>
/// Dictionary<IEnumerable<string>, int> =
/// new Dictionary<IEnumerable<string>, int>(Algorithms.GetSetEqualityComparer<string>());
/// </code>
/// </example>
/// <param name="equalityComparer">An IEqualityComparer<T> implementation used to compare individual T's.</param>
/// <returns>IEqualityComparer<IEnumerable<T>> implementation suitable for
/// comparing collections of T for equality, without regard to order.</returns>
/// <seealso cref="Algorithms.EqualSets"/>
public static IEqualityComparer<IEnumerable<T>> GetSetEqualityComparer<T>(IEqualityComparer<T> equalityComparer)
{
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
return new SetEqualityComparer<T>(equalityComparer);
}
#endregion Sorting
#region Predicate operations
/// <summary>
/// Determines if a collection contains any item that satisfies the condition
/// defined by <paramref name="predicate"/>.
/// </summary>
/// <param name="collection">The collection to check all the items in.</param>
/// <param name="predicate">A delegate that defines the condition to check for.</param>
/// <returns>True if the collection contains one or more items that satisfy the condition
/// defined by <paramref name="predicate"/>. False if the collection does not contain
/// an item that satisfies <paramref name="predicate"/>.</returns>
public static bool Exists<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (predicate == null)
throw new ArgumentNullException("predicate");
foreach (T item in collection) {
if (predicate(item))
return true;
}
return false;
}
/// <summary>
/// Determines if all of the items in the collection satisfy the condition
/// defined by <paramref name="predicate"/>.
/// </summary>
/// <param name="collection">The collection to check all the items in.</param>
/// <param name="predicate">A delegate that defines the condition to check for.</param>
/// <returns>True if all of the items in the collection satisfy the condition
/// defined by <paramref name="predicate"/>, or if the collection is empty. False if one or more items
/// in the collection do not satisfy <paramref name="predicate"/>.</returns>
public static bool TrueForAll<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (predicate == null)
throw new ArgumentNullException("predicate");
foreach (T item in collection) {
if (!predicate(item))
return false;
}
return true;
}
/// <summary>
/// Counts the number of items in the collection that satisfy the condition
/// defined by <paramref name="predicate"/>.
/// </summary>
/// <param name="collection">The collection to count items in.</param>
/// <param name="predicate">A delegate that defines the condition to check for.</param>
/// <returns>The number of items in the collection that satisfy <paramref name="predicate"/>.</returns>
public static int CountWhere<T>(IEnumerable<T> collection, Predicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (predicate == null)
throw new ArgumentNullException("predicate");
int count = 0;
foreach (T item in collection) {
if (predicate(item))
++count;
}
return count;
}
/// <summary>
/// Removes all the items in the collection that satisfy the condition
/// defined by <paramref name="predicate"/>.
/// </summary>
/// <remarks>If the collection if an array or implements IList<T>, an efficient algorithm that
/// compacts items is used. If not, then ICollection<T>.Remove is used
/// to remove items from the collection. If the collection is an array or fixed-size list,
/// the non-removed elements are placed, in order, at the beginning of
/// the list, and the remaining list items are filled with a default value (0 or null).</remarks>
/// <param name="collection">The collection to check all the items in.</param>
/// <param name="predicate">A delegate that defines the condition to check for.</param>
/// <returns>Returns a collection of the items that were removed. This collection contains the
/// items in the same order that they orginally appeared in <paramref name="collection"/>.</returns>
public static ICollection<T> RemoveWhere<T>(ICollection<T> collection, Predicate<T> predicate)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (predicate == null)
throw new ArgumentNullException("predicate");
if (collection is T[])
collection = new ArrayWrapper<T>((T[])collection);
if (collection.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "collection");
IList<T> list = collection as IList<T>;
if (list != null) {
T item;
int i = -1, j = 0;
int listCount = list.Count;
List<T> removed = new List<T>();
// Remove item where predicate is true, compressing items to lower in the list. This is much more
// efficient than the naive algorithm that uses IList<T>.Remove().
while (j < listCount) {
item = list[j];
if (predicate(item)) {
removed.Add(item);
}
else {
++i;
if (i != j)
list[i] = item;
}
++j;
}
++i;
if (i < listCount) {
// remove items from the end.
if (list is IList && ((IList)list).IsFixedSize) {
// An array or similar. Null out the last elements.
while (i < listCount)
list[i++] = default(T);
}
else {
// Normal list.
while (i < listCount) {
list.RemoveAt(listCount - 1);
--listCount;
}
}
}
return removed;
}
else {
// We have to copy all the items to remove to a List, because collections can't be modifed
// during an enumeration.
List<T> removed = new List<T>();
foreach (T item in collection)
if (predicate(item))
removed.Add(item);
foreach (T item in removed)
collection.Remove(item);
return removed;
}
}
/// <summary>
/// Convert a collection of items by applying a delegate to each item in the collection. The resulting collection
/// contains the result of applying <paramref name="converter"/> to each item in <paramref name="sourceCollection"/>, in
/// order.
/// </summary>
/// <typeparam name="TSource">The type of items in the collection to convert.</typeparam>
/// <typeparam name="TDest">The type each item is being converted to.</typeparam>
/// <param name="sourceCollection">The collection of item being converted.</param>
/// <param name="converter">A delegate to the method to call, passing each item in <paramref name="sourceCollection"/>.</param>
/// <returns>The resulting collection from applying <paramref name="converter"/> to each item in <paramref name="sourceCollection"/>, in
/// order.</returns>
/// <exception cref="ArgumentNullException"><paramref name="sourceCollection"/> or <paramref name="converter"/> is null.</exception>
public static IEnumerable<TDest> Convert<TSource, TDest>(IEnumerable<TSource> sourceCollection, Converter<TSource, TDest> converter)
{
if (sourceCollection == null)
throw new ArgumentNullException("sourceCollection");
if (converter == null)
throw new ArgumentNullException("converter");
foreach (TSource sourceItem in sourceCollection)
yield return converter(sourceItem);
}
/// <summary>
/// Creates a delegate that converts keys to values by used a dictionary to map values. Keys
/// that a not present in the dictionary are converted to the default value (zero or null).
/// </summary>
/// <remarks>This delegate can be used as a parameter in Convert or ConvertAll methods to convert
/// entire collections.</remarks>
/// <param name="dictionary">The dictionary used to perform the conversion.</param>
/// <returns>A delegate to a method that converts keys to values. </returns>
public static Converter<TKey, TValue> GetDictionaryConverter<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
{
return GetDictionaryConverter(dictionary, default(TValue));
}
/// <summary>
/// Creates a delegate that converts keys to values by used a dictionary to map values. Keys
/// that a not present in the dictionary are converted to a supplied default value.
/// </summary>
/// <remarks>This delegate can be used as a parameter in Convert or ConvertAll methods to convert
/// entire collections.</remarks>
/// <param name="dictionary">The dictionary used to perform the conversion.</param>
/// <param name="defaultValue">The result of the conversion for keys that are not present in the dictionary.</param>
/// <returns>A delegate to a method that converts keys to values. </returns>
/// <exception cref="ArgumentNullException"><paramref name="dictionary"/> is null.</exception>
public static Converter<TKey, TValue> GetDictionaryConverter<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TValue defaultValue)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
return delegate(TKey key) {
TValue value;
if (dictionary.TryGetValue(key, out value))
return value;
else
return defaultValue;
};
}
/// <summary>
/// Performs the specified action on each item in a collection.
/// </summary>
/// <param name="collection">The collection to process.</param>
/// <param name="action">An Action delegate which is invoked for each item in <paramref name="collection"/>.</param>
public static void ForEach<T>(IEnumerable<T> collection, Action<T> action)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (action == null)
throw new ArgumentNullException("action");
foreach (T item in collection)
action(item);
}
/// <summary>
/// Partition a list or array based on a predicate. After partitioning, all items for which
/// the predicate returned true precede all items for which the predicate returned false.
/// </summary>
/// <remarks>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</remarks>
/// <param name="list">The list or array to partition.</param>
/// <param name="predicate">A delegate that defines the partitioning condition.</param>
/// <returns>The index of the first item in the second half of the partition; i.e., the first item for
/// which <paramref name="predicate"/> returned false. If the predicate was true for all items
/// in the list, list.Count is returned.</returns>
public static int Partition<T>(IList<T> list, Predicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (predicate == null)
throw new ArgumentNullException("predicate");
if (list is T[])
list = new ArrayWrapper<T>((T[])list);
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
// Move from opposite ends of the list, swapping when necessary.
int i = 0, j = list.Count - 1;
for (;;) {
while (i <= j && predicate(list[i]))
++i;
while (i <= j && !predicate(list[j]))
--j;
if (i > j)
break;
else {
T temp = list[i];
list[i] = list[j];
list[j] = temp;
++i;
--j;
}
}
return i;
}
/// <summary>
/// Partition a list or array based on a predicate. After partitioning, all items for which
/// the predicate returned true precede all items for which the predicate returned false.
/// The partition is stable, which means that if items X and Y have the same result from
/// the predicate, and X precedes Y in the original list, X will precede Y in the
/// partitioned list.
/// </summary>
/// <remarks>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</remarks>
/// <param name="list">The list or array to partition.</param>
/// <param name="predicate">A delegate that defines the partitioning condition.</param>
/// <returns>The index of the first item in the second half of the partition; i.e., the first item for
/// which <paramref name="predicate"/> returned false. If the predicate was true for all items
/// in the list, list.Count is returned.</returns>
public static int StablePartition<T>(IList<T> list, Predicate<T> predicate)
{
if (list == null)
throw new ArgumentNullException("list");
if (predicate == null)
throw new ArgumentNullException("predicate");
if (list is T[])
list = new ArrayWrapper<T>((T[])list);
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
int listCount = list.Count;
if (listCount == 0)
return 0;
T[] temp = new T[listCount];
// Copy from list to temp buffer, true items at fron, false item (in reverse order) at back.
int i = 0, j = listCount - 1;
foreach (T item in list) {
if (predicate(item))
temp[i++] = item;
else
temp[j--] = item;
}
// Copy back to the original list.
int index = 0;
while (index < i) {
list[index] = temp[index];
index++;
}
j = listCount - 1;
while (index < listCount)
list[index++] = temp[j--];
return i;
}
#endregion Predicate operations
#region Miscellaneous operations on IEnumerable
/// <summary>
/// Concatenates all the items from several collections. The collections need not be of the same type, but
/// must have the same item type.
/// </summary>
/// <param name="collections">The set of collections to concatenate. In many languages, this parameter
/// can be specified as several individual parameters.</param>
/// <returns>An IEnumerable that enumerates all the items in each of the collections, in order.</returns>
public static IEnumerable<T> Concatenate<T>(params IEnumerable<T>[] collections)
{
if (collections == null)
throw new ArgumentNullException("collections");
foreach (IEnumerable<T> coll in collections) {
foreach (T item in coll)
yield return item;
}
}
/// <summary>
/// Determines if the two collections contain equal items in the same order. The two collections do not need
/// to be of the same type; it is permissible to compare an array and an OrderedBag, for instance.
/// </summary>
/// <remarks>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</remarks>
/// <typeparam name="T">The type of items in the collections.</typeparam>
/// <param name="collection1">The first collection to compare.</param>
/// <param name="collection2">The second collection to compare.</param>
/// <returns>True if the collections have equal items in the same order. If both collections are empty, true is returned.</returns>
public static bool EqualCollections<T>(IEnumerable<T> collection1, IEnumerable<T> collection2)
{
return EqualCollections(collection1, collection2, EqualityComparer<T>.Default);
}
/// <summary>
/// Determines if the two collections contain equal items in the same order. The passed
/// instance of IEqualityComparer<T> is used for determining if two items are equal.
/// </summary>
/// <typeparam name="T">The type of items in the collections.</typeparam>
/// <param name="collection1">The first collection to compare.</param>
/// <param name="collection2">The second collection to compare.</param>
/// <param name="equalityComparer">The IEqualityComparer<T> used to compare items for equality.
/// Only the Equals member function of this interface is called.</param>
/// <returns>True if the collections have equal items in the same order. If both collections are empty, true is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/>, <paramref name="collection2"/>, or
/// <paramref name="equalityComparer"/> is null.</exception>
public static bool EqualCollections<T>(IEnumerable<T> collection1, IEnumerable<T> collection2, IEqualityComparer<T> equalityComparer)
{
if (collection1 == null)
throw new ArgumentNullException("collection1");
if (collection2 == null)
throw new ArgumentNullException("collection2");
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
using (IEnumerator<T> enum1 = collection1.GetEnumerator(), enum2 = collection2.GetEnumerator()) {
bool continue1, continue2;
for (; ; ) {
continue1 = enum1.MoveNext(); continue2 = enum2.MoveNext();
if (!continue1 || !continue2)
break;
if (!equalityComparer.Equals(enum1.Current, enum2.Current))
return false; // the two items are not equal.
}
// If both continue1 and continue2 are false, we reached the end of both sequences at the same
// time and found success. If one is true and one is false, the sequences were of difference lengths -- failure.
return (continue1 == continue2);
}
}
/// <summary>
/// Determines if the two collections contain "equal" items in the same order. The passed
/// BinaryPredicate is used to determine if two items are "equal".
/// </summary>
/// <remarks>Since an arbitrary BinaryPredicate is passed to this function, what is being tested
/// for need not be equality. For example, the following code determines if each integer in
/// list1 is less than or equal to the corresponding integer in list2.
/// <code>
/// List<int> list1, list2;
/// if (EqualCollections(list1, list2, delegate(int x, int y) { return x <= y; }) {
/// // the check is true...
/// }
/// </code>
/// </remarks>
/// <typeparam name="T">The type of items in the collections.</typeparam>
/// <param name="collection1">The first collection to compare.</param>
/// <param name="collection2">The second collection to compare.</param>
/// <param name="predicate">The BinaryPredicate used to compare items for "equality".
/// This predicate can compute any relation between two items; it need not represent equality or an equivalence relation.</param>
/// <returns>True if <paramref name="predicate"/>returns true for each corresponding pair of
/// items in the two collections. If both collections are empty, true is returned.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection1"/>, <paramref name="collection2"/>, or
/// <paramref name="predicate"/> is null.</exception>
public static bool EqualCollections<T>(IEnumerable<T> collection1, IEnumerable<T> collection2, BinaryPredicate<T> predicate)
{
if (collection1 == null)
throw new ArgumentNullException("collection1");
if (collection2 == null)
throw new ArgumentNullException("collection2");
if (predicate == null)
throw new ArgumentNullException("predicate");
using (IEnumerator<T> enum1 = collection1.GetEnumerator(), enum2 = collection2.GetEnumerator()) {
bool continue1, continue2;
for (; ; ) {
continue1 = enum1.MoveNext(); continue2 = enum2.MoveNext();
if (!continue1 || !continue2)
break;
if (!predicate(enum1.Current, enum2.Current))
return false; // the two items are not equal.
}
// If both continue1 and continue2 are false, we reached the end of both sequences at the same
// time and found success. If one is true and one is false, the sequences were of difference lengths -- failure.
return (continue1 == continue2);
}
}
/// <summary>
/// Create an array with the items in a collection.
/// </summary>
/// <remarks>If <paramref name="collection"/> implements ICollection<T>T, then
/// ICollection<T>.CopyTo() is used to fill the array. Otherwise, the IEnumerable<T>.GetEnumerator()
/// is used to fill the array.</remarks>
/// <typeparam name="T">Element type of the collection.</typeparam>
/// <param name="collection">Collection to create array from.</param>
/// <returns>An array with the items from the collection, in enumeration order.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
public static T[] ToArray<T>(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
ICollection<T> coll = collection as ICollection<T>;
if (coll != null) {
// Use ICollection methods to do it more efficiently.
T[] array = new T[coll.Count];
coll.CopyTo(array, 0);
return array;
}
else {
// We can't allocate the correct size array now, because IEnumerable doesn't
// have a Count property. We could enumerate twice, once to count and once
// to copy. Or we could enumerate once, copying to a List, then copy the list
// to the correct size array. The latter algorithm seems more efficient, although
// it allocates extra memory for the list which is then discarded.
List<T> list = new List<T>(collection);
return list.ToArray();
}
}
/// <summary>
/// Count the number of items in an IEnumerable<T> collection. If
/// a more specific collection type is being used, it is more efficient to use
/// the Count property, if one is provided.
/// </summary>
/// <remarks>If the collection implements ICollection<T>, this method
/// simply returns ICollection<T>.Count. Otherwise, it enumerates all items
/// and counts them.</remarks>
/// <param name="collection">The collection to count items in.</param>
/// <returns>The number of items in the collection.</returns>
/// <exception cref="ArgumentNullException"><paramref name="collection"/> is null.</exception>
public static int Count<T>(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
// If it's really an ICollection, use that Count property as it is much faster.
if (collection is ICollection<T>)
return ((ICollection<T>)collection).Count;
// Traverse the collection and count the elements.
int count = 0;
foreach (T item in collection)
++count;
return count;
}
/// <summary>
/// Counts the number of items in the collection that are equal to <paramref name="find"/>.
/// </summary>
/// <remarks>The default sense of equality for T is used, as defined by T's
/// implementation of IComparable<T>.Equals or object.Equals.</remarks>
/// <param name="collection">The collection to count items in.</param>
/// <param name="find">The item to compare to.</param>
/// <returns>The number of items in the collection that are equal to <paramref name="find"/>.</returns>
public static int CountEqual<T>(IEnumerable<T> collection, T find)
{
return CountEqual(collection, find, EqualityComparer<T>.Default);
}
/// <summary>
/// Counts the number of items in the collection that are equal to <paramref name="find"/>.
/// </summary>
/// <param name="collection">The collection to count items in.</param>
/// <param name="find">The item to compare to.</param>
/// <param name="equalityComparer">The comparer to use to determine if two items are equal. Only the Equals
/// member function will be called.</param>
/// <returns>The number of items in the collection that are equal to <paramref name="find"/>.</returns>
/// <exception cref="ArgumentException"><paramref name="collection"/> or <paramref name="equalityComparer"/>
/// is null.</exception>
public static int CountEqual<T>(IEnumerable<T> collection, T find, IEqualityComparer<T> equalityComparer)
{
if (collection == null)
throw new ArgumentException("collection");
if (equalityComparer == null)
throw new ArgumentNullException("equalityComparer");
int count = 0;
foreach (T item in collection) {
if (equalityComparer.Equals(item, find))
++count;
}
return count;
}
/// <summary>
/// Creates an IEnumerator that enumerates a given item <paramref name="n"/> times.
/// </summary>
/// <example>
/// The following creates a list consisting of 1000 copies of the double 1.0.
/// <code>
/// List<double> list = new List<double>(Algorithms.NCopiesOf(1000, 1.0));
/// </code></example>
/// <param name="n">The number of times to enumerate the item.</param>
/// <param name="item">The item that should occur in the enumeration.</param>
/// <returns>An IEnumerable<T> that yields <paramref name="n"/> copies
/// of <paramref name="item"/>.</returns>
/// <exception cref="ArgumentOutOfRangeException">The argument <paramref name="n"/> is less than zero.</exception>
public static IEnumerable<T> NCopiesOf<T>(int n, T item)
{
if (n < 0)
throw new ArgumentOutOfRangeException("n", n, Strings.ArgMustNotBeNegative);
while (n-- > 0) {
yield return item;
}
}
#endregion Miscellaneous operations on IEnumerable
#region Miscellaneous operations on IList
/// <summary>
/// Replaces each item in a list with a given value. The list does not change in size.
/// </summary>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to modify.</param>
/// <param name="value">The value to fill with.</param>
/// <exception cref="ArgumentException"><paramref name="list"/> is a read-only list.</exception>
/// <exception cref="ArgumentNullException"><paramref name="list"/> is null.</exception>
public static void Fill<T>(IList<T> list, T value)
{
if (list == null)
throw new ArgumentNullException("list");
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
int count = list.Count;
for (int i = 0; i < count; ++i) {
list[i] = value;
}
}
/// <summary>
/// Replaces each item in a array with a given value.
/// </summary>
/// <param name="array">The array to modify.</param>
/// <param name="value">The value to fill with.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is null.</exception>
public static void Fill<T>(T[] array, T value)
{
if (array == null)
throw new ArgumentNullException("array");
for (int i = 0; i < array.Length; ++i) {
array[i] = value;
}
}
/// <summary>
/// Replaces each item in a part of a list with a given value.
/// </summary>
/// <typeparam name="T">The type of items in the list.</typeparam>
/// <param name="list">The list to modify.</param>
/// <param name="start">The index at which to start filling. The first index in the list has index 0.</param>
/// <param name="count">The number of items to fill.</param>
/// <param name="value">The value to fill with.</param>
/// <exception cref="ArgumentException"><paramref name="list"/> is a read-only list.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> or <paramref name="count"/> is negative, or
/// <paramref name="start"/> + <paramref name="count"/> is greater than <paramref name="list"/>.Count.</exception>
/// <exception cref="ArgumentNullException"><paramref name="list"/> is null.</exception>
public static void FillRange<T>(IList<T> list, int start, int count, T value)
{
if (list == null)
throw new ArgumentNullException("list");
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
if (count == 0)
return;
if (start < 0 || start >= list.Count)
throw new ArgumentOutOfRangeException("start");
if (count < 0 || count > list.Count || start > list.Count - count)
throw new ArgumentOutOfRangeException("count");
for (int i = start; i < count + start; ++i) {
list[i] = value;
}
}
/// <summary>
/// Replaces each item in a part of a array with a given value.
/// </summary>
/// <param name="array">The array to modify.</param>
/// <param name="start">The index at which to start filling. The first index in the array has index 0.</param>
/// <param name="count">The number of items to fill.</param>
/// <param name="value">The value to fill with.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> or <paramref name="count"/> is negative, or
/// <paramref name="start"/> + <paramref name="count"/> is greater than <paramref name="array"/>.Length.</exception>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is null.</exception>
public static void FillRange<T>(T[] array, int start, int count, T value)
{
if (array == null)
throw new ArgumentNullException("array");
if (count == 0)
return;
if (start < 0 || start >= array.Length)
throw new ArgumentOutOfRangeException("start");
if (count < 0 || count > array.Length || start > array.Length - count)
throw new ArgumentOutOfRangeException("count");
for (int i = start; i < count + start; ++i) {
array[i] = value;
}
}
/// <summary>
/// Copies all of the items from the collection <paramref name="source"/> to the list <paramref name="dest"/>, starting
/// at the index <paramref name="destIndex"/>. If necessary, the size of the destination list is expanded.
/// </summary>
/// <param name="source">The collection that provide the source items. </param>
/// <param name="dest">The list to store the items into.</param>
/// <param name="destIndex">The index to begin copying items to.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="destIndex"/> is negative or
/// greater than <paramref name="dest"/>.Count.</exception>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="dest"/> is null.</exception>
public static void Copy<T>(IEnumerable<T> source, IList<T> dest, int destIndex)
{
Copy(source, dest, destIndex, int.MaxValue);
}
/// <summary>
/// Copies all of the items from the collection <paramref name="source"/> to the array <paramref name="dest"/>, starting
/// at the index <paramref name="destIndex"/>.
/// </summary>
/// <param name="source">The collection that provide the source items. </param>
/// <param name="dest">The array to store the items into.</param>
/// <param name="destIndex">The index to begin copying items to.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="destIndex"/> is negative or
/// greater than <paramref name="dest"/>.Length.</exception>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="dest"/> is null.</exception>
/// <exception cref="ArgumentException">The collection has more items than will fit into the array. In this case, the array
/// has been filled with as many items as fit before the exception is thrown.</exception>
public static void Copy<T>(IEnumerable<T> source, T[] dest, int destIndex)
{
if (source == null)
throw new ArgumentNullException("source");
if (dest == null)
throw new ArgumentNullException("dest");
if (destIndex < 0 || destIndex > dest.Length)
throw new ArgumentOutOfRangeException("destIndex");
using (IEnumerator<T> sourceEnum = source.GetEnumerator()) {
// Overwrite items to the end of the destination array. If we hit the end, throw.
while (sourceEnum.MoveNext()) {
if (destIndex >= dest.Length)
throw new ArgumentException(Strings.ArrayTooSmall, "dest");
dest[destIndex++] = sourceEnum.Current;
}
}
}
/// <summary>
/// Copies at most <paramref name="count"/> items from the collection <paramref name="source"/> to the list <paramref name="dest"/>, starting
/// at the index <paramref name="destIndex"/>. If necessary, the size of the destination list is expanded. The source collection must not be
/// the destination list or part thereof.
/// </summary>
/// <param name="source">The collection that provide the source items. </param>
/// <param name="dest">The list to store the items into.</param>
/// <param name="destIndex">The index to begin copying items to.</param>
/// <param name="count">The maximum number of items to copy.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="destIndex"/> is negative or
/// greater than <paramref name="dest"/>.Count</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is negative.</exception>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="dest"/> is null.</exception>
public static void Copy<T>(IEnumerable<T> source, IList<T> dest, int destIndex, int count)
{
if (source == null)
throw new ArgumentNullException("source");
if (dest == null)
throw new ArgumentNullException("dest");
if (dest.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "dest");
int destCount = dest.Count;
if (destIndex < 0 || destIndex > destCount)
throw new ArgumentOutOfRangeException("destIndex");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
using (IEnumerator<T> sourceEnum = source.GetEnumerator()) {
// First, overwrite items to the end of the destination list.
while (destIndex < destCount && count > 0 && sourceEnum.MoveNext()) {
dest[destIndex++] = sourceEnum.Current;
--count;
}
// Second, insert items until done.
while (count > 0 && sourceEnum.MoveNext()) {
dest.Insert(destCount++, sourceEnum.Current);
--count;
}
}
}
/// <summary>
/// Copies at most <paramref name="count"/> items from the collection <paramref name="source"/> to the array <paramref name="dest"/>, starting
/// at the index <paramref name="destIndex"/>. The source collection must not be
/// the destination array or part thereof.
/// </summary>
/// <param name="source">The collection that provide the source items. </param>
/// <param name="dest">The array to store the items into.</param>
/// <param name="destIndex">The index to begin copying items to.</param>
/// <param name="count">The maximum number of items to copy. The array must be large enought to fit this number of items.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="destIndex"/> is negative or
/// greater than <paramref name="dest"/>.Length.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is negative or <paramref name="destIndex"/> + <paramref name="count"/>
/// is greater than <paramref name="dest"/>.Length.</exception>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="dest"/> is null.</exception>
public static void Copy<T>(IEnumerable<T> source, T[] dest, int destIndex, int count)
{
if (source == null)
throw new ArgumentNullException("source");
if (dest == null)
throw new ArgumentNullException("dest");
int destCount = dest.Length;
if (destIndex < 0 || destIndex > destCount)
throw new ArgumentOutOfRangeException("destIndex");
if (count < 0 || destIndex + count > destCount)
throw new ArgumentOutOfRangeException("count");
using (IEnumerator<T> sourceEnum = source.GetEnumerator()) {
// First, overwrite items to the end of the destination array.
while (destIndex < destCount && count > 0 && sourceEnum.MoveNext()) {
dest[destIndex++] = sourceEnum.Current;
--count;
}
}
}
/// <summary>
/// Copies <paramref name="count"/> items from the list <paramref name="source"/>, starting at the index <paramref name="sourceIndex"/>,
/// to the list <paramref name="dest"/>, starting at the index <paramref name="destIndex"/>. If necessary, the size of the destination list is expanded.
/// The source and destination lists may be the same.
/// </summary>
/// <param name="source">The collection that provide the source items. </param>
/// <param name="sourceIndex">The index within <paramref name="source"/>to begin copying items from.</param>
/// <param name="dest">The list to store the items into.</param>
/// <param name="destIndex">The index within <paramref name="dest"/>to begin copying items to.</param>
/// <param name="count">The maximum number of items to copy.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="sourceIndex"/> is negative or
/// greater than <paramref name="source"/>.Count</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="destIndex"/> is negative or
/// greater than <paramref name="dest"/>.Count</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is negative or too large.</exception>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="dest"/> is null.</exception>
public static void Copy<T>(IList<T> source, int sourceIndex, IList<T> dest, int destIndex, int count)
{
if (source == null)
throw new ArgumentNullException("source");
if (dest == null)
throw new ArgumentNullException("dest");
if (dest.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "dest");
int sourceCount = source.Count;
int destCount = dest.Count;
if (sourceIndex < 0 || sourceIndex >= sourceCount)
throw new ArgumentOutOfRangeException("sourceIndex");
if (destIndex < 0 || destIndex > destCount)
throw new ArgumentOutOfRangeException("destIndex");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (count > sourceCount - sourceIndex)
count = sourceCount - sourceIndex;
if (source == dest && sourceIndex > destIndex) {
while (count > 0) {
dest[destIndex++] = source[sourceIndex++];
--count;
}
}
else {
int si, di;
// First, insert any items needed at the end
if (destIndex + count > destCount) {
int numberToInsert = destIndex + count - destCount;
si = sourceIndex + (count - numberToInsert);
di = destCount;
count -= numberToInsert;
while (numberToInsert > 0) {
dest.Insert(di++, source[si++]);
--numberToInsert;
}
}
// Do the copy, from end to beginning in case of overlap.
si = sourceIndex + count - 1;
di = destIndex + count - 1;
while (count > 0) {
dest[di--] = source[si--];
--count;
}
}
}
/// <summary>
/// Copies <paramref name="count"/> items from the list or array <paramref name="source"/>, starting at the index <paramref name="sourceIndex"/>,
/// to the array <paramref name="dest"/>, starting at the index <paramref name="destIndex"/>.
/// The source may be the same as the destination array.
/// </summary>
/// <param name="source">The list or array that provide the source items. </param>
/// <param name="sourceIndex">The index within <paramref name="source"/>to begin copying items from.</param>
/// <param name="dest">The array to store the items into.</param>
/// <param name="destIndex">The index within <paramref name="dest"/>to begin copying items to.</param>
/// <param name="count">The maximum number of items to copy. The destination array must be large enough to hold this many items.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="sourceIndex"/> is negative or
/// greater than <paramref name="source"/>.Count</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="destIndex"/> is negative or
/// greater than <paramref name="dest"/>.Length</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="count"/> is negative or too large.</exception>
/// <exception cref="ArgumentNullException"><paramref name="source"/> or <paramref name="dest"/> is null.</exception>
public static void Copy<T>(IList<T> source, int sourceIndex, T[] dest, int destIndex, int count)
{
if (source == null)
throw new ArgumentNullException("source");
if (dest == null)
throw new ArgumentNullException("dest");
int sourceCount = source.Count;
int destCount = dest.Length;
if (sourceIndex < 0 || sourceIndex >= sourceCount)
throw new ArgumentOutOfRangeException("sourceIndex");
if (destIndex < 0 || destIndex > destCount)
throw new ArgumentOutOfRangeException("destIndex");
if (count < 0 || destIndex + count > destCount)
throw new ArgumentOutOfRangeException("count");
if (count > sourceCount - sourceIndex)
count = sourceCount - sourceIndex;
if (source is T[]) {
// Array.Copy is probably faster, and also handles any overlapping issues.
Array.Copy((T[])source, sourceIndex, dest, destIndex, count);
}
else {
int si = sourceIndex;
int di = destIndex;
while (count > 0) {
dest[di++] = source[si++];
--count;
}
}
}
/// <summary>
/// Reverses a list and returns the reversed list, without changing the source list.
/// </summary>
/// <param name="source">The list to reverse.</param>
/// <returns>A collection that contains the items from <paramref name="source"/> in reverse order.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
public static IEnumerable<T> Reverse<T>(IList<T> source)
{
if (source == null)
throw new ArgumentNullException("source");
for (int i = source.Count - 1; i >= 0; --i)
yield return source[i];
}
/// <summary>
/// Reverses a list or array in place.
/// </summary>
/// <remarks>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</remarks>
/// <param name="list">The list or array to reverse.</param>
/// <exception cref="ArgumentNullException"><paramref name="list"/> is null.</exception>
/// <exception cref="ArgumentException"><paramref name="list"/> is read only.</exception>
public static void ReverseInPlace<T>(IList<T> list)
{
if (list == null)
throw new ArgumentNullException("list");
if (list is T[])
list = new ArrayWrapper<T>((T[])list);
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
int i, j;
i = 0;
j = list.Count - 1;
while (i < j) {
T temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
}
/// <summary>
/// Rotates a list and returns the rotated list, without changing the source list.
/// </summary>
/// <param name="source">The list to rotate.</param>
/// <param name="amountToRotate">The number of elements to rotate. This value can be positive or negative.
/// For example, rotating by positive 3 means that source[3] is the first item in the returned collection.
/// Rotating by negative 3 means that source[source.Count - 3] is the first item in the returned collection.</param>
/// <returns>A collection that contains the items from <paramref name="source"/> in rotated order.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
public static IEnumerable<T> Rotate<T>(IList<T> source, int amountToRotate)
{
if (source == null)
throw new ArgumentNullException("source");
int count = source.Count;
if (count != 0) {
amountToRotate = amountToRotate % count;
if (amountToRotate < 0)
amountToRotate += count;
// Do it in two parts.
for (int i = amountToRotate; i < count; ++i)
yield return source[i];
for (int i = 0; i < amountToRotate; ++i)
yield return source[i];
}
}
/// <summary>
/// Rotates a list or array in place.
/// </summary>
/// <remarks>Although arrays cast to IList<T> are normally read-only, this method
/// will work correctly and modify an array passed as <paramref name="list"/>.</remarks>
/// <param name="list">The list or array to rotate.</param>
/// <param name="amountToRotate">The number of elements to rotate. This value can be positive or negative.
/// For example, rotating by positive 3 means that list[3] is the first item in the resulting list.
/// Rotating by negative 3 means that list[list.Count - 3] is the first item in the resulting list.</param>
/// <exception cref="ArgumentNullException"><paramref name="list"/> is null.</exception>
public static void RotateInPlace<T>(IList<T> list, int amountToRotate)
{
if (list == null)
throw new ArgumentNullException("list");
if (list is T[])
list = new ArrayWrapper<T>((T[])list);
if (list.IsReadOnly)
throw new ArgumentException(Strings.ListIsReadOnly, "list");
int count = list.Count;
if (count != 0) {
amountToRotate = amountToRotate % count;
if (amountToRotate < 0)
amountToRotate += count;
int itemsLeft = count;
int indexStart = 0;
while (itemsLeft > 0) {
// Rotate an orbit of items through the list. If itemsLeft is relatively prime
// to count, this will rotate everything. If not, we need to do this several times until
// all items have been moved.
int index = indexStart;
T itemStart = list[indexStart];
for (;;) {
--itemsLeft;
int nextIndex = index + amountToRotate;
if (nextIndex >= count)
nextIndex -= count;
if (nextIndex == indexStart) {
list[index] = itemStart;
break;
}
else {
list[index] = list[nextIndex];
index = nextIndex;
}
}
// Move to the next orbit.
++indexStart;
}
}
}
#endregion Miscellaneous operations on IList
}
}
|