# Question
Title: Print 1 to 1000 in C++ without semi-colons
Following this popular question, present your solution which prints the numbers 1 to 1000 (all of them, not the string "1 to 1000" verbatim or something funny) in C++ without using any semi-colons. Unlike the original question, you may use conditionals and loops.

Solutions not requiring any compiler flags are preferred. Please mention any you use if you go against this. Undefined behaviour is allowed, so please specify the compiler and version you're using. Preference will be given to clever solutions. This is *not* a shortest code contest.

(I have a solution, which I'll post in 24 hours if a similar solution isn't posted before then.)

# Answer
The semicolon is not needed if you know the magic word. And no need to go obfuscated.

My solution has the additional fanciness that it doesn't use any comma either ;)

```
#include <iostream>
#define Please(x) if (x) {}

int Number(int x)
{
    if (x > 1)
        Please(Number(x-1))
    Please(std::cout << " " << x)
}

int main()
{
    Please(Number(1000))
}

```
> 35 votes

# Answer
```
#error "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"

```
> 29 votes

# Answer
```
main(){if(printf("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")){}}

```
> 26 votes

# Answer
Simple and almost idiomatic:

```
#include <iostream>

void loop(int low, int high)
{
  if ( low <= high                   &&
       std::cout << low << std::endl &&
       (loop(low+1, high), false) )
  {}
}

int main()
{
  if (loop(1, 1000), false) {}
}

```
> 12 votes

# Answer
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void) {
    if (char *p = (char *) malloc(10000U)) {
        if (__LINE__ < 106 && printf("%d\n", __LINE__ - 5)) {
            if (FILE *fp = fopen(__FILE__ ".tmp", "w")) {
                if (putc('\n', fp) &&
                    fwrite(p, 1U,
                           fread(p, 1U, 10000U, fopen(__FILE__, "r")), fp) &&
                    fclose(fp) ||
                    rename(__FILE__ ".tmp", __FILE__) ||
                    system("g++ " __FILE__ " && exec ./a.out")) {
                }
            }
        }
    }
}

```
> 9 votes

# Answer
Very similar to other solutions, but with a minor variation: The step variable is declared in the `if` condition:

```
#include <iostream>

int main(){
if (int x = 1)
    while (x <= 1000 && std::cout << x++ << std::endl) {}
}

```
> 7 votes

# Answer
This works great on my Linux machine:

```
#include <cstdlib>

int main()
{
    if (system("seq 1 1000")){}
}

```

I know, I know, ...it's not portable.
> 6 votes

# Answer
```
   /* No semicolons - or sense - //
  //  but at least there's      //
 //   undefined behaviour      //
*/                            //
#define __ if
#define ___ int
#define ____ std
#define ______ &&
#define _______ {
#define ________ (
#define _________ )
#define __________ }
#define ___________ .
#define ____________ ,
#define _____________ <
#define ______________ >
#define _______________ ::
#define zero 0
#define five 5
#include <cstdio>
#include <vector>
___ _ ________ ____ _______________
vector
_____________ ___ ______________ _____ _________ _______ __ ________ ____ _______________
distance
________ _____ ___________
emplace
________ _____ ___________
end
________ _________ ____________
zero
_________ ____________ _____ ___________
end
________ _________ _________ ______
printf
________
"%d\n\0 I may have got a bit too carried away with the obfuscation."
____________ _____ ___________
size
________ _________ _________ _____________
five
______ _ ________ _____ _________ _________ _______ __________ __________ ___
main
________ _________ _______ __ ________ _ ________ _______ __________ _________ _________  _______ __________ __________

```

Try it online!
> 6 votes

# Answer
```
#include <iostream>

void main()
{
   if (int i = 1)
   {
      while (std::cout << i << std::endl, i++ < 1000) {}
   }
}

```
> 5 votes

# Answer
*Almost* any regular-looking program can do, (no compiler specification necessary), like:

```
#include <stdio.h>
 void main(int argc, char*argv[])
{
if(argc=1000)
   while(argc-- && printf("%d ",1000-argc)) {}
}

```

can be formulated with C++ iostream in many different ways:

```
 #include <iostream>
 void main(int argc, char*argv[])
{
 if( ! (argc ^= argc) )
    while( argc++<1000 && std::cout.operator<<(argc) ) {

    }
}

```
> 5 votes

# Answer
```
#include <fstream>
#include <stdlib.h>

static int write_code(std::string str, std::ofstream out = std::ofstream())
{
    if (((
        out.open("my-thousand-tmp.cpp"),
        out) << str,
        out).close(),
        system("g++ -Wall -W -O3 my-thousand-tmp.cpp && exec ./a.out")
    ) {}

}

static int add_semicolons(std::string str, size_t i = 0)
{
    while (i < str.size())
        if (str[i++] == ':' && str[i-1]++) {}
    if (write_code(str)) {}
}

int main()
{
    if (add_semicolons(
        "#include <iostream>\n"
        "using namespace std:\n"
        "\n"
        "int main()\n"
        "{\n"
        "\tfor (int i = 1: i <= 1000: i++)\n"
        "\t\tcout << i << endl:\n"
        "\treturn 0:\n"
        "}\n"
    )) {}
}

```

I tried to initialize std::ofstream out by passing it as a parameter (i.e. `write_code(str, std::ofstream())` ), but apparently, the copy constructor is private, and an expression like this can't be passed by reference.
> 4 votes

# Answer
```
#include <stdio.h>
#include <stdlib.h>

int main()
{
    while(errno++ < 1000 && printf("%d ", errno)){}
}

```
> 4 votes

# Answer
```
#include <stdio.h>
#define __INTMAX_TYPE__ struct C { C(int x) { if (x == 1001?(puts(""),true):(printf("%d ",x),C(x+1),false)) {} } }
#include <stdint.h>
main(){if(intmax_t(1),false){}}

```
> 3 votes

# Answer
# C++ (gcc), 57 bytes

This takes advantage that the number of operands is always 1. (Not a codegolf, but I want to golf it...)

Thx to @ceilingcat for replacing printf with `__builtin_printf`.

```
main(int i){while(1001-i&&__builtin_printf("%d ",i++)){}}

```

Try it online!

# C (gcc), 43 bytes

They are also posting C answers, I assume?

```
main(i){while(1001-i&&printf("%d ",i++)){}}

```

Try it online!
> 2 votes

# Answer
I just saw the last comment… However I believe this is valid C++:

```
#include <cstdio>

int main(int argc, char**) {
  while (argc != 1001
    and std::printf("%d, ", argc++)) {}
}

```

compiler explorer
> 2 votes

# Answer
```
int main(int i)
{
while(printf("%d ",i) && i<=1000 && i++){}
}

```
> 1 votes

# Answer
C++11 based solution using a lambda function:

```
/* golf.cpp */
#include <iostream>

int main() {
    if( [] (int from, int to) -> bool {
        while(std::cout << from << " " && ++from <= to
            || std::cout << std::endl && false) {}
    } (1, 1000) ) {}
}

```

Compiles and works:

```
$ g++ --version | head -n1
g++ (GCC) 4.8.2 20131017 (Red Hat 4.8.2-1)
...
$ g++ -std=c++11 golf.cpp -o golf
$ ./golf

```

Bonus 1: Adjusting the range to be printed is as easy as editing the two parameters of the call.

Bonus 2: Output terminated by a new line.
> 1 votes

# Answer
Your run-o'-the-mill recursion-based answer.

```
#include <iostream>

int main(int i, char *k[]) {
    if(
        k != NULL && (
            i = 0
        ),
        std::cout << i << ' ',
        i < 1e3 &&
            main(i + 1, NULL)
    ) {}
}

```
> 1 votes

# Answer
# C++ with templates

```
#include <stdio.h>
#include <stdlib.h>

template<int THOU> void f() { while (printf("%d\n", THOU), f<THOU+1>(), 0) {} }
template<> void f<1001>() { while(exit(0), 0) {} }
int main()
{
    while (f<1>(), 0) {}
}

```

Notes:

* Linux version 3.2.0-58-generic (buildd@allspice) (gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) ) #88-Ubuntu SMP Tue Dec 3 17:37:58 UTC 2013
* 64 bit (amd64) version of Kubuntu
> 1 votes

---
Tags: popularity-contest, restricted-source, c++
---


title: Codegolf the permanent

text:
# Question
Title: Codegolf the permanent
The challenge is to write codegolf for the permanent of a matrix.

The permanent of an \\$n\times n\\$ matrix \\$A = a\_{i,j}\\$) is defined as

$$\text{perm}(A) = \sum\_{\sigma \in S\_n} \prod^n\_{i=1} a\_{i,\sigma(i)}$$

Here \\$S\_n\\$ represents the set of all permutations of \\$\[1, n\]\\$.

As an example (from the wiki):

$$\text{perm} \left( \begin{matrix} a & b & c \\ d & e & f \\ g & h & i \\ \end{matrix} \right) = aei + bfg + cdh + ceg + bdi + afh$$

Your code can take input however it wishes and give output in any sensible format but please include in your answer a full worked example including clear instructions for how to supply input to your code. To make the challenge a little more interesting, the matrix may include complex numbers.

The input matrix is always square and will be at most 6 by 6. You will also need to be able to handle the empty matrix which has permanent 1. There is no need to be able to handle the empty matrix (it was causing too many problems).

**Examples**

Input:

```
[[ 0.36697048+0.02459455j,  0.81148991+0.75269667j,  0.62568185+0.95950937j],
 [ 0.67985923+0.11419187j,  0.50131790+0.13067928j,  0.10330161+0.83532727j],
 [ 0.71085747+0.86199765j,  0.68902048+0.50886302j,  0.52729463+0.5974208j ]]

```

Output:

```
-1.7421952844303492+2.2476833142265793j

```

Input:

```
[[ 0.83702504+0.05801749j,  0.03912260+0.25027115j,  0.95507961+0.59109069j],
 [ 0.07330546+0.8569899j ,  0.47845015+0.45077079j,  0.80317410+0.5820795j ],
 [ 0.38306447+0.76444045j,  0.54067092+0.90206306j,  0.40001631+0.43832931j]]

```

Output:

```
-1.972117936608412+1.6081325306004794j

```

Input:

```
 [[ 0.61164611+0.42958732j,  0.69306292+0.94856925j,
     0.43860930+0.04104116j,  0.92232338+0.32857505j,
     0.40964318+0.59225476j,  0.69109847+0.32620144j],
   [ 0.57851263+0.69458731j,  0.21746623+0.38778693j,
     0.83334638+0.25805241j,  0.64855830+0.36137045j,
     0.65890840+0.06557287j,  0.25411493+0.37812483j],
   [ 0.11114704+0.44631335j,  0.32068031+0.52023283j,
     0.43360984+0.87037973j,  0.42752697+0.75343656j,
     0.23848512+0.96334466j,  0.28165516+0.13257001j],
   [ 0.66386467+0.21002292j,  0.11781236+0.00967473j,
     0.75491373+0.44880959j,  0.66749636+0.90076845j,
     0.00939420+0.06484633j,  0.21316223+0.4538433j ],
   [ 0.40175631+0.89340763j,  0.26849809+0.82500173j,
     0.84124107+0.23030393j,  0.62689175+0.61870543j,
     0.92430209+0.11914288j,  0.90655023+0.63096257j],
   [ 0.85830178+0.16441943j,  0.91144755+0.49943801j,
     0.51010550+0.60590678j,  0.51439995+0.37354955j,
     0.79986742+0.87723514j,  0.43231194+0.54571625j]]

```

Output:

```
-22.92354821347135-90.74278997288275j

```

You may not use any pre-existing functions to compute the permanent.

# Answer
> 14 votes
# J, 5 bytes

```
+/ .*

```

J does not offer builtins for the permanent or determinant but instead offers a conjunction `u . v y` which recursively expands `y` along the minors and calculates dyadic `u . v` between the cofactors and the output of the recursive call on the minors. The choices of `u` and `v` can vary. For example, using `u =: -/` and `v =: *` is `-/ .*` which is the determinant. Choices can even by `%/ .!` where `u=: %/`, reduce by division, and `v =: !` which is binomial coefficient. I'm not sure what that output signifies but you're free to choose your verbs.

An alternative implementation for **47 bytes** using the same method in my Mathematica answer.

```
_1{[:($@]$[:+//.*/)/0,.;@(<@(,0#~<:)"+2^i.@#)"{

```

This simulates a polynomial with *n* variables by creating a polynomial with one variable raised to powers of 2. This is held as a coefficient list and polynomial multiplication is performed using convolution, and the index at 2<sup>*n*</sup> will contain the result.

Another implementation for **31 bytes** is

```
+/@({.*1$:\.|:@}.)`(0{,)@.(1=#)

```

which is a slightly golfed version based on Laplace expansion taken from the J essay on determinants.

## Usage

```
   f =: +/ .*
   f 0 0 $ 0 NB. the empty matrix, create a shape with dimensions 0 x 0
1
   f 0.36697048j0.02459455 0.81148991j0.75269667 0.62568185j0.95950937 , 0.67985923j0.11419187  0.50131790j0.13067928 0.10330161j0.83532727 ,: 0.71085747j0.86199765 0.68902048j0.50886302 0.52729463j0.5974208
_1.7422j2.24768
   f 0.83702504j0.05801749 0.03912260j0.25027115 0.95507961j0.59109069 , 0.07330546j0.8569899 0.47845015j0.45077079 0.80317410j0.5820795 ,: 0.38306447j0.76444045 0.54067092j0.90206306 0.40001631j0.43832931
_1.97212j1.60813
   f 0.61164611j0.42958732 0.69306292j0.94856925 0.4386093j0.04104116 0.92232338j0.32857505 0.40964318j0.59225476 0.69109847j0.32620144 , 0.57851263j0.69458731 0.21746623j0.38778693 0.83334638j0.25805241 0.6485583j0.36137045 0.6589084j0.06557287 0.25411493j0.37812483 , 0.11114704j0.44631335 0.32068031j0.52023283 0.43360984j0.87037973 0.42752697j0.75343656 0.23848512j0.96334466 0.28165516j0.13257001 , 0.66386467j0.21002292 0.11781236j0.00967473 0.75491373j0.44880959 0.66749636j0.90076845 0.0093942j0.06484633 0.21316223j0.4538433 , 0.40175631j0.89340763 0.26849809j0.82500173 0.84124107j0.23030393 0.62689175j0.61870543 0.92430209j0.11914288 0.90655023j0.63096257 ,: 0.85830178j0.16441943 0.91144755j0.49943801 0.5101055j0.60590678 0.51439995j0.37354955 0.79986742j0.87723514 0.43231194j0.54571625
_22.9235j_90.7428

```

# Answer
> 13 votes
## Haskell, 59 bytes

```
a#((b:c):r)=b*p(a++map tail r)+(c:a)#r
_#_=0
p[]=1
p l=[]#l

```

This does a Laplace-like development along the first column, and uses that the order of the rows doesn't matter. It works for any numeric type.

Input is as list of lists:

```
Prelude> p [[1,2],[3,4]]
10

```

# Answer
> 8 votes
# Jelly, ~~10~~ 9 bytes

```
Œ!ŒDḢ€P€S

```

Try it online!

### How it works

```
Œ!ŒDḢ€P€S  Main link. Argument: M (matrix / 2D array)

Œ!         Generate all permutations of M's rows.
  ŒD       Compute the permutations' diagonals, starting with the main diagonal.
    Ḣ€     Head each; extract the main diagonal of each permutation.
      P€   Product each; compute the products of the main diagonals.
        S  Compute the sum of the products.

```

# Answer
> 7 votes
# Python 2, 75 bytes

Seems clunky... should be beatable.

```
P=lambda m,i=0:sum([r[i]*P(m[:j]+m[j+1:],i+1)for j,r in enumerate(m)]or[1])

```

# Answer
> 6 votes
# 05AB1E, ~~19~~ ~~14~~ 13 bytes

```
œvyvyNè}Pˆ}¯O

```

Try it online!

**Explanation**

```
œ              # get all permutations of rows
 v        }    # for each permutation
  yv   }       # for each row in the permutation
    yNè        # get the element at index row-index
        P      # product of elements
         ˆ     # add product to global array
           ¯O  # sum the products from the global array

```

# Answer
> 5 votes
# Python 2, 139 bytes

```
from itertools import*
def p(a):c=complex;r=range(len(a));return sum(reduce(c.__mul__,[a[j][p[j]]for j in r],c(1))for p in permutations(r))

```

**repl.it**

Implements the naïve algorithm which blindly follows the definition.

# Answer
> 4 votes
# Ruby, ~~74~~ 63 bytes

```
->a{p=0;a.permutation{|b|n=1;i=-1;a.map{n*=b[i+=1][i]};p+=n};p}

```

A straightforward translation of the formula. Several bytes saved thanks to ezrast.

## Explanation

```
->a{
    # Initialize the permanent to 0
    p=0
    # For each permutation of a's rows...
    a.permutation{|b|
        # ... initialize the product to 1,
        n=1
        # initialize the index to -1; we'll use this to go down the main diagonal
        # (i starts at -1 because at each step, the first thing we do is increment i),
        i=-1
        # iteratively calculate the product,
        a.map{
            n*=b[i+=1][i]
        }
        # increase p by the main diagonal's product.
        p+=n
    }
    p
}

```

# Answer
> 4 votes
# MATL, ~~17~~14 bytes

```
tZyt:tY@X])!ps

```

**Try it Online**

**Explanation**

```
t       % Implicitly grab input and duplicate
Zy      % Compute the size of the input. Yields [rows, columns]
t:      % Compute an array from [1...rows]
tY@     % Duplicate this array and compute all permutations (these are the columns)
X]      % Convert row/column to linear indices into the input matrix
)       % Index into the input matrix where each combination is a row
!p      % Take the product of each row
s       % Sum the result and implicitly display

```

# Answer
> 3 votes
# Ruby 2.4.0, ~~59~~ 61 bytes

Recursive Laplace expansion:

```
f=->a{a.pop&.map{|n|n*f[a.map{|r|r.rotate![0..-2]}]}&.sum||1}

```

Less golfed:

```
f=->a{
  # Pop a row off of a
  a.pop&.map{ |n|
    # For each element of that row, multiply by the permanent of the minor
    n * f[a.map{ |r| r.rotate![0..-2]}]
  # Add all the results together
  }&.sum ||
  # Short circuit to 1 if we got passed an empty matrix
  1
}

```

Ruby 2.4 is not officially released. On earlier versions, `.sum` will need to be replaced with `.reduce(:+)`, adding 7 bytes.

# Answer
> 3 votes
# Julia 0.4, 73 bytes

```
f(a,r=1:size(a,1))=sum([prod([a[i,p[i]] for i=r]) for p=permutations(r)])

```

In newer versions of julia you can drop the `[]` around the comprehensions, but need `using Combinatorics` for the `permutations` function. Works with all Number types in Julia, including `Complex`. `r` is a `UnitRange` object defined as a default function argument, which can depend on previous function arguments.

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), 82 bytes

```
f=a=>a[0]?a.reduce((t,b,i)=>t+b[0]*f(a.filter((_,j)=>i-j).map(c=>c.slice(1))),0):1

```

Works with the empty matrix too, of course.

# Answer
> 2 votes
# Mathematica, 54 bytes

```
Coefficient[Times@@(#.(v=x~Array~Length@#)),Times@@v]&

```

Now that the empty matrices are no longer considered, this solution is valid. It originates from the MathWorld page on permanents.

# Answer
> 0 votes
# Pari/GP, 44 bytes

```
p(m)=if(#m,sum(n=1,#m,m[1,n]*p(m[^1,^n])),1)

```

Try it online!

---

# Pari/GP, 50 bytes

```
m->polcoef(vecprod([x^2^i|i<-[0..#m-1]]*m),2^#m-1)

```

Based on @miles's Mathematica answer.

According to Wolfram MatheWorld, the permanent of a matrix \\$A = (a\_{ij})\\$ is the coefficient of \\$x\_1 \cdots x\_n\\$ in the polynomial \\$\prod\_{i=1}^{n}\sum\_{j=1}^na\_{ij}x\_j\\$. This is exactly what miles's answer does.

But in PARI/GP there isn't an easy way to generate an arbitrary number of new variables. So instead of a list variables \\$\[x\_1, \dots, x\_n\]\\$, I use the \\$2^i\\$'th powers of a single variable \\$x\\$, i.e., \\$\[x^1, \dots, x^{2^{n-1}}\]\\$, and take the coefficient of \\$x^1 \cdots x^{2^{n-1}} = x^{2^n-1}\\$.

Try it online!

---
Tags: code-golf, math, matrix, complex-numbers
---


title: Does this month start on a Monday?

text:
# Question
Title: Does this month start on a Monday?
June 2020 is a month in which June 1st corresponds to Monday, June 2nd corresponds to Tuesday, ... June 7th corresponds to Sunday. For reference, here's the `cal` of June 2020.

```
      June 2020
Su Mo Tu We Th Fr Sa
    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

```

Given a year and a month in the format `[year, month]`, output two distinct values that tell whether this month starts on a Monday.

## Test cases

```
[2020,6] -> True
[2021,2] -> True
[1929,4] -> True

[1969,1] -> False
[1997,5] -> False
[2060,1] -> False

```

## Specification

* The input can be in any format you prefer for your answer, e.g. numeric list, numeric tuple, etc. It doesn't have to be taken in this rigid format (it's JSON by the way).
* However, making the input a Date object is a loophole here. You shouldn't make the input a Date object.
* The month in the input doesn't have to be 1-indexed - it can also be 0-indexed.
* You need to support all years after 1582 (the start of the Proleptic Gregorian calendar), up to the year 9999.

# Answer
> 5 votes
# Japt `-!`, ~~6~~ 5 bytes

```
ÓÐN e

```

Try it

```
ÓÐN e     :Implicit input of integers U=y and V=m
 Ð        :Create date object from
  N       :  The array of inputs [U,V] with the date defaulting to the 1st
    e     :0-indexed day of the week
Ó         :Decrement
          :Implicit output of Boolean negation

```

# Answer
> 15 votes
# Excel,  ~~44~~  ~~34~~ ~~23~~ ~~19~~ 18 bytes

```
=2=MOD(A3&"-"&A2,7

```

*-11 thanks to Adam* and *-4 thanks to Shazback*

*-1 thanks to this*

## Original Answer

```
=(TEXT(DATE(A2,A3,1),"ddd")="Mon")

```

Ensure that the year is placed in cell `A2` and the month in `A3`.

*:( Crossed out 44 is still 44.*

# Answer
> 14 votes
# Ruby, ~~26~~ 24 bytes

```
->d{Time.gm(*d).monday?}

```

Try it online!

You'll never guess what this does.

Edit: -2 bytes from Dingus.

# Answer
> 10 votes
# Bash \+ GNU utilities, ~~25~~ ~~22~~ 19 bytes

```
date -d$1-1|grep ^M

```

Try it online!

Or verify the test cases online.

The input is passed as an argument in the format `year-month`, and the output is the exit code (0 for truthy, 1 for falsey, as usual).

# Answer
> 9 votes
# JavaScript (ES61),  ~~33 26~~  25 bytes

*1: This works in Chrome, Node and Edge Chromium*

*Saved 7 bytes thanks to @Shaggy*
*Saved 1 byte thanks to @l4m2*

Using a built-in. Takes input as `([year, month])`.

```
a=>/^M/.test(new Date(a))

```

Try it online!

## How?

### Converting the input to a Date object

The `Date()` constructor expects either:

```
Date(year, month [ , date [ , hours [ , minutes [ , seconds [ , ms ] ] ] ] ])

```

or:

```
Date(value)

```

In the first syntax, `month` must be 0-indexed.

In the second syntax, *value* is coerced to a string (unless it's *undefined* or it's an object) and parsed as such. Therefore, a 1-indexed month is expected in that case.

According to the ECMAScript specification:

> The function first attempts to parse the format of the String according to the rules (including extended years) called out in Date Time String Format (20.3.1.15). If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

So `[2020,6]` is turned into `"2020,6"` and parsed using implementation-specific heuristics which happen to work in V8-based engines when a comma is used as a separator. This also works with several other symbols.

### Regular expression

When passed as the argument of `/^M/.test()`, the Date object is implicitly converted into a string in the following format:

```
"DDD MMM 01 YYYY 00:00:00 GMT[...]"

```

where:

* `DDD` is the 3-letter abbreviation of the day of the week
* `MMM` is the 3-letter abbreviation of the month
* `YYYY` is the year in numerical format

Therefore, the string begins with a `"M"` iff the day of the week is **Mon**day.

---

# JavaScript (ES6),  ~~62 61~~  60 bytes

Using a formula. Takes input as `(year)(month)`, where *month* is 0-indexed.

```
y=>m=>(y-=m<2,y+=(y&~3)-3*~~(y/100)>>2)%7=='045204263153'[m]

```

Try it online!

# Answer
> 7 votes
# APL (Dyalog Unicode) 18.0, 9 bytes (SBCS)

Anonymous tacit prefix function.

```
1=7|1⎕DT⊂

```

Try it online! (uses a model, `∆DT`, instead of `⎕DT` so it can run using TIO's current version)

enclose the argument (because we need the date to be a scalar)

`1⎕DT` convert Date-Time to days since 1899-12-31 (this will "pad" the date to the first of the month)

`7|` division remainder when divided by 7

`1=` does one equal that?

# Answer
> 7 votes
# Wolfram Language 36 bytes

```
DayName@DateObject@{#,#2,1}==Monday&

```

**examples**

Naming the function `f`, to save space and increase clarity.

```
f = DayName@DateObject@{#, #2, 1} == Monday &
f[2020, 6]
f[2021, 2]
f[1929, 4]
f[1969, 1]
f[1997, 5]
f[2060, 1]

(*True*)
(*True*)
(*True*)
(*False*)
(*False*)
(*False*)

```

# Answer
> 6 votes
# Red, 33 bytes

```
func[b][1 = pick(to now b)+ 1 10]

```

Try it online!

The argument `b`is a block containing the year and the month. `now` is function returning the current date and time; `to now b` converts the input to a `date!` datatype. The odd thing is that currently Red assigns the missing data (the day of month) 0 by default, but Red being 1-indexed, thus calculates the last day of the previos month instead of the first day of the given month:

`to now [2020 6]` gives `31-May-2020`

That's why I add 1 to the resulting date. `date!` has among its path accessors `/weekday`, wich can be queried using indexing instead - `10` (tenth item). Too bad I can't use direct indexing using paths `/10`, because it only works on `words` (variables) and not on literal / unnamed data. That's why I use `pick`date `10`.

Finally I check if the weekday is 1 (for Monday).

# Answer
> 6 votes
# T-SQL, 47 bytes

```
SELECT 1/datepart(w,datefromparts(y,m,7))FROM i

```

(10 bytes saved thanks to @t-clausen.dk)

Assumes the input is in a table `i` with two columns, `y` and `m`. It assumes Sunday is set as the first day of week, which is the default setting. Outputs 1 if the month starts on a Monday, 0 otherwise.

`datepart(w,datefromparts(y,m,7))`, the day of week of the *seventh* day of the month returns 1 (=Sunday) if the month starts on a Monday, and a higher number otherwise. Since it's an integer, the division is rounded down to zero in the latter case.

Demo

# Answer
> 6 votes
# 05AB1E, 36 bytes

```
Ð3‹12*+>₂*T÷s3‹Xα©т%D4÷®т÷©4÷®·(O7%Θ

```

Here we go again. 05AB1E has no date builtins, so everything is done manually. This solution is a derivative of my answer here.

Takes both inputs separated, the \\$month\\$ as first input and \\$year\\$ as second.

Try it online or verify all test cases.

**Explanation:**

The general formula to calculate the *Day of the Week* manually is:

$${\displaystyle h=\left(q+\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor+K+\left\lfloor{\frac{K}{4}}\right\rfloor+\left\lfloor{\frac{J}{4}}\right\rfloor-2J\right){\bmod{7}}}$$

Where for the months March through December:

* \\$q\\$ is the \\$day\\$ of the month (`[1, 31]`)
* \\$m\\$ is the 1-indexed \\$month\\$ (`[3, 12]`)
* \\$K\\$ is the year of the century (\\$year \bmod 100\\$)
* \\$J\\$ is the 0-indexed century (\\$\left\lfloor {\frac {year}{100}}\right\rfloor\\$)

And for the months January and February:

* \\$q\\$ is the \\$day\\$ of the month (`[1, 31]`)
* \\$m\\$ is the 1-indexed \\$month + 12\\$ (`[13, 14]`)
* \\$K\\$ is the year of the century for the previous year (\\$(year - 1) \bmod 100\\$)
* \\$J\\$ is the 0-indexed century for the previous year (\\$\left\lfloor {\frac {year-1}{100}}\right\rfloor\\$)

Resulting in in the day of the week \\$h\\$, where 0 = Saturday, 1 = Sunday, ..., 6 = Friday.
Source: Zeller's congruence

Since we only care about \\$q=1\\$, we can use that to golf 2 bytes. With the formula above, the result would be \\$2\\$ for Mondays (and thus requiring a leading `$` to push both 1 AND the input-month; as well as a trailing `2Q` to check if the result equal 2). But if we remove the \\$q+\\$ part, the result would be \\$1\\$ for Mondays (in which case we can use the implicit input-month, removing the `$`; and also use the `==1` builtin `Θ` instead of `2Q`).

```
Ð             # Triplicate the (implicit) input-month
 3‹           # Check if the month is below 3 (Jan. / Feb.),
              # resulting in 1 or 0 for truthy/falsey respectively
   12*        # Multiply this by 12 (either 0 or 12)
      +       # And add it to the month
              # This first part was to make Jan. / Feb. 13 and 14

>             # Month + 1
 ₂*           # Multiplied by 26
   T÷         # Integer-divided by 10
s3‹           # Check if the month is below 3 again (resulting in 1 / 0)
   Iα         # Take the absolute difference with the second input-year
     ©        # Store this potentially modified year in the register
      т%      # mYear modulo-100
D4÷           # mYear modulo-100, integer-divided by 4
®т÷©4÷        # mYear integer-divided by 100, and then integer-divided by 4
®·(           # mYear integer-divided by 100, doubled, and then made negative
O             # Take the sum of all values on the stack
 7%           # And then take modulo-7 to complete the formula,
              # resulting in 0 for Sunday, and [1, 6] for [Monday, Saturday]

Θ             # Check if this is equal to 1 (thus a Monday)
              # (after which the result is output implicitly)

```

Note that I've also used \\$\left\lfloor{\frac{26(m+1)}{10}}\right\rfloor\\$ instead of \\$\left\lfloor{\frac{13(m+1)}{5}}\right\rfloor\\$, since 05AB1E has a 1-byte builtin for both `26` and `10` ( and `T` respectively), saving a byte on the `13`.

# Answer
> 5 votes
# Python 2, 56 bytes

```
lambda y,m:date(y,m,1).weekday()<1
from datetime import*

```

Try it online!

# Answer
> 4 votes
# Julia 1.0, 39 bytes

```
using Dates
x*y=dayofweek(Date(x,y))==1

```

Try it online!

I am posting this seperate from my other answer, since it doesn't use the point-free style, and thus doesn't have the cool side-benifits of also working for year only etc. But it is shorter

# Answer
> 4 votes
# C (gcc), ~~61~~ ~~60~~ 59 bytes

Saved a byte thanks to ceilingcat!!!
Saved a byte thanks to nununoisy!!!

```
f(y,m){y-=m<2;m=(y+y/4-y/100+y/400+"bed=pen+fad."[m])%7<1;}

```

Try it online!

Straight-up calculation that uses 0-based months.

# Answer
> 4 votes
# Python 3.8 (pre-release), 53 bytes

```
lambda x:date(*x,1).weekday()<1
from datetime import*

```

Try it online!

# Answer
> 4 votes
# Bash \+ Standard Unix Tools, 17 bytes

```
cal $1|grep ' 6$'

```
* Input like "06 2020".
* Exit Code is `0` if first day of month is Monday and `1` if not.

Try it online!

In some implementations, additional two bytes are necessary:

```
 cal $1|grep ' 6 *$'

```

# Answer
> 3 votes
# Java (JDK), 35 bytes

```
m->{m.set(5,1);return m.get(7)==2;}

```

Try it online!

## Explanation

The input is taken as a `java.util.Calendar`. First we modify the calendar to force the first of the month, then we check if that day of week is a Monday.

```
m -> {
  m.set(Calendar.DAY_OF_MONTH, 1);    // DAY_OF_MONTH is the constant 5
  return m.get(Calendar.DAY_OF_WEEK)  // DAY_OF_WEEK is the constant 7
    == Calendar.MONDAY                // MONDAY is the constant 2. Don't ask why, no one knows.
}

```

# Answer
> 3 votes
# Perl 5 `-MTime::Local -pa`, ~~38~~ 33 bytes

*Shaved 5 bytes with help from @DomHastings*

```
$_=(gmtime timegm 0,0,0,1,@F)=~Mo

```

Try it online!

Input is space separated: 0-indexed month followed by year.

# Answer
> 3 votes
# PowerShell, 28 21 bytes

```
(d $i -U %A)-like'M*'

```

Try it online!

# Answer
> 2 votes
# Julia 41 bytes

(37 characters)

```
using Dates
isequal(1)∘dayofweek∘Date

```

It's fairly rare to find a code-golf that can be answered in point-free style in Julia. An interesting side effect of this, is that if you give this just 1 input it will tell you if the year starts with a Monday. And if you give it 3 inputs it will tell you if a given day is a Monday.

# Answer
> 2 votes
# Retina 0.8.2, 108 bytes

```
\d+
$*
^(11? )1
12$*1$1
\G1
13$*
(1+)\1{4}1{27,} (?=(1*)\2{399})(?=(1*)\3{3})(1*)(?=\4{99})
$1$2$3
^(1{7})*$

```

Try it online! Link includes speedup `^` so that the included test cases complete within TIO's time limit. Takes 1-indexed month first, then the year. Explanation:

```
\d+
$*

```

Convert to unary.

```
^(11? )1
12$*1$1

```

If the month is January or February, then add 12 and subtract 1 from the year.

```
\G1
13$*

```

Multiply the month by 13, which begins a form of Zeller's congruence.

```
(1+)\1{4}1{27,} (?=(1*)\2{399})(?=(1*)\3{3})(1*)(?=\4{99})
$1$2$3

```

The month is integer divided by 5, but with 27 subtracted, which allows the calculation to result in Monday = 0. The year is separately divided by both 400 and 4, after which 1% of the year is skipped thus effectively subtracting it. The month calculation, `y/400` and `y/4` are then added to the remaining `(y-y/100)`. Note that Retina will attempt to match this expression more than once but will always fail because there is only one space in the input. However, these attempts make it very slow, so to optimise this the TIO link includes a leading `^`. The code will work without it eventually though.

```
^(1{7})*$

```

Test whether the result is a multiple of 7.

# Answer
> 2 votes
# , 39 bytes

```
strftime(paste0(scan(,''),'-1'),'%u')<2

```

Try it online!

# Answer
> 2 votes
# PHP 7.4, 43 bytes

This code creates an anonymous function where you pass the month and year, returning `true` for monday, and `false` if the 1st day it isn't on a monday.

```
fn($Y,$M)=>!~-date(N,strtotime("$Y-$M-1"));

```

You can try this on: http://sandbox.onlinephpfunctions.com/code/5bf01ff098ef40b4b45bbc82e3b13a5e1b83f8d1

---

An alternative solution could be just this (40 bytes):

```
fn($Y,$M)=>date(N,strtotime("$Y-$M-1"));

```

Which returns the week day, where 1 is monday, 2 is tuesday ....

I don't think this is in the spirit of the question.

# Answer
> 2 votes
# Python 3.8, 80 bytes

```
from calendar import Calendar as C
f=lambda x:C().monthdayscalendar(*x)[0][0]==1

```

Try it online!

# Answer
> 2 votes
# T-SQL, 43 bytes

```
PRINT datediff(d,0,concat(@+@y*100,14))%7/6

```

the expression

```
datediff(d,0,concat(@+@y*100,14))%7

```

will return 0-6. 6 represent Monday - this is divided by 6(rounding off)

Mondays returns 1, other weekdays returns 0

**Try it online**

# Answer
> 2 votes
# brainfuck, 582 bytes

```
->+++[[>]>,>++++++[<-------->-]<[<++++++++++>-],>++++++[<-------->-]<[<+>-]+[-<+]->-]>>>[->>>>+>+<<<<<]>>>>[<<<<+>>>>-]<+>>>+++<+>+<[->-[>]<<]<[-]<[-<<<<->>>]>[-]>[-]>[-]>[-]>[-]+++>++>+++++>>+++>+++++>+>++++>++++++>++>+++++[-<+]->>>>[>>+>+<<<-]>>[>>>[-<<<<+>>>>]<<[->+<]<[->+<]>-]>>>[-<+<<+>>>]<<<[->>>+<<<]>[[-<+>]>[-<+>]<<<<[->>>>+<<<<]>>-]>>++++++++++[<+++++++>-]<<<<<<<[>>+>>>>--<<<<<<-]>>[-[->>+<]>[<]<]>>[-[->>+<]>[<]<]<<<[->+>>>>+<<<<<]>[-[->>+<]>[<]<]>>[-[->>+<]>[<]<]>>[-<<<<<<<+>>>>>>>]<<<<<<+++++++<<+>[>->+<[>]>[<+>-]<<[<]>-]>[-]+>[[-]<->]<[->+<]>>++++++++[<++++++>-]<.

```

Try it online!

Definitely not the shortest program here, this was more to see if it was possible to do. Expects input in the form of `YYYYMM` \- the month needs to be 1-indexed and 2 characters wide. Outputs `1` if the month starts on Monday, `0` otherwise. This could be shortened by 21 bytes if the output was not ASCII.

Ungolfed:

```
-> reference

+++[                     input 3 sets of 2 numbers
 [>]                     find next zero
 >,>++++++[<-------->-]< input number and sub 48 ascii
 [<++++++++++>-]         mul by 10
 ,>++++++[<-------->-]   input next number and sub 48
 <[<+>-]                 copy to previous cell
 +[-<+]-                 move back to reference
 >-                      dec counter
]                        end input

>>>
[->>>>+>+<<<<<]       copy the month variable for comparison
>>>>[<<<<+>>>>-]<+>>>+++<+>+<[->-[>]<<]
<[-]<[-<              if month is less than 3
 <<<->>>              decrement the year
]>[-]>[-]>[-]>[-]>[-] clear out comparison cells to store lookup table

0 3   2  5    0 3   5     1 4    6      2  4
  +++>++>+++++>>+++>+++++>+>++++>++++++>++>++++ lookup table
+[-<+]- move back to reference
>>>>    move to month

[>>+>+<<<-]
>>[>>>[-<<<<+>>>>]<<[->+<]<[->+<]>-] access lookup table for month
>>>[-<+<<+>>>]<<<[->>>+<<<]>
[[-<+>]>[-<+>]<<<<[->>>>+<<<<]>>-]   copy table value to result
>>++++++++++[<+++++++>-]<<<<<<<      add 70 to result to prevent wrap

[>>+>>>>--<<<<<<-]
>>[-[->>+<]>[<]<]
>>[-[->>+<]>[<]<] add century div by 4

<<<[->+>>>>+<<<<<]> add year
[-[->>+<]>[<]<]
>>[-[->>+<]>[<]<]>> add year div by 4

[-<<<<<<<+>>>>>>>]                           set up modulo
<<<<<<+++++++<<+>[>->+<[>]>[<+>-]<<[<]>-]    all modulo 7
>[-]+>[[-]<->]<[->+<]>>++++++++[<++++++>-]<. display result

```

# Answer
> 2 votes
# q, ~~33~~ 32 bytes

accepting the inputs as strings:

```
{2=mod["d"$"M"$x,".",-2#"0",y]7}

```

explanation

```
                     -2#"0",y    /append "0" to 2nd input and take last 2 chars from result
               x,".",            /join by "."
           "M"$                  /tok, convert string to month type
       "d"$                      /cast to date type - returns 1st of month
   mod[                      ]7  /date mod 7, 0->sat,1->sun,2->mon,etc
 2=                              /check if equal 2

```

run like:

```
q){2=mod["d"$"M"$x,".",-2#"0",y]7}["1929";"4"]
1b

```

# Answer
> 2 votes
# Befunge-93, 81 78 bytes

```
&&:2`!#v_2->267+**2-55+/\:"d"/02-*\:"d"%\:"d"%4/\"d"/4/++++7%!.@
-1\++55<   ^\

```

Try it online!

## How does it work?

This is based on a formula which gives the day of the week given a date:

```
W = (k + floor(2.6m - 0.2) - 2C + Y + floor(Y/4) + floor(C/4)) mod 7

```

where

* `k` is the day of month,
* `m` is the month of the year, if years start with March (so Mar = 1, Apr = 2, ..., Dec = 10, Jan = 11, Feb = 12).
* `C` is the century of the March adjusted year (so year = year - 1 in January and February).
* `Y` is the year in the century (March adjusted).
* `W` is the weekday, (Sun = 0, ..., Sat = 6).

We will be calculating

```
W' = floor((26m - 2)/10) - 2C + Y + floor(Y/4) + floor(C/4)) mod 7

```

the month will start with a Monday, iff `W' == 0`.

Breaking down the program gives us:

```
&&              Reads year and month

  :2`!#v_2->    If the month is January or February, subtract 1 from
-1\++55<   ^\   the year, and add 10 to the month; else, subtract
                2 from the month. (Years start in March).

267+**2-55+/    Calculate (2.6 * month - 0.2).

\:"d"/02-*      -2 * Century (= int (year / 100))

\:"d"%          Year in century (year % 100)

\:"d"%4/        4 year leap year cycle adjustment (int ((year % 100) / 4))

\"d"/4/         400 year leap year cycle adjustment
                (int (int (year / 100) / 4))

++++            Sum them all

7%              Mod 7.

!.@             Negate the result and print it -- if 0 (hence, first
                day of the month is a Monday), then 1, else (not a
                Monday) 0.

```

Edit: Saved three bytes.

# Answer
> 2 votes
# Factor, 20 bytes

```
[ 1 <date> monday? ]

```

Try it online!

* `1 <date>` Create a timestamp object from the given year, month, and using 1 as the day.
* `monday?` Is it Monday? A builtin from the `calendar` vocabulary.

# Answer
> 2 votes
# TI-Basic, 15 bytes

```
2=dayOfWk(Ans(1),Ans(2),1

```

Input is taken from `Ans` as a list. Output is stored in `Ans` and is displayed. Assumes that the time and date are set correctly before the program is run. Outputs `1` if the month starts on a Monday and `0` if it does not. Only works on TI-84+/SE.

# Answer
> 2 votes
# jq, 50 bytes

```
.+[1]+(now|gmtime[3:8])|mktime|strftime("%w")=="1"

```

Try it online!

Not that short, but it's different enough that I thought it might be interesting enough to post...

It expects a year and a 0-indexed month as a list, meaning `[2021,3]` for April, 2021.

```
.+[1]+(               )                            - append "day 1" to input
       now|gmtime[3:8]                             - curr time breakout, drop Y/m/d fields
                       |mktime                     - convert to epoch time
                              |strftime("%w")=="1" - compare "day of week" to Monday

```

# Answer
> 1 votes
# Perl 5, 44 bytes

```
say 1==(gmtime timegm 0,0,0,1,-1+pop,pop)[6]

```

Try it online!

# Answer
> 1 votes
# Charcoal, 43 bytes

```
ＮθＮη≧⁻‹η³θ¬﹪Σ⟦θ÷θ⁴±÷θ¹⁰⁰÷θ⁴⁰⁰Ｉ§”)➙⊟-�=.”η⟧⁷

```

Try it online! Link is to verbose version of code. Takes 1-indexed month and outputs a Charcoal boolean, i.e. `-` for Monday, no output otherwise. Explanation:

```
ＮθＮη

```

Input the year and the month.

```
≧⁻‹η³θ

```

Decrement the year if the month is January or February.

```
¬﹪Σ⟦θ÷θ⁴±÷θ¹⁰⁰÷θ⁴⁰⁰Ｉ§”)➙⊟-�=.”η⟧⁷

```

Calculate the number of leap years and adjust for the month using a cyclic lookup table `403250351462`, then output whether the result is zero (mod 7).

# Answer
> 1 votes
# JavaScript, 45 bytes

```
n=>(''+new Date(n[0]+'-'+n[1]+'-01'))[0]=='M'

```

Takes input as an array like `[2020, 6]`.

## How it works

Converts the date object to a string then checks if the first character is an `M`.

# Answer
> 1 votes
# Python 3, ~~76~~ 68 bytes

Creates a new datetime object with given year and month (as a list) and the first day of the month and then checks if the day name starts with a M for Monday.

```
lambda l:date(*l,1).strftime("%A")[0]=="M"
from datetime import date

```

Try it online!

# Answer
> 1 votes
# Python 3, 57 56 bytes

```
lambda y,m:date(y,m,1).weekday()<1
from datetime import*

```

Try it online!

---
Tags: code-golf, decision-problem, date
---


title: Determine How many Wheels There Are

text:
# Question
Title: Determine How many Wheels There Are
## Non-math explanation

*This is an explanation that is meant to be approachable regardless of your background. It does unfortunately involve some math, but should be understandable to most people with a middle school level of understanding*

A pointer sequence is any sequence such that \\$a(n+1) = a(n-a(n))\\$.

Lets pick apart this formula a little bit to understand what it means. This just means to figure out the next term in the sequence we look at the last term, take that many steps back and copy the term we find. For example if we had the sequence so far to be

```
... 3 4 4 4 3 ?

```

We would take 3 steps back from `3`

```
... 3 4 4 4 3 ?
      ^

```

making our result `4`.

Now normally we play this game on a tape that is infinite in both directions, but we can also play it on a wheel where after a certain number of steps we get back to the beginning of the sequence.

For example here is an visualization of the sequence `[1,3,1,3,1,3]`

Now we might notice that any number, \\$x\\$ in a wheel that exceeds the number of cells in the wheel, \\$n\\$, might as well be \\$x\\$ modulo \\$n\\$ because every complete circuit around the wheel is the same as doing nothing. So we will only consider wheels with all members being less than the size of the wheel.

## Math explanation

A pointer sequence is any sequence such that \\$a(n+1) = a(n-a(n))\\$. Usually these are defined from the integers to the integers, however you might notice that the only things needed in this definition are a successor function and an inverse function. Since all cyclic groups have both of these we can actually consider pointer sequences on any cyclic groups.

If we start looking for these types of functions we will notice that for each function there are a couple of similar functions. For example on \\$\mathbb{Z}\_3\\$ the following 3 are all functions that fit our requirements.

```
f1 : [1,2,2]
f2 : [2,1,2]
f3 : [2,2,1]

```

*(Here a list is used to represent a function to get the result just index the list by the input)*

We might notice that these functions are all "rotations" of each other. To formalize what I mean by rotation, a function \\$b\\$ is a rotation of \\$a\\$ iff

\\$ \exists n : \forall m : a(m+n) = b(m) \\$

We can actually show that if \\$a\\$ is a pointer sequence every rotation of \\$a\\$ is also a pointer sequence. Thus we will actually consider any sequences that are rotations of each other to be equivalent.

## Task

Given \\$n\\$ as input output the number of pointer sequences that have size \\$n\\$.

This is so answers will be scored in bytes with less bytes being better.

## Testcases

Currently these testcases are lacking a bit, I have a computer program to generate these but it is inordinately slow at doing so. If anyone would like to contribute larger testcases (that they can verify correct) they are free to do so. Below some tests is a list of all the functions that I found, this might be useful for debugging. I can't add these for the larger ones because of character limits.

If you want the code I used to generate these here it is

```
1 -> 1
[[0]]
2 -> 2
[[1,1],[0,0]]
3 -> 4
[[2,2,2],[2,2,1],[1,1,1],[0,0,0]]
4 -> 7
[[3,3,3,3],[3,3,3,2],[2,2,2,2],[3,3,3,1],[3,1,3,1],[1,1,1,1],[0,0,0,0]]
5 -> 12
[[4,4,4,4,4],[4,4,4,4,3],[3,3,3,3,3],[4,4,4,4,2],[4,3,4,4,2],[2,2,2,2,2],[4,4,4,4,1],[4,3,4,4,1],[4,4,2,4,1],[4,4,1,4,1],[1,1,1,1,1],[0,0,0,0,0]]
6 -> 35
[[5,5,5,5,5,5],[5,5,5,5,5,4],[5,5,4,5,5,4],[4,4,4,4,4,4],[5,5,5,5,5,3],[5,4,5,5,5,3],[5,5,5,3,5,3],[5,3,5,3,5,3],[3,3,3,3,3,3],[5,5,5,5,5,2],[5,4,5,5,5,2],[5,3,5,5,5,2],[5,5,4,5,5,2],[5,5,2,5,5,2],[5,5,2,5,2,2],[5,3,2,5,2,2],[5,2,2,5,2,2],[4,2,2,4,2,2],[2,2,2,2,2,2],[5,5,5,5,5,1],[5,4,5,5,5,1],[5,3,5,5,5,1],[5,5,4,5,5,1],[5,5,2,5,5,1],[5,5,1,5,5,1],[5,5,5,3,5,1],[5,3,5,3,5,1],[5,5,5,2,5,1],[5,5,5,1,5,1],[5,3,5,1,5,1],[5,1,5,1,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,7,7,1,7,1],[7,7,2,7,7,1,7,1],[7,7,1,7,7,1,7,1],[7,7,7,5,7,1,7,1],[7,5,7,5,7,1,7,1],[7,3,7,5,7,1,7,1],[7,7,7,3,7,1,7,1],[7,5,7,3,7,1,7,1],[7,3,7,3,7,1,7,1],[7,7,7,2,7,1,7,1],[7,7,7,1,7,1,7,1],[7,5,7,1,7,1,7,1],[7,3,7,1,7,1,7,1],[7,1,7,1,7,1,7,1],[5,1,5,1,5,1,5,1],[4,7,1,7,7,7,4,1],[4,7,1,7,7,5,4,1],[3,7,7,1,7,7,3,1],[3,7,3,1,3,7,3,1],[3,5,7,1,7,5,3,1],[3,5,3,1,3,5,3,1],[3,3,3,1,3,3,3,1],[3,1,3,1,3,1,3,1],[1,1,1,1,1,1,1,1],[0,0,0,0,0,0,0,0]]
9 -> 1049
10 -> 4304

```

*Last case calculated by @HyperNeutrino*

# Answer
# Jelly, ~~18~~ 17 bytes

```
J_ịṙ1⁼
ṗṙ€RṂ€QÇ€S

```

Try it online!

### How it works

```
ṗṙ€RṂ€QÇ€S  Main link. Argument: n

ṗ           Cartesian power; yield all vectors of n elements of [1, ..., n].
   R        Range; yield [1, ..., n].
 ṙ€         Rotate each vector 1, ..., and n units to the left.
    Ṃ€      Take the minimum of each array of rotations of the same vector.
      Q     Unique; deduplicate the resulting array.
            Since each vector is replaced by its lexicographically minimal
            rotation, no resulting vector will be a rotation of another vector.
       Ç€   Map the helper link over the remaining vectors.
            Vectors that represent pointer sequences map to 1, others to 0.
         S  Take the sum.

J_ịṙ1⁼      Helper link. Argument: v = (v1, ..., vn)

J           Indices; yield [1, ..., n].
 _          Subtract v, yielding [1 - v1, ..., n - vn].
  ị         Index into v, yielding [v(1 - v1), ..., v(n - vn)].
   ṙ1       Rotate the result one unit to the left.
     ⁼      Compare the result with v.

```
> 7 votes

# Answer
# Python 2, ~~162~~ ~~156~~ ~~152~~ ~~146~~ 143 bytes

```
lambda n:len({min(l[i:]+l[:i]for i in R(n))for l in product(*[R(n)]*n)if all(l[-~i-n]==l[i-l[i]]for i in R(n))})
from itertools import*
R=range

```

Try it online!

More or less brute force:

* Generates all permutations `product(r,repeat=n)`
* Checks valid lists. `all(l[-~i-n]==l[i-l[i]]for i in r)`
* Generates a set of the minimum (lexicographical) rotation of the valid lits `min(l[i:]+l[:i]for i in r)`

---

**Recursive function that short circuits a bit:**

This version is longer, but is able to calculate `f(10)` in ~19 secs on tio.run

On my machine, I've found:

* `f(11) = 16920`
* `f(12) = 78687`

# Python 2, 209 bytes

```
lambda n:len(g(n,(-1,)*n))
r=range
g=lambda n,a,j=0:set()if any(len({-1,a[-~i-n],a[i-a[i]]})>2for i in r(j))else set.union(*[g(n,a[:j]+(i,)+a[j+1:],j+1)for i in r(n)])if j<n else{min(a[i:]+a[:i]for i in r(n))}

```

Try it online!

**Explanation:**

```
f=lambda n:len(g(n,(-1,)*n)) #calls the recursive function, and gets length.
#The initial circle is all -1, and is built recursively
r=range
g=lambda n,a,j=0:
#if any of the indexes so far break the pointer rule (ignored if 'empty'), stop recursion.
if any(len({-1,a[-~i-n],a[i-a[i]]})>2for i in r(j))
    return set()
else
if j<n:
    #recursively call g with a+ all numbers in range ie.(a+[0], a+[1], ..)
    return set.union(*[g(n,a[:j]+(i,)+a[j+1:],j+1)for i in r(n)])
else # if recursion depth == n, we are done. Return the smallest (lexicographically) rotation.
    return {min(a[i:]+a[:i]for i in r(n))}

```
> 5 votes

# Answer
# CJam, 37

```
ri:M_m*{:XM,Xfm<:e<=M{(_X=-X=}%X=&},,

```

Try it online

Pretty much brute force, and it feels kinda clumsy. It gets very slow after 6. Replace the last comma with a `p` to print the wheels.
> 3 votes

# Answer
# Pyth, 28 bytes

```
l{mS.>LdQf!fn@ThY@T-Y@TYUQ^U

```

Test suite

First, we generate all sequences of the appropriate length with the appropriate elements. Second, we check whether there are any pointer failures. Third, map to all sorted rotations. Fourth, deduplicate and count.
> 3 votes

# Answer
# Haskell, ~~117 112~~ 104 bytes

```
f k|x<-[1..k]=sum[1|y@(h:t)<-mapM(x<$f)x,t++[h]==[y!!mod(n-a)k|(n,a)<-zip x y],and[y<=drop n y++y|n<-x]]

```

Brute force, so pretty slow for large inputs. Try it online!

-5 bytes thanks to Laikoni.

-5 bytes thanks to Ørjan Johansen.
> 3 votes

# Answer
# Wolfram Language (Mathematica), ~~150~~ 123 bytes

```
nCount[Tuples[r=Range@n-1,{n}],l_/;l==Sort[l~RotateLeft~#&~Array~n][[1]]&&And@@(!1!-!0//.!a_:>l[[Mod[#+a,n,1]]]&/@r)]

```

Try it online!

-27 bytes thanks to att.

Explanation from 150 byte version:

```
p=Part[#,Mod[#2,Length@#,1]]&;            -helper function to take part of circular list

n|->
  Count[                                  -count all the
    Tuples[Range@n-1,{n}],                  -possible sequences
    _?(l|->                                 -where
      l==Sort[Array[RotateLeft[l,#]&,n]][[1]]  -the sequence is the first of all rotations of that sequence
      &&                                       -and
      And@@Array[p[l,#+1]==p[l,#-p[l,#]]&,n]   -the pointer property holds for all elements in that sequence
  )]

```
> 1 votes

---
Tags: code-golf, math, combinatorics, abstract-algebra
---


# Question
Title: Calculate the probability of getting to the target first (exactly)
Consider the following probability puzzle.

We start with a string of bits all set to 0. At each step we choose a bit uniformly and independently at random and flip it. The value your code has to compute is the probability of getting to the all 1s bit string before you get back to the all 0s bit string.

Let \\$n\\$ be the length of the starting bitstring.

Examples:

\\$n = 1\\$. The output is 1.

\\$n = 2\\$. The output is 1/2.

\\$n = 3\\$. The output is 2/5.

The remaining outputs for n up to 20 are:

```
3/8,3/8,5/13,60/151,105/256,35/83,63/146,630/1433,1155/2588,6930/15341,12870/28211,24024/52235,9009/19456,9009/19345,17017/36362,306306/651745,2909907/6168632.

```

Your code should take \\$n\\$ as the input and give the right output. The output must be exact, for example as a fraction. There is no need for the fraction to be fully reduced.

Your code must work for \\$n\\$ up to at least \\$20\\$ and run without timing out on TIO .

# Answer
# Wolfram Language (Mathematica), 25 bytes

$$n! \div \left( \sum ^n \_{k=0} k!(n-k)! \right)$$

```
#!/Sum[k!(#-k)!,{k,0,#}]&

```

Try it online!

-4 bytes from @ovs
> 10 votes

# Answer
# , ~~7~~ 6 bytes

```
cRİS‘İ

```

Try it online!

M is Jelly's more mathematical (and out-of-date) sibling. While Jelly uses floating point maths, M uses rational numbers where possible.

Similarly to J42161217's Mathematica answer, we use the binomial coefficient. This calculates the exact value of

$$1 \div \left(1 + \sum ^n \_{k=1} \frac 1 {\binom n k}\right)$$

## How it works

```
cRİS‘İ - Main link. Takes n on the left
 R     - Range [1, 2, ..., n]
c      - Calculate nCk for each k
  İ    - Inverse; Get the reciprocal of each
   S   - Sum
    ‘  - Increment, to account for nC0
     İ - Inverse; Get the reciprocal again

```
> 7 votes

# Answer
# Factor \+ `math.combinatorics math.unicode`, ~~45~~ 43 bytes

```
[ dup [0,b] [ nCk -1 ^ ] with map Σ -1 ^ ]

```

Try it online!

This uses the formula graciously offered in the following M answer.

*Edit:* use `-1 ^` instead of `recip` since it's 1 byte shorter.

## Explanation:

It's a quotation (anonymous function) that takes an (0-indexed) integer as input and returns a number (probably a ratio) as output. Assuming `4` is on top of the data stack when this quotation is called...

* `dup` Duplicate TOS (top of stack). **Stack:** `4 4`
* `[0,b]` Create a range object from the number at TOS (0 to 4 inclusive). **Stack:** `4 T{ range f 0 5 1 }`
* `[ nCk -1 ^ ]` Push a quotation to the data stack to be used later by `with`. **Stack:** `4 T{ range f 0 5 1 } [ nCk -1 ^ ]`
* `with` Partial application on the left. It sticks that 4 that's been lingering on the data stack into the quotation that's about to be used by `map` in such a way that it comes before the range elements being mapped over. **Stack:** `T{ range f 0 5 1 } [ 4 [ nCk -1 ^ ] swapd call ]`
* `map` Apply a quotation to each element of a sequence, collecting the results into a sequence of the same size. (Inside the quotation now...) **Stack:** `4 0`
* `nCk` Outputs the total number of unique combinations of size TOS that can be taken from a set of size NOS (next on stack). Also known as 4 choose 0. **Stack:** `1`
* `-1 ^` Take the reciprocal. Shorter than `1 swap /` and `recip`. **Stack:** `1`
* Now `map` applies the quotation to each element of the range sequence and we end up with... **Stack:** `{ 1 1/4 1/6 1/4 1 }`
* `Σ` Take the sum of a sequence. **Stack:** `2+2/3`
* `-1 ^` Take the reciprocal. **Stack:** `3/8`.
> 6 votes

# Answer
# Python 2, 85 bytes

```
n=input()
B=9**9;p=1;q=0
for i in range(n+1):x=(B+1)**n/B**i%B;q=p+x*q;p*=x
print p,q

```

Try it online!

A nice solution made uglier by the requirement that we output an exact fraction. With floats, it looks like:

**62 bytes**

```
lambda n,B=9**9:1/sum(1./((B+1)**n/B**i%B)for i in range(n+1))

```

Try it online!

We use the formula $$ \left(\sum ^n \_{i=0} {\binom n i}^{-1}\right)^{-1}$$ and compute the binomials coefficients using this trick. This gives us a sleeves-rolled-up solution without any imports or built-ins for factorial or binomial coefficients.

The original code implements fraction arithmetic by updating the fraction `p/q`. It might be shortenable but I don't really care to golf it. A more direct but longer conversion uses the `fractions` library:

**94 bytes**

```
from fractions import*
lambda n,B=9**9:1/sum(1/Fraction(((B+1)**n/B**i%B))for i in range(n+1))

```

Try it online!

---

This replace-and-evaluate monstrosity would save bytes over the floats version, but it gives wrong answers where some \\$\binom{n}{i}\\$ ends in a zero digit.

**56 bytes, doesn't work**

```
lambda n:1/eval(`(10**17+1)**n`.replace('0'*9,'e0+1./'))

```

Try it online!
> 5 votes

# Answer
# Python 2,  ~~83~~  77 bytes

-4 thanks to dingledooper! (`from math import factorial as f` -\> `f=lambda n:0**n or n*f(n-1)`)
-2 thanks to ovs! (`0**n or` -\> `n<1or`)

```
f=lambda n:n<1or n*f(n-1)
lambda n:(f(n),sum(f(i)*f(n-i)for i in range(n+1)))

```

An unnamed function accepting `n` that returns a tuple `(numerator, denominator)` (not simplified).

**Try it online!** (1-20, including simplified fraction)
> 4 votes

# Answer
# JavaScript (Node.js), 61 bytes

```
n=>[(g=n=>n?n*g(~-n):1)(n),(h=k=>g(k)*g(n-k)+(k&&h(~-k)))(n)]

```

Try it online!

Search the sample output given by OP on OEIS, and you may find out A046825. Use the formula given on that page:

$$ \begin{split} f(n) & = \frac{1}{\sum\_{k=0}^{n}\frac{1}{C\_n\left(k\right)}} \\ & = \frac{1}{\sum\_{k=0}^{n}\frac{k!\left(n-k\right)!}{n!}} \\ & = \frac{n!}{\sum\_{k=0}^{n}k!\left(n-k\right)!} \end{split} $$

It may need +1 byte (change `1` to `1n`) if larger (\\$n\>21\\$) testcases is required.

Note: I have no idea why it works.
> 2 votes

# Answer
# , ~~45~~ 40 bytes

Using J42161217's Mathematica answer, and following Guiseppe's astounding improvement,

```
   function(n,`!`=gamma)c(!n,(!1:n)%*%!n:1)

```

Try it online!
> 2 votes

# Answer
# Sledgehammer, 11 bytes

```
⣸⢄⠔⢅⢉⢟⣹⢤⢟⡹⣽

```

Decompresses into this Wolfram Language function:

```
Tr[Binomial[#1, Range[0, #1]]^(-1)]^(-1) &

```

Try it online!

Returns 0-indexed fractions.

---

Can't say I have much to add in terms of golfing, but as, judging by the other answers, no one seems to know why the formula works, I can offer an explanation:

Let \\$P\_n(k)\\$ be the probability that, following the given algorithm, a string of all ones is reached before a string of all zeroes, starting from an \\$n\\$-length bitstring which has \\$k\\$ ones. We can immediately see that \\$P\_n(0)=0\\$ and \\$P\_n(n)=1\\$. The desired value is \\$P\_n(1)\\$: one bit is flipped on first.

When we flip a bit at random, there is a \\$\frac kn\\$ chance that bit was a one, and a \\$\frac{n-k}n\\$ chance it was a zero. Therefore, for \\$0\<k\<n\\$, we have \\$P\_n(k)=\frac knP\_n(k-1)+\frac{n-k}nP\_n(k+1)\\$. In other words, \\$P\_n(k)\\$ is the weighted average of \\$P\_n(k-1)\\$ and \\$P\_n(k+1)\\$, with weights \\$k\\$ and \\$n-k\\$, respectively.
If we denote \\$P\_n(x)-P\_n(x-1)\\$ by \\$\Delta P\_n(x)\\$, we can equivalently say \\$\Delta P\_n(k+1)=\frac{k}{n-k}\Delta P\_n(k)\\$.

Checking some values of \\$k\\$:

* \\$\Delta P\_n(2)=\frac 1{n-1}\Delta P\_n(1)\\$
* \\$\Delta P\_n(3)=\frac 2{n-2}\Delta P\_n(2)=\frac{1\cdot 2}{(n-1)(n-2)}\Delta P\_n(1)\\$
* And, in general, \\$\Delta P\_n(k)=\frac{(k-1)!(n-k)!}{(n-1)!}\Delta P\_n(1)={n-1\choose k-1}^{-1}\Delta P\_n(1)\\$ by induction.

Now, consider the telescoping sum
\\$P\_n(n)-P\_n(0)=1=\sum\_{k=1}^n\Delta P\_n(k)=\sum\_{k=1}^n{n-1\choose k-1}^{-1}\Delta P\_n(1)\\$.
Solving, we get our formula \\$\Delta P\_n(1)=P\_n(1)=\left(\sum\_{k=1}^n{n-1\choose k-1}^{-1}\right)^{-1}\\$.

The zero-indexed form is slightly more compact: \\$P\_{n+1}(1)=\left(\sum\_{k=0}^n{n\choose k}^{-1}\right)^{-1}\\$.
> 2 votes

# Answer
# Jelly, 7 bytes

5 bytes with `cŻİSİ` if we may print with floating point inaccuracy.

```
cŻPṄ:ƊS

```

A full program printing a numerator and then a denominator (not simplified).

**Try it online!**

### How?

```
cŻPṄ:ƊS - Main Link: integer, n
 Ż      - zero range -> [0,1,2,...,n]
c       - (n) choose (that) (vectorises) -> [1, n, ..., n, 1] (Pascal row n)
     Ɗ  - last three links as a monad - f(Pascal row n):
  P     -   product (of Pascal row n)
   Ṅ    -   print (product) and a newline; yield (product)
    :   -   (product) integer divide (Pascal row n) (vectorises)
      S -   sum
        - implicit print

```
> 1 votes

# Answer
# Charcoal, 24 bytes

```
ＦＮ⊞υ∨¬ι×⌈υιＩ⟦⌈υΣＥ⮌υ×ι§υκ

```

Try it online! Link is to verbose version of code. Explanation: Flipping `n` random bits in a string is equivalent to a random walk over the vertices of an `n`-dimensional hypercube; moving along an edge corresponds to flipping one of the bits. The starting point is the string of all `0`s and the diagonally opposite vertex is the string of all `1`s. The probability that it visits that vertex before it returns to the starting point is then documented in the linked page as being (n-1)!/A003149(n-1).

```
ＦＮ⊞υ∨¬ι×⌈υι

```

Input `n` and calculate the factorials up to `n-1`.

```
Ｉ⟦⌈υΣＥ⮌υ×ι§υκ

```

Output `(n-1)!` as the numerator and the sum of the termwise product of the factorials with their reverse as the denominator.
> 1 votes

# Answer
# 05AB1E, ~~6~~ ~~9~~ 8 bytes

*-1 thanks to Command Master.*

```
!,Ý!Â*O,

```

Try it online!

```
!,Ý!Â*O,  # full program
 ,        # output...
          # implicit input...
!         # factorial
       ,  # output...
      O   # sum of...
  Ý       # [0, 1, 2, ...,
          # ..., implicit input...
  Ý       # ]...
          # (implicit) with each element...
   !      # factorial...
          # (implicit) with each element...
     *    # multiplied by...
          # (implicit) corresponding element in...
  Ý       # [0, 1, 2, ...,
          # ..., implicit input...
  Ý       # ]...
          # (implicit) with each element...
   !      # factorial...
    Â     # reversed

```
> 1 votes

---
Tags: code-golf, math, rational-numbers, probability-theory
---


title: Every Pong is Abelian

text:
# Question
Title: Every Pong is Abelian
*Part of the Language of the Month*

A pong\* is a set \\$P\\$ with an operation \\$+\\$, that satisfies the following properties:

\\$ \forall a, b \in P : (b + b) + a = a\\ \forall a, b \in P : a + (b + b) = a\\ \forall a, b, c \in P: a + (b + c) = (a + b) + c \\ \\$

This makes a pong\*, just a group where every element is it's own inverse.

Now most operations we know of are not pongs. Addition is clearly not a pong. However you should be familiar with some. Exclusive or on booleans is a pong, since \\$\mathrm{True}\oplus\mathrm{True} = \mathrm{False}\\$ and \\$\mathrm{False}\oplus\mathrm{False} = \mathrm{False}\\$, and by extension bitwise xor on integers is also a pong.

A beginner level proof in Abstract Algebra is to show that every pong is an Abelian group. That is given the axioms prove

\\$ \forall a,b : a + b = b + a \\$

So as I thought it would be fun to tackle this problem as a beginner lean problem. Here's a pong class:

```
universe u

class pong (A : Type u) extends has_add A :=
  ( add_assoc : ∀ a b c : A, (a + b) + c = a + (b + c) )
  ( left_id : ∀ a b : A, (b + b) + a = a )
  ( right_id : ∀ a b : A, a + (b + b) = a )

open pong

```

Your task is to prove the following theorem:

```
theorem add_comm (A : Type u) [pong A] : ∀ a b : A, a + b = b + a

```

As is standard now you may rename the function and golf declaration as long as the underlying type remains the same.

You may not use any of the theorem proving sidesteps.

This is answers will be scored in bytes with fewer bytes being the goal.

I ask that if you are experienced in Lean you give a little time for beginners to have a go at this. Feel free to post your score below as a motivator. You can also post a hash of your program as proof.

* A term I just made up, because saying "Group where every element is its own inverse" gets tiring real quick.

# Answer
> 6 votes
# Lean, ~~115~~ ~~103~~ 100 bytes

```
def P:=@add_assoc
def V(A)[pong A](a b:A):a+b=_:=by rw[<-right_id$a+b,<-P,P a,<-P b,left_id,left_id]

```

Try it on Lean Web Editor!

-14 bytes thanks to Kyle Miller.

### Proof outline

```
a + b
= (a + b) + ((b + a) + (b + a)) -- by right_id
= ((a + b) + (b + a)) + (b + a) -- by add_assoc
= (a + (b + (b + a))) + (b + a) -- by add_assoc
= (a + ((b + b) + a)) + (b + a) -- by add_assoc
= (a + a) + (b + a) -- by left_id
= b + a -- by left_id

```

# Answer
> 4 votes
# Lean, ~~141 140~~ 121 bytes

* Saved one byte thanks to Wheat Witch/Wheat Wizard
* Saved 19 bytes thanks to Kyle Miller!

```
def s:=@add_assoc
def V(A)[pong A](a b:A):a+b=b+a:=by rw<-left_id b(a+b);repeat{rw<-s};rw s;simp[right_id,s(a+b),left_id]

```

Try it online

Bubbler's is much better, but I'm just throwing my hat into the ring anyway.

---
Tags: code-golf, abstract-algebra, lean
---


title: Multiple-Key Sorting

text:
# Question
Title: Multiple-Key Sorting
Given a list of indices and zero or more lists of integers, output the lists of integers, sorted in ascending order, with the key priority from the first input.

## Example

Let the keys input be `[1, 0, 2]`, and the lists input be `[[5, 3, 4], [6, 2, 1], [5, 2, 1]]`. Those lists need to be sorted by their second element, then first element, then third element, in ascending order:

1. First, we sort by the values at index `1`: `[[6, 2, 1], [5, 2, 1], [5, 3, 4]]`
2. Next, we break any ties from the first sort using the values at index `0`: `[[5, 2, 1], [6, 2, 1], [5, 3, 4]]`
3. Finally, we break any remaining ties with the vlues at index `2` (this doesn't actually change anything, because there are no ties remaining).

## Details

* Sorting is stable: if two elements compare equal with respect to the given sort keys, they must remain in the same relative order in the output. For example, if `A` and `B` are equal under the given sort keys, and the input was `[..., A, ..., B, ...]`, `A` must be placed before `B` in the output.
* A sort key will never reference a non-existant element in one of the input lists.
* No sort key will be repeated. Thus, `[1, 2, 1]` is not a valid list of sort keys.
* Any elements not referenced by the sort keys do not factor into the sorting order. Only the initial relative order and the values of the elements referenced by the sort keys determine the output order.
* You may choose whether the sort keys are zero-indexed or one-indexed.
* There will be no negative values in the sort keys. If you choose to use one-indexing, there will be no zeroes in the sort keys either.
* Integer values will not exceed your language's natively-representable range. If your chosen language is natively capable of arbitrary-precision integers (like Python), then any integer value can be present in the input, subject to memory constraints.

## Reference Implementation (Python 2)

```
#!/usr/bin/env python

keys = input()
lists = input()

print sorted(lists, key=lambda l:[l[x] for x in keys])

```

Try it online

## Test Cases

Format: `keys lists -> output`. All sort keys are zero-indexed.

```
[1, 0, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[5, 2, 1], [6, 2, 1], [5, 3, 4]]
[1, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[6, 2, 1], [5, 2, 1], [5, 3, 4]]
[0, 1] [[1, 2], [2, 1]] -> [[1, 2], [2, 1]]
[1, 0] [[1, 2], [2, 1]] -> [[2, 1], [1, 2]]
[0] [[4], [10, 11, -88], [-2, 7]] -> [[-2, 7], [4], [10, 11, -88]]
[2] [[-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6]] -> [[-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2]]
[2, 1] [[9, 2, -2, -10, -6], [3, -4, -2]] -> [[3, -4, -2], [9, 2, -2, -10, -6]]
[2, 4, 8] [[5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5], [-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3]] -> [[-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3], [5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5]]
[1, 2, 3, 4, 5] [[-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [5, 3, -6, -5, -4, -4, -8, 2], [9, -4, 1, -1, -3, -2], [-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [1, -5, -3, -10, -7, 9, -8, -5, -1], [-9, 4, -1, -1, 2, 4]] -> [[-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -5, -3, -10, -7, 9, -8, -5, -1], [9, -4, 1, -1, -3, -2], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [5, 3, -6, -5, -4, -4, -8, 2], [-9, 4, -1, -1, 2, 4]]
[8, 7, 3, 2, 4, 9, 1] [[8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9]] -> [[10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5]]

```

# Answer
# Jelly, 4 bytes

```
⁴ị$Þ

```

Try it online!
> 5 votes

# Answer
## CJam, 13 bytes

```
{W%{{X=}$}fX}

```

An unnamed block which expects the list of lists and the list of priorities on top of the stack and replaces them with the sorted list of lists.

Try it online! (As a test suite.)

### Explanation

Sorting with tie breakers can be implemented by repeatedly sorting the entire list stably going from the lowest-priority key to the highest-priority key.

```
W%      e# Reverse priority list.
{       e# For each priority X...
  {     e#   Sort the lists by the result of this block...
    X=  e#     Extract the Xth element from the current list.
  }$
}fX

```
> 5 votes

# Answer
## Mathematica, ~~22~~ 19 bytes

```
SortBy[Extract/@#]&

```

Uses 1-based indices. This unnamed function is curried, so the calling convention is:

```
SortBy[Extract/@#]&[{2, 1, 3}][{{5, 3, 4}, {6, 2, 1}, {5, 2, 1}}]

```

Mathematica's `SortBy` can take a list of functions in which case the individual functions are used as successive tie-breakers, so that's just what we want. All we need to do is create a list of functions which return the corresponding list element. This can be done with `Extract`. `Extract` is normally a binary function `Extract[list, index]` which returns a list element. However if used unarily, then `Extract[index]` returns a function which retrieves the element at `index` from a list passed to it. In other words, the `index` parameter of `Extract` can be curried. We make use of this by mapping `Extract` over the list of indices we're given, which creates the list of functions we need.
> 4 votes

# Answer
# Ruby, 35 bytes

```
->k,a{a.sort_by{|e|e.values_at *k}}

```

See it on eval.in: https://eval.in/652574
> 4 votes

# Answer
## Haskell, 38 bytes

```
import Data.List
sortOn.flip(map.(!!))

```

Usage example: `( sortOn.flip(map.(!!)) ) [2,1] [[9,2,-2,-10,-6], [3,-4,-2]]` -\> `[[3,-4,-2],[9,2,-2,-10,-6]]`.

Non-pointfree: `f k v=sortOn(\x->map(\y->x!!y)k)v`.
> 4 votes

# Answer
## Python, 50 bytes

```
lambda l,k:sorted(l,key=lambda x:[x[y]for y in k])

```

This is a trivially-golfed version of the reference implementation. `l` is the lists parameter, and `k` is the sort keys parameter. `l` can be any iterable, so long as its elements are subscriptable by integers (like lists, tuples, or int-keyed dicts). `k` can be any iterable.
> 3 votes

# Answer
# Brachylog, 29 bytes

```
tT,?hg:Tz:{:2f}o:ta
heI,?t:Im

```

Try it online!

### Explanation

We use the fact that `o - Order` can be used with an additionnal predicate as input: we order the lists by using for each `[Keys, a list]` the list of the elements of `a list` which are at index `a key` in the order that they appear in `Keys`.

```
                          Input = [Keys, List of lists]

tT,                       Call the Keys T
   ?hg:T                  Create the list [[T], List of lists]
        z                 Zip [T] with the list of lists
         :{   }o          Order by the output of this predicate
                :ta       Keep only the last element of each sublist in the Output

           :2f            Find all outputs of the predicate below

heI,                      Take a key I
    ?t:Im                 Output is the Ith element of the sublist

```
> 3 votes

# Answer
## CJam (12 bytes)

```
{{1$\f=}$\;}

```

Online demo. This is an anonymous block (function) which takes the arguments in the order given for the test cases and leaves the sorted value on the stack. It relies on the built-in sort `$` being stable, but the official interpreter guarantees that.

### Dissection

```
{          e# Define a block. Stack: orders values-to-sort
  {        e#   Sort by...
    1$\f=  e#     Copy orders from the stack, and map array lookup
  }$
  \;       e#   Pop the orders to leave just sorted-values
}

```
> 3 votes

# Answer
# J, 6 bytes

```
]/:{&>

```

Keys are zero-indexed. The LHS is the list of keys and the RHS is an array of values. Since J doesn't support ragged arrays, each array must be boxed.

## Usage

```
   f =: ]/:{&>
   < 1 0 2
┌─────┐
│1 0 2│
└─────┘
   5 3 4 ; 6 2 1 ; 5 2 1
┌─────┬─────┬─────┐
│5 3 4│6 2 1│5 2 1│
└─────┴─────┴─────┘
   (< 1 0 2) f  5 3 4 ; 6 2 1 ; 5 2 1
┌─────┬─────┬─────┐
│5 2 1│6 2 1│5 3 4│
└─────┴─────┴─────┘
   (< 1 2) f  5 3 4 ; 6 2 1 ; 5 2 1
┌─────┬─────┬─────┐
│6 2 1│5 2 1│5 3 4│
└─────┴─────┴─────┘
   (< 0) f 4 ; 10 11 _88 ; _2 7
┌────┬─┬─────────┐
│_2 7│4│10 11 _88│
└────┴─┴─────────┘

```

## Explanation

```
]/:{&>  Input: keys (LHS), values (RHS)
   {&>  Select from values at each index in keys
]       Get the values
 /:     Sort up the values using the ones selected with the keys

```
> 3 votes

# Answer
# Pyth, ~~5~~ 4 bytes

```
@LDF

```

Try it online: Demonstration or Test Suite

Thanks to @Maltysen for one byte.

# Explanation:

```
@LDFQ   Q (=input) added implicitly.
  D     sort a list of lists by
@L         the sublists generated by some indices
   FQ   executes ^ with the the input as parameter

```

I was really surprised that this worked. It's a really strange syntax.
> 2 votes

# Answer
## JavaScript (ES6), 55 bytes

```
(k,l)=>k.reduceRight((l,i)=>l.sort((a,b)=>a[i]-b[i]),l)

```

The ECMAscript standard doesn't guarantee that the underlying sort is stable, so the following 68-byte code doesn't make that assumption:

```
(k,l)=>l.sort(g=(a,b,i=0)=>i<k.length?a[k[i]]-b[k[i]]||g(a,b,i+1):0)

```
> 2 votes

# Answer
# JavaScript (ES6) 46

```
k=>l=>l.sort((a,b)=>k.some(i=>v=a[i]-b[i])&&v)

```

At each comparison during the sort, scan the key indices to find the right order

**Test**

```
f=k=>l=>l.sort((a,b)=>k.some(i=>v=a[i]-b[i])&&v)

;`[1, 0, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[5, 2, 1], [6, 2, 1], [5, 3, 4]]
[1, 2] [[5, 3, 4], [6, 2, 1], [5, 2, 1]] -> [[6, 2, 1], [5, 2, 1], [5, 3, 4]]
[0, 1] [[1, 2], [2, 1]] -> [[1, 2], [2, 1]]
[1, 0] [[1, 2], [2, 1]] -> [[2, 1], [1, 2]]
[0] [[4], [10, 11, -88], [-2, 7]] -> [[-2, 7], [4], [10, 11, -88]]
[2] [[-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6]] -> [[-9, 8, -5, -1, -7, -8, -5, -6, 5, -6, 6], [-7, 6, 2, -8, -7, 7, -3, 3, 0, -6, 1], [-1, -5, 8, -1, -4, -10, -5, 4, 4, 6, -8, 4, 2]]
[2, 1] [[9, 2, -2, -10, -6], [3, -4, -2]] -> [[3, -4, -2], [9, 2, -2, -10, -6]]
[2, 4, 8] [[5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5], [-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3]] -> [[-7, -8, -6, 7, 3, 8, 6, -7, -2, 0, -6, -4, 4, -3, 2, -3], [5, -3, 4, -6, -1, -2, -2, -4, 5], [-2, -3, 6, -4, -1, -4, -4, -5, 8, 9, 9, -3, 3, -9, -3], [2, 0, 10, -10, -1, 2, -1, 5, -1, 10, -5]]
[1, 2, 3, 4, 5] [[-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [5, 3, -6, -5, -4, -4, -8, 2], [9, -4, 1, -1, -3, -2], [-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [1, -5, -3, -10, -7, 9, -8, -5, -1], [-9, 4, -1, -1, 2, 4]] -> [[-6, -10, 4, -10, 6, 6, -1, 3, 0, 0], [1, -5, -3, -10, -7, 9, -8, -5, -1], [9, -4, 1, -1, -3, -2], [1, -2, -7, -6, -7, -7, -1, 0, -4, 3, 3], [-9, -1, -7, -9, -10, -2, -8, -10, -10, -3], [7, -1, -7, 2, -2, 9, 7, 5, -6, -8], [-7, 3, -8, 3, 5, -1, 6, -6, 9, 8], [5, 3, -6, -5, -4, -4, -8, 2], [-9, 4, -1, -1, 2, 4]]
[8, 7, 3, 2, 4, 9, 1] [[8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9]] -> [[10, -1, 3, 0, -4, 1, -5, -4, -1, -7, 9, -9, -1, -5, 7, 8, 9, 6, -3], [5, 6, -9, 0, -1, 5, 4, 7, 5, 10, 2, 5, 7, -9], [0, -9, -7, -2, 2, -5, 7, 4, 6, -4, 1, 8, -7, 10], [4, -8, 6, -10, -2, -3, 2, -6, 9, 5, 4, 10, 2, 3], [8, -5, 1, -6, -1, -4, 6, 10, 10, 6, 9, 5]]`
.split('\n').map(row=>{
  var [keys,list,expected]=row.split(/] -?>? ?\[/)
  keys=eval(keys+']');
  list=eval('['+list+']');
  expected=eval('['+expected);
  var result=f(keys)(list);
  var ok=result.join`|`==expected.join`|`;
  console.log(ok?'OK':'KO',keys+' '+list.join`|`+' -> ' +expected.join`|`,ok?'':result.join`|`)
})
```
> 2 votes

# Answer
# Perl 6  ~~23 20~~  19 bytes

```
->\a,\b{b.sort:{.[|a]}}
{$^a;$^b.sort:{.[|$a]}}
{$^b.sort: *.[|$^a]}

```

```
{$^b.sort: *[|$^a]}

```
> 2 votes

# Answer
## PHP, ~~212~~ 170 bytes

```
function m(&$i,$k){foreach($i as$a=>$y)for($b=-1;++$b<$a;){for($p=0;$p<count($k)&!$r=$i[$b][$x=$k[$p++]]-$i[$b+1][$x];);if($r>0){$s=$i[$b+1];$i[$b+1]=$i[$b];$i[$b]=$s;}}}

```

PHP has no stable sort built in anymore; picking an older version there is no way to do a recursive callback with the required specification. But nevermind: using the recursive callback iterator would cost tons; so I didn´t even check if that could do it.

The inner loop could be replaced with another `foreach`; that would save some bytes on the swapping. But without a check for `$b<$a` (or `$b<count($i)`), that will result in an infinite loop. And with that check, The `foreach` costs as much as the swapping wins.

I first did the comparison recursively; but iteration saves tons of bytes:

**breakdown**

```
// bubble sort
function m(&$i,$k)
{
    foreach($i as$a=>$y)
        for($b=-1;++$b<$a;)
        {
            // comparison:
            for($p=0;$p<count($k)                       // loop through keys
                &
                !$r=$i[$b][$x=$k[$p++]]-$i[$b+1][$x]    // while element equals its successor
            ;);
            // if element is larger than its successor, swap them
            if($r>0)
            {
                $s=$i[$b+1];$i[$b+1]=$i[$b];$i[$b]=$s;
            }
        }
}

```
> 2 votes

# Answer
## Racket 218 bytes

```
(λ(il ll)(define qsl(λ(l i)(if(null? l)l(let*((h(first l))(t(rest l))(g(λ(ff)(filter(λ(x)(ff(list-ref x i)
(list-ref h i)))t))))(append(qsl(g <)i)(list h)(qsl(g >=)i))))))(for((i(reverse il)))(set! ll(qsl ll i)))ll)

```

Ungolfed (il=index list; ll=list of lists; qsl= quicksort for list of lists; h=head (first element); t=tail (rest or remaining elements); g=modifiable filter fn):

```
(define qsl
  (λ(l i)
    (if (null? l)
        l
        (let* ((h (first l))
               (t (rest  l))
               (g (λ(ff) (filter (λ(x) (ff (list-ref x i) (list-ref h i))) t))))
          (append (qsl (g <) i)
                  (list h)
                  (qsl (g >=) i)
                  )))))
(define f
  (λ(il ll)
    (for ((i (reverse il)))
      (set! ll (qsl ll i)))
    ll))

```

Testing:

```
(f (list 0 1 2) (list (list 5 3 4) (list 5 3 7) (list 6 2 1) (list 6 1 3) (list 5 2 1)))
(f [list 1 2] [list [list 5 3 4] [list 6 2 1] [list 5 2 3]])

```

Output:

```
'((5 2 1) (5 3 4) (5 3 7) (6 1 3) (6 2 1))
'((6 2 1) (5 2 3) (5 3 4))

```
> 1 votes

# Answer
## R 40 bytes

```
for(i in rev(il)){dd=dd[order(dd[,i]),]}

```

Explanation:

List of lists is best represented as a data.frame in R:

```
ll2 = list(c(5,3,4), c(5,3,7), c(6,2,1), c(6,1,3), c(5,2,1))
dd = data.frame(do.call(rbind, ll2))
dd
      X1 X2 X3
    1  5  3  4
    2  5  3  7
    3  6  2  1
    4  6  1  3
    5  5  2  1

```

If index list is il (indexing is from 1):

```
il = list(1, 2, 3)

```

Sorting can be done with following code:

```
for(i in rev(il)){dd = dd[order(dd[,i]),]}

```

Output:

```
dd
  X1 X2 X3
5  5  2  1
1  5  3  4
2  5  3  7
4  6  1  3
3  6  2  1

```
> 1 votes

# Answer
# PHP, 139 Bytes

use the new spaceship operator and usort

```
<?$a=$_GET[a];function c($x,$y,$i=0){$k=$_GET[k];return$x[$k[$i]]-$y[$k[$i]]?:($k[++$i]?c($x,$y,$i):0);}usort($a,c);echo json_encode($a);

```

Instead of `$x[$k[$i]]<=>$y[$k[$i]]` you can use `$x[$k[$i]]-$y[$k[$i]]` under a PHP Version greater 7 - 2 Bytes

version with create an own index 197 Bytes like in a real library

```
<?$m=min(array_map(min,$a=$_GET[a]));foreach($a as$p=>$v){$k="";foreach($s=$_GET[s]as$f){$k.=str_pad($v[$f]-$m,5,0,0);}$k.=str_pad($p,5,0,0);$r[$k]=$v;}ksort($r);echo json_encode(array_values($r));

```
> 1 votes

# Answer
# K (ngn/k), 10 bytes

```
{y@<y[;x]}

```

Try it online!
> 1 votes

# Answer
**Clojure, 29 bytes**

```
#(sort-by(fn[c](mapv c %))%2)

```

Nicely `sort-by` is stable and knows how to sort vectors, and vectors can operate as functions. `([4 6 9 7] 2)` is `9` (0-based indexing).
> 0 votes

---
Tags: code-golf, number, array, sorting
---