text:
Cheat at Rock-Paper-Scissors-Lizard-Spock
When playing Rock-Paper-Scissors-Lizard-Spock, your robot reflexes let you see your opponent's throw before they make it. You just need to choose a throw that beats theirs, in as few bytes as possible of course.
There's always two winning throws, and either one will work.

Input    -> Possible outputs
------------------------------
Rock     -> Spock or Paper
Spock    -> Paper or Lizard
Paper    -> Lizard or Scissors
Lizard   -> Scissors or Rock
Scissors -> Rock or Spock

Take a string as input, and output one of the strings that beats it. Strings must be exactly as given, with capitalization. List of characters may substitute for strings.

It's a pity that the two hands that start with S have no outputs in common...

How about leading or trailing whitespace?

@Bubbler Nope, sorry.

@JoKing Hardly! Necessity is the mother of invention, and your solution is pretty clever.

V for "Vulcan" would fix the overloaded S!

@JoKing: The second letters of the possible inputs are distinct, though.  Possibly useful.

@JoKing The two hands that end in k do, though.

Perl 6, 36 30 bytes
{<Spock Lizard Rock>[.comb%4]}

Try it online!
Gets each output based on the length of the input modulo 4. I think this is probably the optimal strategy.

Perl 5 -p, 28 bytes
$_=/k/?Paper:/i/?Rock:Lizard

Try it online!
Tried @JoKing's length mod 4 method, but this turned out to be even shorter.

At first glance this looked like sed for me.

@val, Perl was inspired by sed and awk

+1, pretty sure this is optimal unless you can combine output words somehow.

PHP, 39 bytes
Shorter md5 variants by Christoph and Benoit Esnard.
<?=[Lizard,Spock,Rock][md5(y.$argn)%3];

Try it online!
<?=[Spock,Rock,Lizard][md5($argn.m)%7];

Try it online!

PHP, 40 bytes
<?=[Rock,Spock,Lizard][md5($argn)[5]%3];

Try it online!
Takes sixth character of md5 of input, which gives unique number of 1 for "Rock" and "Scissors", unique number of 2 for "Spock" and "Paper" and unique number of 9 for "Lizard". A mod 3 on those numbers and we have 0 or 1 or 2 indexes.
| Input    | MD5                              | 6th char | %3 | Output |
|----------|----------------------------------|----------|----|--------|
| Rock     | 4cfbb125e9878528bab91d12421134d8 |        1 |  1 | Spock  |
| Spock    | 5769c28299713c949cd59d5469e40ace |        2 |  2 | Lizard |
| Paper    | d0a662a5235ecde30739fe50cf0de830 |        2 |  2 | Lizard |
| Lizard   | 2f7569e00c4d97aef5f2c2b3a4d2213f |        9 |  0 | Rock   |
| Scissors | 28204140cee6e34a9843b64e5a490b08 |        1 |  1 | Spock  |

PHP, 40 bytes
Alternative 40 bytes, port of Jo King's answer.
<?=[Spock,Lizard,Rock][strlen($argn)%4];

Try it online!

PHP, 41 bytes
This is based on 79037662's answer.
<?=[Lizard,Rock,Paper][ord($argn[-1])%3];

Try it online!

PHP (7.4), 42 bytes
Uses fifth and sixth characters of input to get one of 0, 1 or 2.
fn($s)=>[Rock,Lizard,Paper][!$s[5]+!$s[4]]

Try it online!

PHP, 43 bytes
Uses CRC32 of input and mod to get 0, 1 or 2.
<?=[Rock,Lizard,Paper][crc32($argn)%866%3];

Try it online!

PHP, 43 bytes
Uses second to the last character of input ("Rock" and "Spock" = "c", "Paper" = "e", "Lizard" and "Scissors" = "r").
<?=[c=>Paper,e=>Lizard,r=>Rock][$argn[-2]];

Try it online!

39 by adding some pepper: <?=[Lizard,Spock,Rock][md5(y.$argn)%3];.

39 bytes: <?=[Spock,Rock,Lizard][md5($argn.m)%7]; - Try it online!

@BenoitEsnard ha beat you by 5 seconds! :)

APL (Dyalog Unicode), 28 bytes
'Spock' 'Lizard' 'Rock'⊃⍨4|≢

Try it online!
Uses the simple strategy based on input length modulo 4 (idea from Jo King's answer). ⎕IO←0.

APL (Dyalog Unicode), 34 bytes
'Lizard' 'Rock' 'Paper'⊃⍨'Xbj'⍸2∘⊃

Try it online!
Uses the shortest choice for all cases. ⎕IO←1.
How it works
'Lizard' 'Rock' 'Paper'⊃⍨'Xbj'⍸2∘⊃
2∘⊃     Take the second character
'Xbj'⍸  Classify it by intervals:
        'X'≤c<'b': 1
        'b'≤c<'j': 2
        'j'≤c    : 3
...⊃⍨   Give the nth string

Jelly, 16 14 bytes
Lị“ŀ¡ḋ¤:1KỌ»Ḳ¤

Try it online!
-2 bytes thanks to Jonathan Allan and Nick Kennedy both independently coming up with splitting on spaces instead of using a list literal.
A translation of Jo King's Perl 6 solution, using Jelly's compressed strings and modular indexing.
 ị                The element of
  “ŀ¡ḋ¤:1KỌ»      "Lizard Rock  Spock"
            Ḳ¤    split on spaces
 ị                at (1-based) index
L                 length of the input
  “ŀ¡ḋ¤:1KỌ»Ḳ¤    mod 4.

Using split-at-spaces saves two bytes: “ŀ¡ḋ¤:1KỌ»Ḳị@L or Lị“ŀ¡ḋ¤:1KỌ»Ḳ¤

I was about to post an almost identical comment: https://tio.run/##y0rNyan8/9/n4e7uRw1zjjYcWvhwR/ehJVaG3g939xza/XDHpkNL/gNlgvKTs4FUQGJBahGQDk7OLC7OLyoGMn0yqxKLUkBiBWA1cw9tPbrncPujpjWR/wE

That's 29 bytes in UTF-8, not 14

Am I missing something? It doesn't take input of the required form or produce output of the required form.

It's not in UTF-8, and it does input and output just fine if you take the footer out, and run it one case at a time. You can also use a footer that doesn't pair each input with the output, and just spits them out in order: Try it online!

JavaScript, 40 bytes
s=>['Spock','Lizard','Rock'][s.length%4]

Try it online!

Runic Enchantments, 42 bytes
il͍4%:0)9*?~"Spock"@1)9*?"Lizard"@"Rock"@

Try it online!
Footer runs all five input possibilities (the y sequences make them print in the correct order, no I'm not sure why the last one needed so many) and presets the stack with an input value (the input command then reads no input) and a newline. Remove the footer to use input instead.

Python 3, 44 bytes
lambda s:["Spock","Lizard","Rock"][len(s)%4]

Try it online!
Uses the input-length-modulo-4 strategy in Jo King's answer.

And it’s readable!

C (gcc), 51 49 bytes
Thanks to Unrelated String for the suggestion.
The second byte of the string has sufficient uniqueness that I can take its two least-significant bits and use them to then index into a string (with the longest-length result at the end if I rotate the result, fortunately!) The separator between the strings should be a literal NUL character, but I put a space in between them below so that you can see the gaps.
f(char*s){s="Spock Paper Scissors"+(s[1]-3)%4*6;}

Try it online!

You can replace the \0s with literal null bytes: Try it online!

Python 2, 73 69 bytes
lambda i:l[l.index(i)-1]
l="Rock Lizard Spock Scissors Paper".split()

Try it online!
Since there are already plenty of ports of @JoKing's excellent answer, here is a different way of doing it.

Haskell, 43 bytes
(k!!).length
k="Spock":"Lizard":"Rock":"":k

Try it online!
The mod-4 approach. Longer approaches:
f t|t<"Q"="Scissors"|t<"Sd"="Spock"|1<2="Paper"   (47)
f.last;f 'k'="Paper";f 'r'="Lizard";f _="Rock"    (46)
(["Spock","Lizard","Rock"]!!).(`mod`4).length     (45)
(words"Spock Lizard Rock"!!).(`mod`4).length      (44)
(cycle["Spock","Lizard","Rock",""]!!).length      (44)
(cycle(words"Spock Lizard Rock .")!!).length      (44)

Welcome back, Lynn!

I tried golfing some tweaks to your code, but it looks like your alternatives have pretty much covered everything. I did get two kind-of weird 45's: 1, 2.

Shakespeare Programming Language, 1359 bytes
(Whitespace added for readability)
R.Ajax,.Puck,.Act I:.Scene I:.[Enter Ajax and Puck]Ajax:
Open mind.Open mind.You is the remainder of the quotient betweenyou a big big cat.
Be you nicer a cat?If solet usScene V.
Be you nicer I?If solet usScene X.
You is twice twice twice twice the sum ofa big big cat a cat.Speak thy.You is the sum ofthe sum ofyou a big big big big cat a cat.Speak thy.You is the sum ofthe sum ofyou a big big big big cat a pig.Speak thy.You is the sum ofthe square oftwice the sum ofa big big cat a cat a cat.Speak thy.You is the sum ofyou the sum ofa cat twice twice the sum ofa big cat a cat.Let usScene L.
Scene V:.Ajax:
You is the sum ofa big cat the square ofthe sum ofa big big big cat a cat.Speak thy.You is twice twice twice twice the sum ofa big big big cat a pig.Speak thy.You is the sum ofyou a pig.Speak thy.You is the sum ofyou twice twice the sum ofa big pig a pig.Speak thy.You is the sum ofyou a big big big cat.Let usScene L.
Scene X:.Ajax:
You is the sum ofa big cat the square ofthe sum ofa big big big cat a cat.Speak thy.You is the sum ofyou a big big big big cat.Speak thy.You is the sum ofyou twice the sum ofa big cat a cat.Speak thy.You is the sum ofyou twice the sum ofa big big cat a cat.Remember you.Speak thy.Speak thy.You is the sum ofyou a big big pig.Speak thy.You is the sum ofyou the sum ofa big cat a cat.Speak thy.Recall.
Scene L:.Ajax:Speak thy.

Try it online!
Explanation:
I get the second character of the input mod 4:

This is 0 when the input is Spock, at which point Puck is neither nicer than a cat nor nicer than Ajax. Then, Scene I prints Paper.
This is 1 when the input is Paper or Lizard, at which point Puck is not nicer than a cat, but he is nicer than Ajax. Then, Scene X prints Scissors.
This is 3 when the input is Rock or Scissors, at which point Puck is nicer than a cat. Then, Scene L prints Spock.

Possible improvements:

Better math when printing to get between the letters, including switching characters and using Recall more
Better modulus because some of the things are longer than others, and I could reuse the ock
Possibly better ways to write the existing numbers. I actually am using a brute forcer that I wrote to do this, but it doesn’t yet account for getting between the letters (using ‘you’). GitHub link coming soon.

This was really fun and I love this language and I have no regrets.

Retina, 30 27 bytes
'R(`R
Sp
'i(K`Rock
K`Lizard

Try it online! Link includes all possible test cases. @BusinessCat's answer works perfectly well in Retina 0.8.2 but for Retina 1 we can do a little better by using a conditional stage. Explanation:
'R(`

If the input contains R...
R
Sp

... then replace the R with Sp, thus turning Rock into Spock...
'i(

... otherwise if the input contains i...
K`Rock

... then overwrite it with the string Rock, which beats Lizard and Scissors...
K`Lizard

... otherwise overwrite the input with Lizard, which beats Spock and Paper.

Nice. I still need to learn the new features in Retina 1. The .{6,} is clever though and saves bytes for mine too.

@BusinessCat I'm glad it helped you, as I've switched to an even better Retina 1 method now!

Ruby, 42 36 bytes
->c{%w(Spock Lizard Rock)[c.size%4]}

Try it online!

Ruby, 43 39 bytes
->c{%w(Lizard Rock Paper)[c[-1].ord%3]}

Try it online!
The second one is an alternative I found to Jo's method, using the ASCII value of the last character, but alas is 3 bytes longer in Ruby.
It is conceivable that my method is better in some language where finding the ASCII value of the last character is shorter than finding the string's length, but I don't know of any.
EDIT: Saved several bytes thanks to @IMP1

Why not .size instead of .length?

Also, have a look at this. You can use %w(Lizard Rock Paper) instead of ["Lizard","Rock","Paper"]

@IMP1 Thanks for the tips, still new to Ruby.

No worries. Ruby often has multiple methods that do the same thing (like .size and .length), so it's worth looking to see if there's one that's a few characters shorter.

F# (.NET Core), 53 49 46 bytes
 ["Spock";"Lizard";"Rock"].[String.length n%4]

Try it online!
I am using the input-length-modulo-4 strategy from Jo King's answer, so please check his answer.
And I know it's not in competition but I wanted to try something new…

V (vim), 28 bytes
2ORock
Lizard
SpockLÝkYHVGp

Try it online!
Hexdump:
00000000: 324f 526f 636b 0d4c 697a 6172 640d 5370  2ORock.Lizard.Sp
00000010: 6f63 6b1b 4cdd 6b59 4856 4770            ock.L.kYHVGp

Japt, 24 bytes
`Spock Lizd Rock`¸gUÊu4

Try it
"Spock Lizard Rock" //=>compressed
.q(S) // split on " "
.g(U.l().u(4)) // return element at index ( length of input % 4 )

Thanks to @Shaggy for the help

Python 3, 69 64 61 57 bytes
lambda s:[["Scissors","Paper"]['k'in s],"Rock"]['i'in s]

Not as short as the mod 4 solution, but not a bad alternative.
Try it online!

57 bytes by deleting some spaces

Haha, thanks! First code golf, my nasty programmer habits of formatting code are still strong! I also didn't realize you could remove spaces between a string and 'in'. TIL

@Ahndwoo Check out my tip on omitting spaces. tldr: you usually need a space only when letters are followed by letters or digits.

Pyth, 24 bytes
@c."Lzž›^ºéëEL”‡"\`lz

Try it online!
Port of Jo King's mod-4 answer. Without the compressed string, it's 2 bytes longer: @c"Spock`Lizard`Rock`"\`lz

Excel, 49 bytes
Mod4 approach:
=CHOOSE(MOD(LEN(A1),4)+1,"Spock","Lizard","Rock")

Switching on last character: 57 bytes
=CHOOSE(MOD(CODE(RIGHT(A1)),3)+1,"Lizard","Rock","Paper")

R, 52 bytes
function(x)c("Spock","Lizard","Rock")[nchar(x)%%4+1]

C# dotnet core, 47 bytes
h=>(new[]{"Spock","Lizard","Rock"})[h.Length%4]

Try it online
Uses the input-length-modulo-4 strategy in Jo King's answer.

You seem to be missing the function declaration part of your answer, i.e. the public static string RPSLS(string h){return ... } part. Taking input as a predefined variable is not an allowed input format, plus you're not actually outputting anything

This is a snippet where h is implicit. However, here we need a complete program or function. Unfortunately, though, dotnet core is too old to have =>, so a boilerplate will be quite long for this.

Fair enough. The lambda function definition is not much longer. I updated the .net fiddle to reflect that usage.

K, 26 bytes
`Paper`Rock`Lizard@&/"ki"?

The footer of the Jelly answer is simply a loop over the possible test cases, not a dictionary as additional argument. Jelly, and some other golfing languages like 05AB1E, have builtin dictionary files with ~10,000 words they know and can access with compressed strings. Here is that same Jelly program without a footer, and a given argument, so you can see the footer isn't part of the program and unrelated to the dictionary string “ŀ¡ḋ¤:1KỌ»

I've removed my comment, but that "program" doesn't work since it doesn't take the input as a string or as an argument.

///, 81 70 bytes
/~/\/\/.//.Sp/.~R/.~ock/Paper~Paper/Lizard~Lizard/Rock~Scissors/Rock/.

Because there is no other way to take input in ///, it goes after the . at the end of the code. For an input of Spock:
/~/\/\/.//.Sp/.~R/.~ock/Paper~Paper/Lizard~Lizard/Rock~Scissors/Rock/.Spock

Try it online!
Test suite
Explanation:
/// works by replacing strings with other strings, within the code.
The first chunk of code, /~/\/\/./, works as a macro replacing ~ with //.. After this, the code expands to:
/.Sp/.//.R/.//.ock/Paper//.Paper/Lizard//.Lizard/Rock//.Scissors/Rock/

/.Sp/./ and /.R/./ change spock and rock to ock, allowing me to just replace ock with Paper.
The rest of the cases are just explicitly handled.
The period before the input is to make sure that none of the code itself is changed, just the input.

Python 2, 50 bytes
lambda s:["Lizard","Rock","Paper"][cmp(s[-2],"e")]

Try it online!

Wren, 47 bytes
Fn.new{|s|["Spock","Lizard","Rock"][s.count%4]}

Try it online!
Uses the input-length-modulo-4 strategy in Jo King's answer.

05AB1E, 16 bytes
”‰«†ÕâŸard”#I3öè

Try it online!

Produces wrong answer for "Spock" (returns 5 "Papers" instead of the one)

@geocar No it doesn’t.

Retina 0.8.2, 36 33 31 bytes
-3 thanks to Neil
R
s
.{6,}
Rock
.{5}
Lizard
s
Sp

Try it online!

Can the first line be .[ci].*?

@Neil Yeah, probably.

Or not. That makes Rock give SpRock. I guess it would need to be ^.[ci].*

Batch, 87 bytes
@set/ps=
@for %%a in (Rock.d Rock.s Paper.k Lizard.r)do @if %%~xa==.%s:~-1% echo %%~na

Takes input on STDIN. Works by switching on the last character of the input, which saves a case.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Follow the Path, but is it valid?
Follow the Path
I got directions to my friend's house, but it looks like his map might have some mistakes. He's expecting me soon, so I need some short code to figure out if I can get there.
The Challenge
The code should, when given an ASCII representation of a path as input, traverse from the start to the end, and output depending on whether there is a valid path.
Input
Input is an ASCII representation of a map. It will use only the following symbols:
Character = Meaning
(space) = Blocked area
| = Vertical Path
- = Horizontal Path
+ = Intersection
^ or v = Horizontal Bridge
< or > = Vertical Bridge
$ = Start Location
# = End Location

Traversal Rules

Execution always starts on $ and will end when all paths are blocked, an infinite loop, or the pointer hits #. It is guaranteed that input will have exactly 1 of each.
The pointer starts moving to the right and down.
Vertical paths will only connect to vertical paths, vertical bridges, or intersections.
Horizontal paths will only connect to horizontal paths, horizontal bridges, or intersections.
If a vertical and horizontal path meet at a non-bridge, it is considered blocked at that point.
Bridges function according to the following:

 |      |
-^- OR -v- = Horizontal path going over a vertical path
 |      |

 |      |
-<- OR ->- = Vertical path going over a horizontal path
 |      |

When the pointer hits an intersection, movement precedence is in the clockwise direction (up, right, down, left). The pointer will not go back the way it came.
The program must detect/calculate infinite loops and branching paths from +.

Output
The length of the path, or -1, according to the following conditions:

If the program reaches #, output the path length.
If the program detects only blocked paths, return -1.
If the program detects an infinite loop, return -1.

Scoring
This is code-golf, so the shortest code in bytes wins! Standard loopholes are forbidden.
Test Cases
   $
   |
 +-|
#+-+
= 6 (going north at `#+-` will lead to a blocked path, but going to the west is a valid path)

#-+-+
  | |
$-^-+
  +-+
= -1 (Will infinitely loop)

$#
= 1

#^^^^+
     >
$----^-+
     > +
     +-+
= 20

$------+
|-----+|
 --#--+|
+--+---+
+------+
= 23

$ #
= -1 (Blocked by the space)

$|#
= -1 (Can't go onto a vertical path from the sides)

$
-
#
= -1 (Can't go onto a horizontal path from the top or bottom)

$|#
|--|
++++
= -1 (No valid paths exist)

@FryAmTheEggman If you go north, you will eventually hit a blocked path, meaning that path is invalid. However, this is also a valid path to the west, which is where the 4 should be a 6. I'll add in clarification.

I see, so you automatically look ahead to see that a turn will be invalid if you would be blocked, but not if there is a loop? I'd highlight that some more since it is fine, but surprising.

I've put in some more clarification

Shouldn't the fourth test case result in 20 instead of 19? You first go underneath the bridge at the intersection, and after that a second time across it. So 5 (east) + 4 (south) + 2 (east) + 2 (north) + 7 (west) = 20.

@KevinCruijssen Yeah, that should be 20.

@Arnauld Aight, will remove.

"Execution always starts on $ and will end when all paths are blocked, an infinite loop, or the pointer hits #." <-- Detecting an infinite loop for a small input is possibly trivial, but it's impossible to determine if the code will go into an infinite loop somewhere may require solving the Halting problem. It may still be (somewhat) possible to detect any infinite loop for any input, but I believe the question would be a lot more accessible if infinite loops weren't allowed.

JavaScript (ES6), 219 bytes
Takes input as a list of lists of characters.
a=>((g=(X,Y,D,n=o=0)=>!(a+0)[n++]|a.some((r,y)=>r.some((c,x)=>D=='975'[i='-| #+$'.indexOf(c),x-X+1]-'450'[y-Y+1]?i-3?i-2?i>3?[3,0,7,4].some(d=>D^d^4&&g(x,y,d,n)):~i&&i^D&1?0:g(x,y,D,n):0:o=-n:X+1|i<5?0:g(x,y,2))))(),~o)

Try it online!
How?
Because they need to be tried in a specific order, the way the directions are handled in this code is a bit unusual.
Given a direction \$D\$ and the source coordinates \$(X,Y)\$, we want to figure out which target coordinates \$(x,y)\$ correspond to a move by one square along \$D\$.
We use the following test for each candidate pair \$(x,y)\$:
D == '975'[x - X + 1] - '450'[y - Y + 1]

This test always fails if \$|x-X|>1\$ or \$|y-Y|>1\$ because we get an undefined value from at least one of the 2 lookup strings.
Otherwise, we have the following table:
$$\begin{array}{r|c|ccc}
&x-X&-1&0&+1\\
\hline
y-Y&&9&7&5\\
\hline
-1&-4&5&3&1\\
0&-5&4&2&0\\
+1&-0&9&7&5
\end{array}$$
Because diagonal moves are not used, our final compass looks as follows:
$$\begin{array}{cccc}
&&3\\
&&↑\\
4&←&2&→&0\\
&&↓\\
&&7
\end{array}$$
The lookup values were chosen in such a way that we end up with some handy properties:

Opposite directions can be detected by testing if \$d\operatorname{xor}d'=4\$. Hence the code to try all directions in clockwise order except the one that would make us going back the way we came:
  [3, 0, 7, 4].some(d => D ^ d ^ 4 && g(x, y, d, n))

Vertical moves are connected to odd values.

Horizontal moves are connected to even values (except direction \$2\$, for no move at all, which is only used at the beginning of the process when the starting point has been identified).

Python3, 934 bytes:
E=enumerate
V=lambda b,X,Y:0<=X<len(b)and 0<=Y<len(b[0])and b[X][Y]!=' '
def U(D,x,X):D[x]=D.get(x,[])+[X];D[X]=D.get(X,[])+[x]
def f(b):
 m,W=[[0,1,'-^'],[1,0,'|>'],[0,-1,'-^'],[-1,0,'|>']],{'^':'-','>':'|'}
 x,y=[[x,y]for x,r in E(b)for y,t in E(r)if'$'==t][0]
 q,D=[(x,y,0,not V(b,x,y+1))],{}
 while q:
  x,y,p,l=q.pop(0)
  if'#'==b[x][y]:return p
  if b[x][y]in'>^':
   for j,k,I in[(X,Y,i)for i,(X,Y,u)in E(m)if b[x][y]in u]+[(m[l][0],m[l][1],l)]:
    if(x+j,y+k)not in D.get((x,y),[])and(b[x+j][y+k]in'>#^+'or b[x+j][y+k]==W[b[x][y]]):U(D,(x,y),(x+j,y+k));q+=[(x+j,y+k,p+1,I)];break
  elif'+'==b[x][y]:
   T,O=[0,1,2,3],[]
   for i in T[l:]+T[:l]:
    if V(b,X:=x+m[i][0],Y:=y+m[i][1])and(X,Y)not in D.get((x,y),[]):
     if'#'==b[X][Y]:return p+1
     O+=[((X,Y),i)]
   if O:U(D,(x,y),O[0][0]);q+=[(*O[0][0],p+1,O[0][1])]
  elif V(b,X:=x+m[l][0],Y:=y+m[l][1])and b[X][Y]in(m[l][2]+'#+'):U(D,(x,y),(X,Y));q+=[(X,Y,p+1,l)]

Try it online!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Trick or Treating
Introduction
Little Jimmy is going trick or treating. He lives in an odd neighborhood: some houses give out candy, and some give out toothbrushes. Now, Jimmy does not want to get too many toothbrushes. He wants candy! You must help him get some.
Challenge
Each street in Jimmy's neighborhood has a number. Each house on the street will give out either candy or toothbrushes. However, Jimmy's parents know he gets very hyper if he eats too much candy. To prevent this, they are only letting him go down one street in the neighborhood. Given a list of streets, you must output the street where Jimmy will get the most candy and the fewest toothbrushes. This means that, as said in the comments, even if one street gives out 500 candies and 1 toothbrush, it is worse than one that gives out 1 candy and no toothbrush.

The list of streets will be 2D. It will never be empty. Each street will be a list of truthy or falsy values. It might be empty. Falsy values represent a house that gives out toothbrushes, truthy ones represent houses that give out candy.
Your program must output the index of the street with the most truthy values and the fewest falsy ones, or the street that gives the most candy and the fewest toothbrushes. If all the streets have the same amount of candy and toothbrushes, you may output -1. It does not matter if the index is 0-based or 1-based. It can be stored as a string. The integer can be in any base.

Example I/O
Note: In these lists, True represents a truthy value and False a falsy one. 0 can be replaced with 1 if your language uses 1-indexing.

Streets: [[True,True,True],[False,False],[False]]
Output: 0
Streets: [[False,True,True],[False,False],[True],[False]]
Output: 2
Streets: [[],[False,False,True],[False]]
Output: 0
Streets: [[True,True,False],[False,True,True],[True,False,True]]
Output: -1
Streets: [[True,True,True,True,True,False],[True]]
Output: 1
Streets: [[False, True],[False,True,True]]
Output:1

Rules
This is code-golf, so shortest code in bytes wins!

Must we output -1 if two streets are equal, or can we output one of the streets?

Wait, so getting 500 pieces of candy and a toothbrush is worse than getting only 1 piece of candy and no toothbrushes?

I'm not totally following how to determine the answer. Are we first minimizing falses and then maximizing trues? In which case I would suggest the test case [[False, True], [False, True, True]]

@Veskah, he must really hate toothbrushes. (Or love dentists)

Python 2, 58 bytes
lambda l:l.index(max(l,key=lambda s:(-s.count(0),sum(s))))

Try it online!

R, 52 bytes
function(l)order(lengths(l)-(m=sapply(l,sum)),-m)[1]

Try it online!
Minimizes the number of toothbrushes, then maximizes the pieces of candy, since this is apparently what OP is asking.
If we want to first maximize the amount of candy, then minimize the number of toothbrushes (seems more plausible…) it becomes
R, 51 bytes
function(l)order(m<--sapply(l,sum),lengths(l)+m)[1]

Try it online!
Computing the number of TRUEs in a list of vectors is easy with sapply(l,sum). Computing the number of FALSEs is much less golfy, so I use lengths minus the number of TRUEs instead.

Mathematica, 180 172 bytes
ToExpression[StringReplace[a,{"["->"{","]"->"}"," "->"=","True"->"-10^-9","False"->"1"}]];(If[Length[#]==1,#[[1]],-1]&@@Flatten[Position[#,Min[#]]]&/@{Total/@Streets})[[1]]

We assume the input is already stored as text in the variable a. If the reformatting code is neglected (input is already stored in the variable Streets) the length becomes 82 bytes.
My solution maps the toothbrushes (1) + candy(-1e-9) onto the real line and finds the minimum. It will only work for streets that have a maximum of 1,000,000,000 toothbrush houses as is (but it can be easily modified to suit the max number of toothbrush houses.)
Expanded code:
a := "Streets: [[True,True,False],[False,True,True],[True,False,True]]";
ToExpression[
 StringReplace[
  a, {"[" -> "{", "]" -> "}", " " -> "=", "True" -> "-10^-9",
   "False" -> "1"}]]
b = (Total /@ Streets)
c = Flatten[Position[b, Min[b]]]
If[Length[c]==1,c[[1]],-1]

Jelly, 15 bytes
ċþØ.N1¦ZM-¹L’$?

Try it online!
A monadic link taking a list of lists of Jelly booleans (0s and 1s). Returns the 1-indexed maximum list using the specified criteria, or -1 if there is more than one that is equal. The last 6 bytes are spent on converting multiple values into -1; if this could be dropped the answer would be 9 bytes.

J, 19 bytes
0{[:/:(-.,&(+/)-)@>

Try it online!

0 { first element of...
[: /: the grade up of... (indices with smallest item first)
(-.,&(+/)-) the list of pairs , created by summing each of &(+/): 1 minus an input item -. and the negative of an input item -
@> of each unboxed input item

This turns each input item into a pair:
<number of false, -1 * number of true>

When we sort this list J will automatically sort first by element 1, then by element 2.  Lower are numbers come first.


text:
Golf Lathe Machine
You probably know what a Turing Machine is but do you know what is a Turning Machine (lathe)?
Ok you already know.. and what about a Golf Turning Machine ??
Ok I tell you..
A Golf Turning Machine is a full program or function taking a list/array (or any convenient method) representing the Profile (P) of a turned piece and producing an ascii turned shape.
An ascii turned shape has square rotated by 45° cutting section instead of a circle so that we only need '/' and '\' characters to draw it.
And it has '_' characters for the profiles: upper, lower and median.(like the one of this challenge :  ASCII TURNED SHAPE ) for simple and nice drawing purpose.
      _________
     /\        \
    /  \________\
    \  /        /
     \/________/

A Profile P is a container of positive integers values in the range 0 <= value < 26(minimum)
    - Every value represents the radius of a 1 long character section, so the length of the container is the length of the piece obtained.
    - Alphabet are also valid [a to z] or [A to Z] they must correspond to a [0 to 25] value.

0 values at the beginning and at the end of the profile input can not be considered.

Test cases:
[2,2,2,2,2,4,4,4,4,4,6,6,6,6,6,4,4,4,4,4,2,2,2,2,2] or
"CCCCCEEEEEGGGGGEEEEECCCCC" or
['c','c','c','c','e',.....]
             _____
            /\    \
        ___/_ \    \__
       /\    \ \    \ \
   ___/_ \    \ \    \ \__
  /\    \ \    \ \    \ \ \
 /  \____\ \____\ \____\_\_\
 \  /    / /    / /    / / /
  \/____/ /    / /    / /_/
      \  /    / /    / /
       \/____/ /    /_/
           \  /    /
            \/____/

.
[1,0,0,0,0,0,0,3,3,0,0,1] or
[0,0,0,0,0,1,0,0,0,0,0,0,3,3,1,1,1,0,0,0]
         __
        /\ \
  _    /  \ \_
 /\\  /    \_\\
 \//  \    / //
       \  / /
        \/_/

.
[2,1,1,1,1,10,10,8,8,8,8,8,8,10,10,1,1,1,1,2]

           __      __
          /\ \    /\ \
         /  \ \__/_ \ \
        /    \ \   \ \ \
       /      \ \   \ \ \
      /        \ \   \ \ \
     /          \ \   \ \ \
    /            \ \   \ \ \
   /  _           \ \   \ \ \
  /  /\\___        \ \   \ \ \
 /  /  \\__\        \_\___\ \_\
 \  \  //__/        / /   / / /
  \  \//           / /   / / /
   \              / /   / / /
    \            / /   / / /
     \          / /   / / /
      \        / /   / / /
       \      / /   / / /
        \    / /___/ / /
         \  / /  \  / /
          \/_/    \/_/

Rules :
   - Margins are not specified.
   - Standard loopholes are forbidden.
   - Standard input/output methods.
   - Shortest answer in bytes wins.
Sandbox https://codegolf.meta.stackexchange.com/a/18150/84844

Can we choose the number of trailing and leading zeroes? (inferring from test case 2) If so, we can require a amount of zeroes that happens to be the output converted from ASCII to unary.

@someone if you refer to the input nope

JavaScript (ES6),  259 249  246 bytes
Takes input as an array of integers. Returns a matrix of characters.
a=>{for(m=[],i=a.length,X=i+25;i--;r[X]>' '|!w?0:r[X]='_',X--)for(y=w=a[i];y>=-w;y--)for(r=m[Y=y+25]=m[Y]||Array(X).fill` `,W=w+(y>0?1-y:y),k=2;k--;)for(x=-W;x<W;x++)r[X+x+k]='/\\  _'[w^a[i+k]|w^a[i+k-1]?(x+W&&2-!(~x+W))^y>0:y&&y-w?2:4];return m}

Try it online! (with leading and trailing empty lines removed for readability)
Commented
We are 'drawing' in a matrix \$m[\:]\$, from right to left. The code essentially consists of 4 nested for loops, followed by the matrix update.
First loop: input values
for(                            // initialization:
  m = [],                       //   m[] = output matrix
  i = a.length,                 //   i   = length of input
  X = i + 25;                   //   X   = center x-coordinate
                                // condition:
  i--;                          //   stop when i = 0; decrement i
                                // final expression:
  r[X] > ' ' | !w ? 0           //   unless w = 0 or there's already a character other
                  : r[X] = '_', //   than a space here, append the top '_'
  X--                           //   decrement X
)                               //

Second loop: rows
for(                            // initialization:
  y = w = a[i];                 //   y = w = next width, taken from the input list,
                                //   read in reverse order
                                // condition:
  y >= -w;                      //   stop when y = -w-1
                                // final expression:
  y--                           //   decrement y
)                               //

Third loop: slices
for(                            // initialization:
  r = m[Y = y + 25] =           //   r[] = row to update
      m[Y] || Array(X).fill` `, //   if undefined, initialize it with X leading spaces
  W = w + (y > 0 ? 1 - y : y),  //   W = width of the pattern at this row
  k = 2;                        //   k = counter to draw two consecutive slices
                                // condition:
  k--;                          //   stop when k = 0; decrement k
)                               //

Fourth loop: columns
for(                            // initialization:
  x = -W;                       //   start with x = -W
                                // condition:
  x < W;                        //   stop when x = W
                                // final expression:
  x++                           //   increment x
)                               //

Matrix update
r[X + x + k] =                  // set the character at the current position:
  '/\\  _'[                     //   0 = '/', 1 = '\', 2 or 3 = space, 4 = '_'
    w ^ a[i + k] |              //   if a[i] is different from a[i + k]
    w ^ a[i + k - 1] ?          //   or different from a[i + k - 1]:
      ( x + W &&                //     append a '/' if x = -W
        2 - !(~x + W)           //     append a '\' if x = W - 1, or a space otherwise
      ) ^ y > 0                 //     invert '/' and '\' if we're below the middle row
    :                           //   else:
      y && y - w ? 2 : 4        //     append a '_' if y = 0 or y = w,
  ];                            //     or a space otherwise

Suggest 32 for ' '

@ceilingcat This is not C. That would not work in JS.

Charcoal, 68 bytes
ＦＬθ«≔⌕α§⮌θιηＦη«Ｊ±⁺ιη⁰Ｇ↘η↗⊕η↖η ↘η←↙η↑↖η→↗η↘§_/⁼/ＫＫ≔⎇⁼ηζ◧_ηηδ↘δ←↙δ»≔ηζ

Try it online! Link is to verbose version of code. Takes a string of uppercase letters as input. Explanation:
ＦＬθ«

Loop once for each input letter.
≔⌕α§⮌θιη

Calculate the previous letter's value, since the drawing is done from end to start.
Ｆη«

Loop that many times; this is slightly golfier than an if since it doesn't need an else.
Ｊ±⁺ιη⁰Ｇ↘η↗⊕η↖η ↘η←↙η↑↖η→↗η

Erase and draw the main diamond of the section.
↘§_/⁼/ＫＫ

Draw the _ profile at the top if there isn't already a / there.
≔⎇⁼ηζ◧_ηηδ↘δ←↙δ

Draw the right side of the back of the section if this is a new section, otherwise erase the right side of the front diamond we drew last time (the left side was already erased earlier) leaving just two _s for the profiles.
»≔ηζ

Save the size of the section for the next loop.


text:
Pi to the power y, for small y's
Input
This task takes no input.
Output
Your code should compute and print (or return)
\$\pi^y\$ for all \$y = \frac11, \frac12, \frac13, \frac14, \frac15, \frac16, \frac17, \frac18, \frac19, \frac1{10}, \frac1{11}, \frac1{12}\$.  The first 20 digits of the output (truncated and without any rounding) should be correct in each case.
Here are the answers:
3.1415926535897932384
1.7724538509055160272
1.4645918875615232630
1.3313353638003897127
1.2572741156691850593
1.2102032422537642759
1.1776640300231973966
1.1538350678499894305
1.1356352767378998683
1.1212823532318632987
1.1096740829646979321
1.1000923789635869829

APL (Dyalog Extended), 9 8 bytesSBCS
(⍳12)√○1

Try it online! (⎕PP←34 is Print Precision: 34 digits; ⎕FR←1287 is Float Representation: 128-bit decimal)
○1 \$π×1\$
(…)√ take the following roots of that:
 ⍳12 ɩndices 1 through 12

Shouldn't ⎕PP←34 and ⎕FR←1287 be part of the byte-count?

@KevinCruijssen ⎕PP←34 certainly not, as it is just the print precision, not the actual precision of the returned (allowed by OP) value. ⎕FR←1287 can be set as a system default (so it doesn't need to be set by the programs), making it no worse than a "compiler" flag.

Ah ok, that makes sense. Thanks for clarifying.

JavaScript (ES7), 121 bytes
Computes as many digits as the precision of IEEE 754 allows and hardcodes the other ones.
_=>[32384,60272,2630,7127,[n=0]+593,2759,3966,4305,8683,2987,9321,69829].map(v=>(Math.PI**(1/++n)+'').slice(0,~(n==2))+v)

Try it online!
Commented
_ =>                          // input is ignored
[ 32384, 60272, 2630, 7127,   // hard-coded digits for n=1 to n=4
  [n = 0] + 593,              // initialize n to 0, and set this entry to '0593' (n=5)
  2759, 3966, 4305, 8683,     // hard-coded digits for n=6 to n=9
  2987, 9321, 69829           // hard-coded digits for n=10 to n=12
].map(v =>                    // for each entry in the above array:
  (Math.PI ** (1 / ++n) + '') //   increment n; compute π**(1/n) and coerce it to a string
  .slice(0, ~(n == 2))        //   remove the last 2 digits if n=2,
                              //   or only the last digit otherwise
  + v                         //   append the hard-coded digits
)                             // end of map()

I see what you have done... very nice :)

Apologies.. the last digit of Pi in the example should have been a 4.

@Anush No worries. Updated.

Nice! I made a similar solution in C.

Bash + bc + coreutils, 51, 40, 39, 36 bytes
following @ChristianSievers comment |cut -c -21 could be removed.
-3 bytes thanks to @DigitalTrauma.
echo "e(l(4*a(1))/"{1..12}");"|bc -l

Try it online!
Some explanations

bc -l define math functions and set scale to 20, see man bc for more details
a() atan function, so 4*a(1) is pi
e() exp function
l() log function, so e(l(x)/y) is x^(1/y)

Ahh... I am always very happy with a bash answer! Thank you.

Could you add some explanation please for the non-bc gurus here.

Untypically, this kolmogorov question doesn't demand some exact output, it only asks for 20 correct digits. So you can do without cut.

Or forget bash and just do it all in bc for 28: https://codegolf.stackexchange.com/a/195298/11259

@DigitalTrauma, :), i didn't know bc was on tio.

@DigitalTrauma, thanks for the solution, i didn't notice your first comment

Julia 1.0, 18 bytes
@.π^(1/big(1:12))

Try it online!
(1./big(1:12)) divides a BigInt 1 by each of 1 thru 12, then π.^ raises pi to each of those values. So long as there is one BigInt or BigFloat involved in each computation, it will calculate the result at that precision. The @. macro transforms the code to add dots to every function call (thus the dots that appear in my explanation that don't appear in the code snippet), this causes it to "broadcast" which for this purpose means do it all elementwise.
20->19 thanks to Robin Ryder
19->18 thanks to TimD

Very glad for a Julia answer. I had no idea you could define BigFloats so compactly!

It seems that you can save 1 byte with big(1) instead of big(1.).

Thanks. I swear I tested that, but clearly left with the wrong answer.

@.π^(1/big(1:12)) Saves another byte

My other now-bountied question might be another good place to show Julia’s abilities.

The current solution doesn't work as expected (it outputs π^n rather than π^(1/n)). TimD's suggestion, does however work for 18.

i fixed it again.

Wolfram Language (Mathematica), 22 20 19 bytes
-2 bytes thanks to game0ver
-1 byte thanks to LegionMammal978
Pi^(1`11/Range@12)&

Try it online!

This seems to calculate more precision than OP specified, and furthermore it rounds instead of truncates. I don't know Mathematica either so I don't know a good way of fixing this problem.

@79037662 More precision is ok as long as it matches the given output when correctly truncated.

@Anush Thanks for the clarification, that wasn't totally clear to me and I misunderstood.

If you change ,20 inside N to e.g. 25 it will produce results that approach the OP's data in the 19th floating point digit.

Also you can save two bytes by replacing range with [..] like that: N[Pi^(1/[1..12]),25], also PoC here.

@game0ver Thank you! Is this syntax [x..y] for Range special for WolframAlpha? (It doesn't work in TIO, as well as in Wolfram Cloud)

@GalenIvanov yes it's special for wolfram alpha, that's why I provided a link there.

WolframAlpha syntax ≠ Wolfram Language syntax. The two are totally separate, and WolframAlpha doesn't have any notion of pure text output. Also, since snippets aren't valid, you'd want to end it with an & to make it a function. The precision can also be specified in the 1 constant. All of these create a 19-byte solution runnable on TIO: Pi^(1\11/Range@12)&`

05AB1E (legacy), 47 43 40 bytes
•u¬Œo¡õ≠ÎĆζw1Á4¼©éßw–xùó1O•5ôεžqN>zm16£ì

-7 bytes thanks to @Grimy.
Try it online.
Uses the legacy version, because for some reason the new version outputs \$1.0\$ for \$\pi^{\frac{1}{1}}\$.. :S
Explanation:
•u¬Œo¡õ≠ÎĆζw1Á4¼©éßw–xùó1O•
             # Push compressed integer 323846027232630971275059342759739669430598683329877932169829
 5ô          # Split it into parts of size 5:
             #  [32384,60272,32630,97127,50593,42759,73966,94305,98683,32987,79321,69829]
ε            # Then map each integer to:
   N>        #  Take the 0-based map-index, and increase it by 1
     z       #  Calculate 1/(index+1)
 žq   m      #  Then calculate PI the power of this
       16£   #  Only leave the first 16 characters (including decimal dot)
          ì  #  And prepend it before the current integer we're mapping
             # (after which the mapped result is output implicitly)

See this 05AB1E tip of mine (sections How to compress large integers?) to understand why •u¬Œo¡õ≠ÎĆζw1Á4¼©éßw–xùó1O• is 323846027232630971275059342759739669430598683329877932169829.

I really like this answer. It's very clever.

43 by using 5ô instead of base compression.

@Grimmy Ah, didn't realize that would be shorter in this case. Should have known since they're all 5 digits.. Thanks! :)

-3 from a simple inversion of the loop

@Grimmy Ah, smart. Thanks!

Python 3, 61 69 63 bytes
Variant of Jitse's answer, who wants to stick to standard libraries. As mentioned by @Seb & @Jitse, Rational or E/E are needed because 1/i isn't precise enough as float.
from sympy import*;i=E/E
while i<13:print(N(pi**(1/i),99));i+=1

Try it online!
As a bonus, sympy allows to output 99 decimals with the same byte count as for 20 decimals:
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211707
1.77245385090551602729816748334114518279754945612238712821380778985291128459103218137495065673854467
1.46459188756152326302014252726379039173859685562793717435725593713839364979828626614568206782035382
1.33133536380038971279753491795028085330936622381810425845370748286670076101723561496824589105670695
1.25727411566918505938452211411044829390616631003965817353418162262716270074393519788994784267497245
1.21020324225376427596603076175994353105276255513631810467305643780646240044814351479113420061960303
1.17766403002319739668470085583704641096763145003350008756991802723553566109741289228117335907046316
1.15383506784998943054096521314988190017738887987082462087415032873413337243208073328092932090341440
1.13563527673789986837981146453309184806238366027985302804182074656192075351096762716281170420998022
1.12128235323186329872203095522015520934269381296656043824699758762377264153679046528721553289724806
1.10967408296469793211291254568401340513968966612239757917494488030006513039871082996506101420959919
1.10009237896358698298222864697784031503277459309498017808547779493972810083028975298933600450861044

sympy is cool :)

This output is incorrect for all lines after the second, from about the 16th digit. The Python float 1/i is preventing you from getting the precision you need. Replacing it with Rational(1,i) solves this issue at the cost of 8 bytes.

@Seb: Unpleasant but excellent comment, thanks.

You can save the hassle with Rational by initiating i as E/E: Try it online!

@Jitse Brilliant, wish I had thought of it.

Full credits to @flornquake for this trick.

Python 3, 91 bytes
import fractions as f;p=f.Decimal('%s2384'%f.math.pi);i=p/p
while i<13:print(p**i**-1);i+=1

Try it online!
-23 bytes thanks to flornquake

It doesn't quite give the right answer. Your first output ends 385 for example.  In general, compare the last digits of your answers to the outputs in the question.

@Anush Pi starts as 3.14159265358979323846, so ~385 should be correct, no? You may want to check your examples.

There was a mistake in the example but.. the spec says " The first 20 digits of the output should be correct in each case. The first 20 digits of the output should be correct in each case.". So the last digit should be 4.

@Anush I will argue that the first 20 digits are correct, since rounding is a proper way to cut off digits. If you don't allow rounding, please update your question to specifiy exactly what you want to want to see.

I've changed the wording to make it clearer.

@EricDuminil sympy is definitely allowed.

@EricDuminil Thanks, but feel free to post it as a separate answer. I like to stick to the standard libraries.

@Jitse: Done

-1 byte but this relies on undocumented cross-imports: Try it online!

bc -l, 28
for(;i<12;)e(l(4*a(1))/++i)

Try it online!

Ruby -rbigdecimal/math, 65 50 bytes
Conveniently, even though BigMath.PI(9) only guarantees precision up to 9 digits, it actually is precise up to 26, which is enough to calculate the exponents, which use the builtin Rational fractions instead of floats to ensure the precision is still good enough. (Also, making a Rational saves a byte over dividing it normally, since Ruby uses integer division if both arguments are integers, necessitating the use of 1.0 somewhere in the code.)
-15 bytes from histocrat!
1.upto(12){|i|puts BigMath.PI(9).**(1r/i).to_s ?F}

Try it online!

Great to see Ruby here. I don’t know if it helps but you don’t need to truncate as long as the first 20 digits are correct.

Pari/GP, 20 bytes
vector(12,n,Pi^n^-1)

Try it online!
(TIO needs some supporting code, but this works as is in the REPL.

Thank you. I was hoping you might be interested in my now-bountied question too.

cQuents, 268 bytes
#1&"3.1415926535897932384
1.7724538509055160272
1.4645918875615232630
1.3313353638003897127
1.2572741156691850593
1.2102032422537642759
1.1776640300231973966
1.1538350678499894305
1.1356352767378998683
1.1212823532318632987
1.1096740829646979321
1.1000923789635869829"

Try it online!
There is no way to get more precision out of floats in cQuents, so the values must be hardcoded as strings.
cQuents, 11 bytes
#12&`p^(1/$

Try it online!
Does not reach the required precision levels.

It doesn't look like the output is to the right precision.

@Anush fixed, don't have higher-precision floats so have to hardcode it

Octave, 23 bytes
vpa(pi,22).^(1./(1:12))

Try it online!
Declares a variable precision arithmetic (VPA) pi. Octave then cleverly infers that the double constant pi actually means pi, not whatever the double constant contains.

The output isn't quite right. See the output in the question. Maybe you are rounding?

@Anush yep. Needed two extra digits instead of just one. Edited now.

“cleverly infers that the double constant pi actually means pi”. I wonder if it really does this cleverly or just has π hard-coded as a special case...

@ceased It infers multiples of pi as well. But yes, probably hardcoded, for example, it does not infer pi+1

C (gcc -lm), 171 131 122 bytes
Shaved off 40 49 bytes thanks to ceilingcat.
i;p(){for(;i<12;)printf("%.14f%d ",pow(acos(~fesetround(1024)),1./++i),L"纀罶얡꜇胛"[i]);}

Try it online!
Output:
3.1415926535897932384 1.7724538509055160272 1.4645918875615232630 1.3313353638003897127 1.2572741156691850593 1.2102032422537642759 1.1776640300231973966 1.1538350678499894305 1.1356352767378998683 1.1212823532318632987 1.1096740829646979321 1.1000923789635869829

R + Rmpfr, 80 bytes
Requires package Rmpfr.
mpfr("1.00000000238982476721842284052415179434",30 *log2(10))^(479001600/(1:12))

Gives the following, with truncations mine and some minor formatting
12 'mpfr' numbers of precision  99   bits
3.1415926535897932384...
1.7724538509055160272...
1.4645918875615232630...
1.3313353638003897127...
1.2572741156691850593...
1.2102032422537642759...
1.1776640300231973966...
1.1538350678499894305...
1.1356352767378998683...
1.1212823532318632987...
1.1096740829646979321...
1.1000923789635869829...

See below for why simpler versions don't work. Direct calculation using exponents 1/N for N=1,12 returned inaccurate value fairly early. I figured that was probably due to R or Rmpfr rounding 1/3 early, so whole number exponents would be preferred. So I calculated pi^(12!) (12!=479001600) using Mathematica, then raised it to the power of 12!/N, which would always be a whole number. I had to further tune it by passing the number to Rmpfr as a character vector (so R wouldn't round it), and by using an arbitrarily high precision in both Mathematica and Rmpfr so it would truncate accurately. Because of those arbitrary additions, I can probably shave off a few bytes, but I'm good with it as is.
R, 29 bytes
This only works if R value for pi is accurate, which it isn't. Even reassigning the variable pi to a more accurate representation does not improve accuracy, as it rounds or something around 17 decimals.
format(pi^(1/1:12),nsmall=20)

Try it online
Or, for 30 bytes
options(digits=20);pi^(1/1:12)

There's a package that gives a more accurate value for pi and other floating point numbers, Rmpfr, which you'll find referenced in questions about pi in R. One might expect the following to give the desired output.
library(Rmpfr)
Const("pi",20 *log2(10))^(1/1:12)

It doesn't. It gives
12 'mpfr' numbers of precision  66   bits
[1] 3.1415926535897932385  1.7724538509055160273  1.464591887561523232
[4] 1.3313353638003897128 1.2572741156691850754 1.2102032422537642632
[7]  1.177664030023197386 1.1538350678499894305 1.1356352767378998604
[10] 1.1212823532318633058 1.1096740829646979353 1.1000923789635869772

This is wrong on all counts by rounding or being a few off in the last digits (sidenote: the rnd.mode flag for mpfr does not fix this). Now one might think if we went up to many digits (say 100), then it would surely be correct to the first 20 digits. Nope
12 'mpfr' numbers of precision  332   bits
 [1] 3.1415926535897932384...
 [2] 1.7724538509055160272...
 [3] 1.4645918875615232319...
 [4] 1.3313353638003897127...
 [5] 1.2572741156691850753...
 [6] 1.2102032422537642631...
 [7] 1.1776640300231973859...
 [8] 1.1538350678499894305...
 [9] 1.1356352767378998603...
[10] 1.1212823532318633058...
[11] 1.1096740829646979353...
[12] 1.1000923789635869771...

(Truncations mine). These don't all match OP or the other responses.

The output is not correct. Compare it with the output in the question.

@Anush I noticed that just now. Strange, it appears r's built-in pi constant is not precise to 20 decimals.

You might need Rmpfr.

@Anush Unfortunately, no. That gives a highly precise output for any arbitrary digits of pi, but once you start manipulating the number, it loses accuracy. For Const("pi",68)^(1/3) it gives 1.4645918875615232319, which is off.

Even the value of pi outputted by your code is wrong. If you use Rmpfr you can start with slightly more precision than you need to get the right result in the end. Look at the other answers to this question.

@Anush I am aware. My point is that it doesn't matter if I do Const("pi",3333)^(1/1:12), it's still wrong to 20 digits by the time it gets to Const("pi",3333)^(1/3), and is therefore wrong for the remaining numbers. I can't give you a TIO link as it involves a library, but just take my word for it.

@John part of this challenge is working around the precision issues of your language, since the double-precision floating point numbers used by most languages only goes up to 15 digits of accuracy. See the JavaScript answer for an example of how someone has worked around the accuracy issue even though it doesn't have a higher-precision decimal type.

@ValueInk Thanks, I am aware. Clearly I didn't expect R to have that flaw when I submitted.

@Anush Please see my most recent edit for an improved answer using Rmpfr

It really looks like a bug that ought to be reported!

Firstly, you need to list this as R + Rmpfr, since it doesn’t work on just base R. Secondly, the reason your first Rmpfr solution didn’t work is that you need the fractions to have sufficient accuracy. Try library(Rmpfr);Const("pi",70)^(mpfr(1,70)/1:12) https://rdrr.io/snippets/embed/?code=library(Rmpfr)%0AConst(%22pi%22%2C70)%5E(mpfr(1%2C70)%2F1%3A12) 47 bytes

@NickKennedy So, like I said. prec'

C (gcc) with libquadmath, 107

2 bytes saved thanks to @ceilingcat.

This uses __float128 to get the required precision.
#import<quadmath.h>
s[9];main(i){for(;i<13;puts(s))quadmath_snprintf(s,36,"%.99Qf",expq(logq(M_PIq)/i++));}

Try it online!

I was curious to try this using the GNU MPFR library too:
C (gcc) with libmpfr, 123

13 bytes saved thanks to @ceilingcat.

#include<mpfr.h>
i;main(){MPFR_DECL_INIT(p,99);for(;i<12;){mpfr_const_pi(p,99);mpfr_root(p,p,++i,MPFR_RNDN);mpfr_printf("%.19Rf\n",p);}}

Try it online!

Really pleased to see a C answer!

Nice one with libquadmath. Now there's two C solutions that technically count as different languages.

Could you link to an HTML version of that doc so it can be viewed on mobile more easily?

The libmpfr solution  can be fixed by just changing .19 to .21. There is no need to truncate the answer yourself. (The rounding is not down. That's why the second line was outputted as 273 instead of 272.)

Looks good to me

It would be great to see a C/C++ where to my other bountied question too...

@ceilingcat - Thanks!

Canvas, 30 bytes
６«｛“≥αｙＨT.─Ｃ¹„1.0000ŗ┤“^m„┘÷＾］

Don't try it here! It'll take a while to calculate all those digits (it took ~15 minutes to run for me). Rather, here's a version of the same code, only outputting the last 3 items.
Computes C ^ (27720/N) where C is the hard-coded constant pi^(1/27720) = 1.000041297024626834690309 and N is looped over from 1 to 12. The big number library decided to expand the amount of significant digits for successively bigger N, making the code take unreasonable amounts of time to run.

Python 3, 146 bytes
import math
for i in range(1,13):print(str(math.pi**(1/i))[:~(i==2)]+str([32384,60272,2630,7127,'0593',2759,3966,4305,8683,2987,9321,69829][i-1]))

Try it online!
This uses a similar method to Arnauld's JavaScript solution, by using the inbuilt pi value with the extra precision added to the end.

-2 bytes by using range(12) over range(1,13): Try it online!

Jelly, 46 bytes
12İ€ØP*×ȷ19Ḟ+“Ṿẏ⁽)¬ọƓỴ³ɲỊUị&ıİḣl’ḃ4ȷ¤_2ȷD;"€”.

Try it online!
Similar to some other answers, but encodes the difference between the Jelly answer and the correct answer (with big integer arithmetic). Full explanation to follow.

jelly 46 bytes? Is this a software suite?

@GeorgeMenoutis Jelly is a programming language linked to through the title of my post. It’s designed for CodeGolf so has many one character built-ins. It also uses its own 8-bit code page.

ah Nick, you didn't catch my joke. Jelly answers are usually <10 bytes; so, with 46 bytes, the program developed must be a suite...

Oh I see! Sorry for missing the joke...

Java 10, 316 299 268 259 bytes
v->Math.PI+"2384 1.7724538509055160272 1.4645918875615232630 1.3313353638003897127 1.2572741156691850593 1.2102032422537642759 1.1776640300231973966 1.1538350678499894305 1.1356352767378998683 1.1212823532318632987 1.1096740829646979321 1.1000923789635869829"

-40 bytes by just hard-coding the output instead of calculating it.. >.>
-9 bytes thanks to @ceilingcat.
Try it online.
Old 299 291 bytes answer with actual calculations..
v->{var P=new java.math.BigDecimal(Math.PI+"2384");var x=P;for(int i=0;++i<13;System.out.println(x)){var p=P;for(x=P.divide(P.valueOf(i),21,5);x.subtract(p).abs().compareTo(P.ONE.movePointLeft(22))>0;)x=P.valueOf(i-1).multiply(p=x).add(P.divide(x.pow(i-1),21,5)).divide(P.valueOf(i),21,5);}}

Not entirely precise, but good enough to have the first 20 digits correct.
Try it online.
Explanation:
Most bytes come from the fact that BigDecimal doesn't have a builtin for BigDecimal.pow(BigDecimal) nor the \$n\$th root, so we'll have to calculate this manually..
v->{                         // Method with empty unused parameter and no return-type
  var P=new java.math.BigDecimal(Math.PI+"2384");
                             //  Create a BigDecimal for PI
  var x=P;                   //  Create a BigDecimal to print after every iteration
  for(int i=0;++i<13;        //  Loop `i` in the range [1,12]:
      System.out.println(x)){//    After every iteration: print `x` to STDOUT
    var p=P;                 //   Create a BigDecimal to save the previous value
    for(x=P.divide(P.valueOf(i),
                             //   Set `x` to PI divided by `i`
                   21,5);    //   (with precision 21 and rounding mode HALF_DOWN)
                             //   Continue an inner loop as long as:
        x.subtract(p).abs()  //   The absolute difference between `x` and `p`
         .compareTo(P.ONE.movePointLeft(22))>0;)
                             //   is larger than 1e-22
      x=                     //    Set `x` to:
        P.valueOf(i-1)       //     `i-1`
         .multiply(p=x)      //     Multiplied by `x` (and store the previous `x` in `p`)
         .add(               //     And add:
          P.divide(          //      PI divided by
           x.pow(i-1),21,5)) //      `x` to the power `i-1`
         .divide(P.valueOf(i),21,5);}}
                             //     Divided by `i`

Looks like I should have asked for 15 roots in the end! I was worried about Java from the beginning.

You can compute the 1/5, 1/7,1/8,1/9,1/11 th roots. All the other ones can be made from these using multiplication and division which I assume BigDecimal supports.

Perl 5, 72 bytes
$n=1;print substr(Math::BigFloat->bpi()**(1/$n++),0,21).$/ while($n<13);

Even using \$\pi\$ from BigFloat, it doesn't seem to exactly match the given outputs. I'm sure it's truncated properly, though.
Try it online!

A Perl bug maybe?

Fortran (GFortran), 48 bytes
print*,(acos(-1._16)**(1/real(i,16)),i=1,12)
end

Try it online!
Just an implicit loop with quad-precision vars. Not transferable, but works with GCC.


text:
Fermat's Last Theorem, mod n
Fermat's Last Theorem, mod n
It is a well known fact that for all integers \$p>2\$, there exist no integers \$x, y, z>0\$ such that \$x^p+y^p=z^p\$. However, this statement is not true in general if we consider the integers modulo \$n\$.
You will be given \$n\$ and \$p\$, which are two positive integers with \$n>1\$. Your task will be to write a function or program to compute all positive integers \$x, y, z<n\$ such that \$(x^p+y^p)\$ and \$z^p\$ give the same remainder when divided by \$n\$.
Input
Any reasonable method of input is allowed. E.g. two separate user inputs, ordered pair, two function parameters, etc.
Output
Any reasonable method of output is valid, it may be produced by a function or output to the screen. The order the triples are listed does not matter. Triples such as (1, 2, 3) and (2, 1, 3) are considered distinct, and all distinct triples should be listed exactly once. No invalid/trivial triples such as (0, 0, 0) should be output.
The numbers \$x, y, z\$ may have any ordering within each of the triples, but that order should be consistent. For example if \$2^p+2^p\$ and \$3^p\$ have the same remainder when divided by \$n\$, you may list this triple as (2, 2, 3) or (3, 2, 2).
Examples
n p -> Possible Output
----------------------------------------------------------------
2 3 -> []
3 3 -> [(1,1,2),(2,2,1)]
3 4 -> []
4 3 -> [(1,2,1),(1,3,2),(2,1,1),(2,2,2),(2,3,3),(3,1,2),(3,2,3)]

Scoring
Shortest code in bytes with no standard loopholes wins.

I guess we have to specify how triplets are ordered and be consistent.. E.g. All (x,y,z) or all (z,x,y) and so on

@AZTECCO Good point, I will add that specification.

I'm not convinced that solutions with z=0 are trivial.

@Neil I didn't say they were, but they are invalid for the purposes of this question.

So (1 2 3) and (2 1 3) would be 2 different solution...

@RosLuP Correct.

Julia 1.0, 61 bytes
f(n,p,q=1:n-1)=[(x,y,z) for x=q,y=q,z=q if(x^p+y^p)%n==z^p%n]

-1 thanks to Glen O
Try it online!

You can drop the space after if to save a byte.

05AB1E, 15 10 bytes
-2 bytes by Kevin Cruijssen
-3 bytes by Grimmy
<L3ãʒImÆ¹Ö

Try it online!
Returns a triples in the format [z,y,x].
Explanation:
<L                | Push the interval [1,n)
  3ã              | Push the triple cartesian product [1,n) x [1,n) x [1,n)
                  | E.g. with n = 3, the list begins as follows:
                  | [[1, 1, 2], [1, 2, 1], [2, 1, 3], ...]
    ʒ             | Filter the list:
     Im           | Take the p-th power of each input
                  | E.g. [1, 1, 2] --> [1^p, 1^p, 2^p]
       Æ          | Reduce by subtraction
                  | E.g. [1^p, 1^p, 2^p] -->  1^p - 1^p - 2^p
        ¹Ö        | Check if 1^p - 1^p - 2^p = 0 (mod n), and filter out if not.

The specification says the order of the numbers in the triple does not matter (as long as it's consistent). Is the í necessary?

Ops! Yes, then it is not needed. Good catch, thanks.

0Q can be _ to save a byte.

13 bytes by outputting as triplets in the order [z,y,x].

10 bytes

Thanks a lot! Glad you found a way to got rid of that ugly Ðââ I had in my original solution.

That's still 15 bytes in my book: echo -n '<L3ãʒImÆ¹Ö' | wc -c

It is 10 bytes; 05AB1E uses its own codepage

APL (Dyalog Unicode), 19 bytes
{⍸0=⍵|-/¨⍺*⍨⍳3⍴⍵-1}

The triples are returned in the format x z y.  Try it online!
Explanation
{⍸0=⍵|-/¨⍺*⍨⍳3⍴⍵-1} ⍝ n is our right argument, ⍵, and p is our left, ⍺.

             3⍴⍵-1  ⍝ First, we get a triple of (n-1, n-1, n-1).
            ⍳       ⍝ Then we get the Cartesian product of three range[1, n-1).
                    ⍝ As you will see, this gives a list of (x z y) triples.
         ⍺*⍨        ⍝ We take each element of each triple to the power of p.
      -/¨           ⍝ Here we subtract over each triple, using (element - rest)
                    ⍝ This gives us (x^p - (z^p - y^p)) = x^p + y^p - z^p.
    0=              ⍝ Then we check which (x^p + y^p - z^p) equals 0.
   ⍸                ⍝ And use these results, a Boolean array,
                    ⍝ to find get the indices of the correct triples,
                    ⍝ which are our (x z y)s.

Jelly, 13 bytes
*ŒH§%³E
Ṗṗ3çƇ

A full program accepting command line arguments n p which prints a list representation of the results (Do note that the empty list is represented as no output).
Try it online!
How?
*ŒH§%³E - Link 1: evaluate a triple: [x, y, z], p
*       - exponentiate               [x^p, y^p, z^p]
 ŒH     - split into halves          [[x^p, y^p], [z^p]]
   §    - sums                       [x^p+y^p, z^p]
     ³  - program's 1st argument     n
    %   - modulo                     [(x^p+y^p)%n, (z^p)%n]
      E - all equal?                 (x^p+y^p)%n == (z^p)%n

Ṗṗ3çƇ - Main Link: n, p
Ṗ     - pop (implicit range of n)    [1,2,3,...,n-1]
  3   - literal three                3
 ṗ    - Cartesian power              [[1,1,1],[1,1,2],...,[n-1,n-1,n-1]]
    Ƈ - filter keep those for which:
   ç  -   last Link (1) as a dyad    Link 1([[1,1,1],[1,1,2],...,[n-1,n-1,n-1]], p)
      - implicit print

GAP, 63 bytes
Filtered(Tuples([1..n-1],3),i->(i[1]^p+i[2]^p-i[3]^p) mod n=0);

For example:
gap> n:=4; p:=3;
4
3
gap> Filtered(Tuples([1..n-1],3),i->(i[1]^p+i[2]^p-i[3]^p) mod n=0);
[ [ 1, 2, 1 ], [ 1, 3, 2 ], [ 2, 1, 1 ], [ 2, 2, 2 ], [ 2, 3, 3 ],
  [ 3, 1, 2 ], [ 3, 2, 3 ] ]

Octave, 74 72 bytes
2 bytes saved thanks to @79037662
@(n,p){[c,b,a]=ndgrid(1:n-1) [a(k=~mod(a.^p+b.^p-c.^p,n)) b(k) c(k)]}{2}

Try it online!

Do you need the extra pair of parentheses in a((k=~mod(a.^p+b.^p-c.^p,n)))?

@79037662 No, they are not needed. They were a leftover from some (unsuccessful) tests to try to get rid of the cell array. Thanks!

JavaScript (ES7), 104 bytes
Takes input as (n)(p).
n=>p=>[...Array(n**3)].map((_,i)=>[i/n/n|0,i/n%n|0,i%n]).filter(([x,y,z])=>x*y*z&&(x**p+y**p)%n==z**p%n)

Try it online!

R, 67 bytes
function(n,p,m=t(expand.grid(a<-2:n-1,a,a)))m[,!c(1,1,-1)%*%m^p%%n]

Try it online!
expand.grid creates all possible triplets of numbers. Annoyingly, the output of expand.grid is a data frame and not a matrix, so I transpose it to coerce to a matrix m. Take the matrix product of [1,1,-1] with m^p to get \$x^p+y^p-z^p\$, then keep only the rows for which we get \$ 0 \mod n\$.

nice, I tried a different approach and only got down to 68

@MickyT Nice idea using which with 3d indices! Here is a 65 byte version of yours, which you should post separately as it is substantially different.

R, 65 bytes

3 btye's saved from my original idea by @robin-ryder by using subtraction, applying modulo the result.
function(n,p,q=(2:n-1)^p)which(!outer(outer(q,q,'+'),q,'-')%%n,T)

Try it online!
Makes use of outer to build a 3d array of the addition, then the subtraction. If the remainder of n is 0 output the array indices using which.

Wolfram Language (Mathematica), 54 bytes
n_~f~p_:=Select[Range[n-1]~Tuples~3,n|{1,1,-1}.#^p&]

Named function taking the two inputs, like f[4,3].
The | symbol typed above needs to be replaced by the 3-byte character representing the "divides" relation; \[Divides] works as well, and is used in the TIO example.
Works by testing every possible triple {x,y,z}. The only detail of note is that the dot product {1,1,-1}.#^p&, when applied to {x,y,z}, calculates x^p+y^p-z^p.
Try it online!

Jelly, 13 bytes
*+_ƭ/³ḍ
Ṗṗ3çƇ

Try it online!
-2 bytes thanks to caird coinheringaahing
-1 byte borrowing a clever trick from Jonathan Allan
Explanation
*+_ƭ/³ḍ  Helper Link - given (x, y, z), determine if x^p + y^p = z^p (mod n)
*        (x^p, y^p, z^p)
    /    Reduce over
 +_ƭ     Tied operator: cycle between + and - (x^p + y^p - z^p)
     ³ḍ  Divisibility check by n (if x^p + y^p - z^p is divisible by n then x^p + y^p is congruent to z^p mod n)
Ṗṗ3çƇ    Main Link
Ṗ        Pop (remove last element) - on an integer, implicit range (1 to n-1)
 ṗ3      Cartesian power ^ 3
   çƇ    Filter: keep triples that are valid by the helper link

14 bytes

@cairdcoinheringaahing nice, thanks!

Ruby, 67 66 bytes
->n,p{w=*1...n;w.product(w,w).select{|a,b,c|(a**p+b**p-c**p)%n<1}}

Try it online!
Thanks Chas Brown for -1 byte.

Save a byte with (a**p+b**p-c**p)%n<1

I never knew you could pass multiple arrays to product! Very nice.

Python 2, 94 bytes
n,p=input()
R=range(1,n)
print[(x,y,z)for x in R for y in R for z in R if(x**p+y**p-z**p)%n<1]

Try it online!
Pretty basic.

APL(NARS), chars 129, bytes 258
r←f w;n;p;a;v;i;j;b
(n p)←w⋄a←n∣p*⍨v←⍳n-1⋄r←⍬
:for i :in v⋄:for j :in v
:if a∊⍨b←n∣a[i]+a[j]⋄r←r,⊂i,j,a⍳b⋄:endif
:endfor⋄:endfor

test:
  ⎕fmt f 2 3
┌0─┐
│ 0│
└~─┘
  ⎕fmt f 3 3
┌2────────────────┐
│┌3─────┐ ┌3─────┐│
││ 1 1 2│ │ 2 2 1││
│└~─────┘ └~─────┘2
└∊────────────────┘
  ⎕fmt f 3 4
┌0─┐
│ 0│
└~─┘
  ⎕fmt f 4 3
┌7─────────────────────────────────────────────────────────────┐
│┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐ ┌3─────┐│
││ 1 2 1│ │ 1 3 2│ │ 2 1 1│ │ 2 2 2│ │ 2 3 3│ │ 3 1 2│ │ 3 2 3││
│└~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘ └~─────┘2
└∊─────────────────────────────────────────────────────────────┘

Icon, 95 bytes
procedure f(n,p)
x:=1to(t:=n-1)&y:=1to t&z:=1to t&(x^p+y^p-z^p)%n=0&write(x," ",y," ",z)&\q
end

Try it online!

K (oK), 30 23 bytes
-7 bytes thanks to ngn!
{(~x!-/*/y#)#+1+!3#x-1}

Try it online!

(*/y#)'' -> */y#,

using func#list as "filter": {(~x!-/*/y#)#+1+!3#x-1}

@ngn Filter, of course! Thanks!

Zsh, 90 bytes
l=({1..$[$1-1]}\ )
for x y z (${=${:-$^l$^l$^l}})(((x**$2+y**$2-z**$2)%$1))||<<<"$x $y $z"

Try it online!
Creates the list l=('1 ' '2 ' '3 ' ... '(n-1) ' ), then ${=${:-$^l$^l$^l} gets the Cartesian product and splits on spaces.

Pyth, 17 bytes
AQf!%-F^RHTG^StG3

Try it online!
Displays a list of triplets, each as \$(z, x, y)\$.
AQ                 # Q = eval(input()), G = Q[0] (=n), H = Q[1] (=p)
            ^StG3  # Get the following: range(1, n) ^ 3 -> List of (z,x,y) tuples
  f                # filter that on the following condition: lambda T:
       ^RHT        # map(lambda x: x^H, T)  --> (z^p, x^p, y^p)
     -F            # reduce by subtraction -> z^p - x^p - y^p = z^p - (x^p + y^p)
    %      G       # modulo n  --> (z^p - (x^p + y^p)) mod n
   !               # not (check if == 0) --> z^p == x^p + y^p mod n


text:
Check the validity of a 10-digit telephone number
Your task is to write a program or function that checks if a string is a valid phone number.
Given a string (or list of characters/codepoints) input, you will output a truthy value if the input is a valid phone number. If it is not, output a falsey value. An input string is considered a valid phone number for this challenge if it meets all of these criteria:

It contains ten digits, which are grouped like this: ###-###-####
The strings separating the digit groups must be the same
The first and last characters must be part of the phone number (i.e. must not be part of a separator)

Test cases:
111-222-3333     truthy
123-456-7890     truthy (number groups can contain different numbers)
1112223333       truthy (can have 0 length separators)
111022203333     falsey (has more than 10 numbers)
111ABC222ABC3333 truthy (can have length>1 separators)
111-222_3333     falsey (non-matching separators)
111-22-23333     falsey (missing digit in middle group)
111--222--33333  falsey (extra digit in last group)
-111-222-3333    falsey (first character is not part of number)
111-222-3333a    falsey (last character is not part of number)
aaa-aaa-aaaa     falsey (not enough numbers)
11-2222-3333     falsey (wrong separator location)
111-1-222-1-3333 falsey (too many numbers)

This is a code golf challenge, shortest answer per language wins.

Can we return two consistent values instead of truthy/falsey?

@Adám Such as? I'd be fine with t/f or true/false

How about "  " for true and "" for false?

@Adám I'd be fine with that, if it's the fairest solution in whatever language you are using

I don't know how to judge fairest, but it is quite common here to allow any two values for [tag:decision-problem] challenges. It definitely isn't the normal true and false.

@Adám Makes sense. I'd accept "  " and "", especially since I consider an empty string to be falsey anyway

APL (Dyalog Unicode), 30 29 bytesSBCS
'^\d{3}(\D*)\d{3}\1\d{4}$'⎕S⍬

It simply ⎕Searches for the PCRE regex and returns a dummy value (the empty numeric list) for each match. If none are found, it returns a single empty numeric list.
Try it online! The effect of printing a list of empty lists is to print two spaces on a line, while the effect of printing an empty list is to print an empty line. Select all contents in the Output field to reveal the spaces, or use this to lead each printed line with → and each space with ·.

Jelly, 22 bytes
fØDȯ0ṁ334DR¤jḟØDŒHḢƊµƑ

A monadic Link accepting a list of characters which yields 1 if it is a valid telephone number and 0 otherwise.
Try it online! Or see a test-suite.
How?
fØDȯ0ṁ334DR¤jḟØDŒHḢƊµƑ - Link: list of characters, S  e.g. '123a456bc78de'
                     Ƒ - is S invariant under...
                    µ  - ...this function of S?:
f                      -   filter keep:
 ØD                    -     digit characters              '12345678'
   ȯ0                  -   OR zero (necessary as ṁ will error with an empty list)
           ¤           -   nilad followed by link(s) as a nilad:
      334              -     literal 334                   334
         D             -     to decimal                    [3,3,4]
          R            -     range (vectorises)            [[1,2,3],[1,2,3],[1,2,3,4]]
     ṁ                 -   mould (left) like (right)       ['123','456','7812']
                   Ɗ   -   last three links as a monad  - i.e. f(S):
             ḟ         -     filter discard:
              ØD       -       digit characters           'abcde'
                ŒH     -     split in halves              ['abc', 'de']
                  Ḣ    -     head (zero if empty)         'abc'
            j          -   join                           '123abc456abc7812'
                                                  (...not invariant as not equal to S)

Perl, 36 bytes
print/^\d{3}(\D*)\d{3}\1\d{4}$/?1:0

Run as
perl -ne 'print/^\d{3}(\D*)\d{3}\1\d{4}$/?1:0' <<< "111-222-3333"

Try it online!

29 bytes

05AB1E, 16 bytes
þ©м2äн®T∍ƵêS£sýQ

Port of @JonathanAllan's Jelly answer.
Thanks to @Grimy for fixing a bug.
Try it online or verify all test cases.
Explanation:
þ                 # Only leave the digits of the (implicit) input-string
 ©                # Store it in variable `®` (without popping)
  м               # Remove all digits from the (implicit) input-string
   2ä             # Split the remaining characters into two equal-sized parts
     н            # And only leave the first part
      ®           # Push the digits from variable `®` again
       T∍         # Extend this string of digits to size 10
         Ƶê       # Push compressed integer 334
           S      # Converted to a list of digits: [3,3,4]
            £     # And split the digits of the input into parts of that size
             s    # Swap to get the earlier string
              ý   # And join the digit-parts with this delimiter-string
               Q  # Check if it's now equal to the (implicit) input-string
                  # (after which the result is output implicitly)

See this 05AB1E tip of mine (section How to compress large integers?) to understand why Ƶê is 334.

PHP, 50 bytes
Just a simple regex, with a backreference to make sure the separator is the same.
<?=preg_match('/^\d{3}(\D*)\d{3}\1\d{4}$/',$argn);

Try it online!

I like your RegEx. Do you mind if I use it for an answer, with proper attribution to you?

Heh, I think everyone ended up using the same regex in this challenge :)

Thank you! I went ahead and used it.

JavaScript (ES6), 37 bytes
s=>/^\d{3}(\D*)\d{3}\1\d{4}$/.test(s)

Try it online!

Out of interest, why wouldn't /^\d{3}(\D*)\d{3}\1\d{4}$/.test work as a standalone function?

@cairdcoinheringaahing f=/^\d{3}(\D*)\d{3}\1\d{4}$/.test is only assigning the method test from the RegExp object to f. Something that would work is this.

@cairdcoinheringaahing Or this for 41 bytes, but that's still quite lengthy. Ironically, we can't do //.test.bind(...) because it would be a comment. :p

@Arnauld But isn't that what this is doing? Outputting the output of the test method on a certain input? It seems the exact same as /^\d{3}(\D*)\d{3}\1\d{4}$/.test to me...

@RedwolfPrograms The problem is that the value of this is lost. In other words, you get a reference to the test method without any regular expression attached to it.

@Arnauld Now I feel stupid, just tested it and you're absolutely right

@RedwolfPrograms For it to work, you would need to do (s,r=/^\d{3}(\D*)\d{3}\1\d{4}$/)=>r.test.call(r,s), which is an invalid and longer answer.

Gema, 26 characters
<D3><-d><D3>$2<D4>\Z=t
*=f

There is no truthy / falsey concept in Gema, so just outputting “t” / “f”.
Sample run:
bash-5.0$ echo -n 111-222-3333 | gema '<D3><-d><D3>$2<D4>\Z=t;*=f'
t

Try it online! / Try all test cases online!

Python 3, 69 66 57 bytes
lambda n:re.match(r"\d{3}(\D*)\d{3}\1\d{4}$",n)
import re

Try it online!
Thanks To:
-@Arnauld and @Value Ink for saving me 3 bytes by using match instead of fullmatch
-@Value Ink for saving me another 6 bytes

re.match actually already anchors to the beginning of the string, so you just need the $ and you save 3 bytes. But other than that I agree with @Arnauld

Also since the match object is truthy and None is falsey, I think you can cut !=None entirely since there's no mandate for you to have 2 specific values to distinguish true and false.

@Arnauld you right thank you for the suggestion

@ValueInk I was not sure if None ist falsey and an Object truthy... Thank yoo for pointing that out :)

Ruby -n, 28 bytes
Same as basically every other regex solution here. Note that in Ruby, 0 is actually truthy. (Only false and nil are falsey in Ruby)
p~/^\d{3}(\D*)\d{3}\1\d{4}$/

Try it online!

Huh, 0 is truthy? That must get annoying (especially in code golf)

Sometimes it's a problem, sometimes it it's a benefit. For example, this very program -- the regex check operator string =~ regex returns the index of the first match, or nil if not found, and there's no need to do an explicit check for the "invalid" value because 0 is already truthy :D (In -n mode, ~regex is an alias for $_ =~ regex where $_ is the last read line from STDIN, which is fetched automatically.)

Red, 64 bytes
func[s][d: charset[#"0"-#"9"]parse s[3 d copy t to d 3 d t 4 d]]

Try it online!
As always Red's parse is much longer than regex.

Java (JDK), 43 bytes
s->s.matches("\\d{3}(\\D*)\\d{3}\\1\\d{4}")

Try it online!
Apparently I came to the same solution as others: a simple regex is the key.

QuadS, 28 25 bytesSBCS
^\d{3}(\D*)\d{3}\1\d{4}$

It simply ⎕Searches for the PCRE regex and returns a dummy value (the empty string) for each match. If none are found, it returns a single empty numeric list.
Try it online! The effect of printing a list of empty strings is to print two spaces on a line, while the effect of printing an empty list is to print an empty line. Select all contents in the Output field to reveal the spaces, or use this to lead the printed line with → and each space with ·.

Retina 0.8.2, 24
Same regex as the other regex-based answers:
^\d{3}(\D*)\d{3}\1\d{4}$

Try it online!

Aw, if only I had allowed omitting the trailing line break…

Kotlin (JDK), 60 bytes
{s: String->s.matches(Regex("\\d{3}(\\D*)\\d{3}\\1\\d{4}"))}

Try it online!
Really similar to the Java one

Clojure, 46 bytes
(fn[x](re-matches #"\d{3}(\D*)\d{3}\1\d{4}"x))

Try it online!
Another day, another regex.

SimpleTemplate, 56 bytes
This was actually a very simple challenge, using XMark's RegEx in the PHP answer.
{@ifargv.0 is matches"@^\\d{3}(\\D*)\\d{3}\\1\\d{4}$@"}1

Sadly, due to the need to escape the slashes, this code is 5 bytes longer :/
This code outputs 1 in case the input matches (truthy), or nothing (falsy).
You can try the golfed and ungolfed versions in http://sandbox.onlinephpfunctions.com/code/ca206ad7cc82351283e6c319ce5f9ae03f87b695
You can also check the generated PHP code, if you are curious.


text:
Counting symmetric grid chains
Notation and definitions
Let \$[n] = \{1, 2, ..., n\}\$ denote the set of the first \$n\$ positive integers.
A polygonal chain is a collection of connected line segments.
The corner set of a polygonal chain is a collection of points which are the endpoints of one or more of the line segments of the chain.
Challenge
The goal of this challenge is to write a program that takes two integers, \$n\$ and \$m\$ and computes the number of non-self-intersecting polygonal chains with corner set in \$[n] \times [m]\$ that hit every point in \$[n] \times [m]\$ and are stable under \$180^\circ\$ rotation. You should count these shapes up to the symmetries of the rectangle or square.
Note: In particular, a polygon is considered to be self-intersecting.
Example
For example, for \$n=m=3\$, there are six polygonal chains that hit all nine points in \$[3] \times [3]\$ and are the same after a half-turn:

Table of small values
 n | m | f(n,m)
---+---+-------
 1 | 2 | 1
 1 | 3 | 1
 2 | 1 | 1
 2 | 2 | 1
 2 | 3 | 5
 2 | 4 | 11
 2 | 5 | 23
 3 | 1 | 1
 3 | 2 | 5
 3 | 3 | 6
 3 | 4 | 82

Scoring
This is a code-golf challenge, so shortest code wins.

You say "stable under rotation by 180 degrees", but your 3x3 example seems to be stable on all 90-degree multiple rotations and reflections. Can you clarify, and give us a detailed non-square example?

Do you have any test cases for larger values?

Consider your first example for 3x3; call that A. Now imagine the vertical reflection of that example; call that A'. Why is A' not also shown as one of the possible polygonal chains to be counted? Surely it is exactly as "stable" as A under the action of rotation through 180-degrees; and yet it is not identical to A. Why is it not counted separately?

I misunderstood your earlier comment. This challenge has you count essentially different configurations: “You should count these shapes up to the symmetries of the rectangle or square.”

So you are special casing squares, right?  I mean, the algorithm for a square will be essentially different from that for an oblong rectangle.

I think f(2,2)=2. There's an open chain shaped like an N and a closed chain shaped like a square.

I'd imagine that the reason that the closed-square on a 2*2 is not counted is that it is considered to be "self-intersecting" (albeit only at a node)

@Peter, this is a good question and Jonathan gives the correct answer. This challenge doesn’t count polygons because it considers them self-intersecting.

If a closed chain is self-intersecting then so is every open chain with more than one segment. If you want to count only open chains then I think you have to state it explicitly in the question in those terms.

@PeterTaylor, I don't see it that way, but I'll edit the problem to disambiguate.

@L.F., the way that I've implemented my code doesn't treat the squares as special cases—but it's true that in principle you have to check eight symmetries of the square, but only four symmetries of a rectangle.

@PeterKagey I think OP means "exactly $(nm - 2)$ intersections"

Python 3 + SymPy, 480 455 452 bytes
lambda w,h:len({min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w+~p[0],p[1]),I),(lambda p:(p[0],h+~p[1]),I),(lambda p:p[::-1],I)))for o in permutations(Q(range(w),range(h)))for s in[[*zip(o,o[1:])]]if any(x-~X-w|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))+any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s))<1})
from math import*
from sympy import*
from itertools import*
Q=product
S=Segment
I=tuple

Try it online!
Inlined version of the previous answer below. -3 bytes thanks to Kevin Cruijssen's tip.

Python 3 + SymPy, 480 bytes
from math import*
from sympy import*
from itertools import*
Q=product
S=Segment
I=tuple
def f(w,h):
 a={1}
 for o in permutations(Q(range(w),range(h))):
  s=[*zip(o,o[1:])]
  if any(x+X-w+1|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))+any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s))<1:a.add(min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w-1-p[0],p[1]),I),(lambda p:(p[0],h-1-p[1]),I),(lambda p:p[::-1],I))))
 return~-len(a)

Try it online!
The golfed version takes too long to check the nontrivial answers. The version below has a shortcut in the conditional, so you can check that the results up to (2,4) are correct.
Python 3 + SymPy, 483 bytes
from math import*
from sympy import*
from itertools import*
Q=product
S=Segment
I=tuple
def f(w,h):
 a={1}
 for o in permutations(Q(range(w),range(h))):
  s=[*zip(o,o[1:])]
  if(any(x+X-w+1|y+Y-h+1for(x,y),(X,Y)in zip(o,o[::-1]))or any(gcd(x-X,y-Y)>1for(x,y),(X,Y)in s)+any((len({*u,*v})>3)*intersection(S(*u),S(*v))for u,v in Q(s,s)))<1:a.add(min(I(D(H(V(x)))for x in o)for H,V,D in Q((lambda p:(w-1-p[0],p[1]),I),(lambda p:(p[0],h-1-p[1]),I),(lambda p:p[::-1],I))))
 return~-len(a)

Try it online!
Ungolfed, with comments
from math import*
from sympy import*
from itertools import*
def pass_point(p1,p2): # test if the segment passes through another point
 return gcd(p1[0]-p2[0],p1[1]-p2[1]) > 1
def f(w,h):
 pts = [(i,j) for i in range(w) for j in range(h)]
 ans = set()
 for orders in permutations(pts):
  # test if the ordering has 180 degrees rotational symmetry
  if any(x1+x2!=w-1or y1+y2!=h-1for (x1,y1),(x2,y2) in zip(orders, orders[::-1])):continue
  segments = [*zip(orders, orders[1:])]
  # test if a segment passes through another point or two segments intersect
  if any(pass_point(*p)for p in segments)+any(len({*s1,*s2})==4and intersection(Segment(*s1),Segment(*s2))for s1 in segments for s2 in segments):continue
  # take minimum of 8 possible rotations/reflections
  flipH = lambda p:(w-1-p[0],p[1]); flipV = lambda p:(p[0],h-1-p[1]); flipD = lambda p:p[::-1]; nop = lambda p:p
  flipmin = min(tuple(map(lambda o:d(h(v(o))),orders))for h in (flipH,nop)for v in (flipV,nop) for d in (flipD, nop))
  ans.add(flipmin)
 print(len(ans))

Try it online!
SymPy has Geometry module that includes an intersection checker intersection that works for line segment Segment objects. This is much shorter than rolling a hand-written intersection checker based on coordinates. The intersection of two Segments is either an empty array (if they don't intersect) or an array that contains a single object (either Point or Segment, depending on the input).

In your top and third versions, the w-1-p[0] and h-1-p[1] can be w+~p[0] and h+~p[1], as well as the x+X-w+1|y+Y-h+1for to x-~X-w|y-~Y-h for (or x-~X-w|y+Y-h+1for). (Relevant tip)


text:
Implement the Max-Pooling operation from Convolutional Neural Networks
In convolutional neural networks, one of the main types of layers usually implemented is called the Pooling Layer. Sometimes, the input image is big (and therefore time consuming especially if you have a big input set) or there is sparse data. In these cases, the objective of the Pooling Layers is to reduce the spatial dimension of the input matrix (even though you would be sacrificing some information that could be gathered from it).
A Max-Pooling Layer slides a window of a given size \$k\$ over the input matrix with a given stride \$s\$ and get the max value in the scanned submatrix. An example of a max-pooling operation is shown below:

In the example above, we have an input matrix of dimension 4 x 4, a window of size \$k=2\$ and a stride of \$s=2\$.
Task
Given the stride and the input matrix, output the resulting matrix.
Specs

Both the input matrix and the window will always be square.
The stride and the window size will always be equal, so \$s=k\$.
The stride is the same for the horizontal and the vertical direction
The stride \$s\$ will always be a nonzero natural number that divides the dimension of the input matrix. This guarantees that all values are scanned by the window exactly once.
Input is flexible, read it however you see fit for you.
Standard loopholes are not allowed.

Test Cases
Format:
s , input, output

2, [[2, 9, 3, 8], [0, 1, 5, 5], [5, 7, 2, 6], [8, 8, 3, 6]] --> [[9,8], [8,6]]
1, [[1, 2, 3], [4, 5, 6], [7, 8, 9]] --> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
4, [[12, 20, 30, 0], [8, 12, 2, 0], [34, 70, 37, 4], [112, 100, 25, 12]] --> [[112]]
3, [[0, 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]] --> [[20, 23, 26], [47, 50, 53], [74, 77, 80]]

This is code-golf, so shortest answers in bytes wins!

would have been a more interesting challenge without s==k imho

Can we do my homework next? :P

Python 3, 101 108 bytes
def f(m,w):r=range(0,len(m),w);return[[max(sum([x[i:i+w]for x in m[j:j+w]],[]))for i in r]for j in r]

Thanks to Jo King and Jonathan Allan for some more bytes off!
Try it online!
Alternate (longer) version as a single Lambda expression:
Try it online!

Very nice. -4 bytes - no need for list of unpacked range, also one extra white-space: TIO

You can also put it all one one line for a further -3 bytes

Note: in the lambda version it is better to just use range twice

You could also get to 100 bytes with Python 3.8

Yeah, repeating Range eliminates the internal lambda. Still longer than this solution iirc

Jelly, 6 bytes
»⁹/Z$⁺

A dyadic Link accepting the matrix (list of lists) on the left and the window size on the right which yields a matrix (list of lists).
Try it online!
Or see all windows of a 24*24 grid pooled at each possible granularity
How?
»⁹/Z$⁺ - Link: M, k
    $  - last two links as a monad - i.e. f(X) where X is initially M
  /    -   reduce (X)...
 ⁹     -     ...in chunks of: chain's right argument (k)
»      -     ...by: (left) maximum (right) (this vectorises across the k rows)
   Z   -   transpose the resulting matrix
     ⁺ - repeat the last link - i.e. f(that result)

Octave with Image Package, 38 bytes
@(M,s)blockproc(M,[s s],@(b)max(b(:)))

Try it online!

Didn't know blockproc, very nice:)

J, 15 14 bytes
-1 byte, thanks @Bubbler
The left argument is the matrix and the  right argument is the stride.
>./@,;.3~2 2&$

Try it online!

That's clean J, much better than my contrived solution that uses an inappropriate cutting verb. I started forgetting J even before I have learned it :)

+1 for using the right tool for the job. Btw, you can use ;.3 instead of ;._3 because OP specifies that the stride is always a divisor of the matrix size.

J, 13 12 bytes
>./\&|:^:2~-

Try it online!
... When I said ";.3 is the right tool for the job", I was wrong. This challenge is so simple that an alternative method can get to fewer bytes.
How it works
>./\&|:^:2~-  Left argument: matrix, Right argument: stride (s)
           -  Negate the right argument
       ^:2~   Run the thing twice, with flipped arguments:
              (now the left is -s, right is matrix)
    &|:         Transpose both the matrix and -s
                (transpose on -s is no-op)
>./\            Run "reduce by max" on each of non-overlapping intervals of
                length s, in the primary dimension
              By running this twice, we achieve max pooling in two dimensions

Python 2, 68 bytes
lambda M,k:eval("map(lambda*l:map(max,zip(*[iter(l)]*k)),*"*2+"M))")

Try it online!

74 bytes
lambda M,k:eval("zip(*map(lambda*N:map(max,*N*2),*k*[iter("*2+"M)])))]))")

Try it online!
I can't even ...

APL (Dyalog Unicode), 20 bytes
{⌈⌿⍤2⌈/⍵}⊢⍴⍨4⍴÷⍨∘≢,⊣

Try it online!
I'm pretty sure converting the dfn part into an atop (⌈⌿⍤2⌈/) should work (and save a byte), but there seems to be an anomaly that prevents me from running multiple test cases with that version.
How it works
{⌈⌿⍤2⌈/⍵}⊢⍴⍨4⍴÷⍨∘≢,⊣  left: stride (s), right: matrix
              ÷⍨∘≢    a = size of matrix divided by stride
                  ,⊣  Concatenate a with s
            4⍴        Create a length-4 array (a s a s)
         ⊢⍴⍨          Reshape the matrix into a 4-dimensional array with shape a,s,a,s
{       }             Pass the result into the dfn...
     ⌈/⍵              Take the max through the 4th axis (shape: a,s,a)
 ⌈⌿⍤2                 Take the max through the 2nd axis (shape: a,a)

APL also has an operator called "Stencil" ⌺ that is similar to J's "Subarrays" ;.3, but it has a weird starting location, making it clunky to use for this challenge.

{⌈/↑⍵⊂⍨0=⍺|⍳≢⍉⍵}⍣2 is a bit shorter (⎕io←0)

dzaima/APL, 14 12 bytes
⊣t¨t←⌈/⍬∘⍮⍛⍴

Try it online!

J, 23 bytes
(#@];~@$1{.~[)>./@,;.1]

Try it online!

05AB1E, 8 7 bytes
ôεø¹ôεZ

-1 byte thanks to @Grimy.
Stride as first input and matrix as second input.
Try it online or verify all test cases.
Explanation:
ô        # Split the rows of the (implicit) input-matrix into
         # the (implicit) input-integer amount of groups
         #  i.e. [[12,20,30,0],[8,12,2,0],[34,70,37,4],[112,100,25,12]] and 2
         #   → [[[12,20,30,0],[8,12,2,0]],[[34,70,37,4],[112,100,25,12]]]
 ε       # Map each group of rows to:
  ø      #  Zip/transpose; swapping rows/columns
         #   i.e. [[12,20,30,0],[8,12,2,0]] → [[12,8],[20,12],[30,2],[0,0]]
   ¹ô    #  Split the columns into the input-integer amount of groups as well
         #   i.e. [[12,8],[20,12],[30,2],[0,0]] → [[[12,8],[20,12]],[[30,2],[0,0]]]
     ε   #  Inner map over each block:
      Z  #   And get the flattened maximum of the block
         #    i.e. [[12,8],[20,12]] → 20
         # (after which the result is output implicitly)

I think ø¹ô instead of ¹δôø works.

@Grimmy Ah, you're indeed right. How did I miss that.. Thanks (as always xD)

Wolfram Language (Mathematica), 23 bytes
BlockMap[Max,#2,{#,#}]&

Try it online!

Python 3, 275 196 184 163 159 111 bytes
def f(s,m):r=range(len(m)//s);return[[max(b for k in range(s)for b in m[i*s+k][j*s:][:s])for j in r]for i in r]

Try it online!
Thanks to:
- @randomdude999 for saving me 12 bytes
- @Jitse for saving 48 bytes

You don't need a newline after for k in range(l):, since there's only a single simple statement following it. Same for if l<2:. Also, **0.5 == **.5. Since the input matrix is a square, len(m[0]) == len(m). And i'm pretty sure at least the innermost loop can be done with a list comprehension.

Same approach, 118 bytes: Try it online!

JavaScript (ES6), 85 bytes
Takes input as (s)(matrix).
s=>m=>m.map((r,y)=>r.map((v,x)=>(r=M[Y=y/s|0]=M[Y]||[])[x=x/s|0]>v?0:r[x]=v),M=[])&&M

Try it online!

Charcoal, 24 bytes
ＮθＩＥ⪪ＥＡＥ⪪ιθ⌈λθＥ§ι⁰⌈Ｅι§νμ

Try it online! Link is to verbose version of code. Outputs each maximum on its own line, with matrix rows double-spaced. Explanation:
Ｎθ                          Input the stride
      Ａ                     Input matrix
     Ｅ                      Map over rows
         ι                  Current row
        ⪪ θ                 Split (horizontally) into windows
       Ｅ                    Map over windows
            λ               Current window
           ⌈                Take the maximum
    ⪪        θ              Split vertically into windows
   Ｅ                        Map over windows
              Ｅ§ι⁰          Map over horizontal maxima
                   Ｅι       Map over windowed rows
                     §νμ    Get windowed cell
                  ⌈         Take the maximum
  Ｉ                         Cast to string for implicit print

Ｅ§ι⁰Ｅι§νμ is effectively the nearest Charcoal has to a transpose operation, although obviously I can at least take the maximum of the transposed column in situ.

Stax, 11 bytes
ó╚←XF«≡ûÖçx

Run and debug it at staxlang.xyz!
Unpacked (13 bytes) and explanation
X/{Mx/{:f|Mmm
X                Save window size to register X
 /               Take groups of X rows
  {         m    Map block over groups:
   M               Transpose (gets list of column segments)
    x/             Take groups of X column segments (our windows)
      {    m       Map block over windows:
       :f|M          Flatten and take maximum

Leaves the result on the stack, since arrays print as strings. That makes the output hard to determine. Here's a pretty version.

Ruby, 57 bytes
->m,w{g=->r{r.transpose.each_slice(w).map &:max};g[g[m]]}

Try it online!

Japt, 24 bytes
mòY=UÊzV)Õc òYp)®rwÃòV y

Try it
U.m("ò", // split each row by..
 Y = U.l().z(V)) // input size / s
.y() // transpose
.c() // flatten
.ò(Y.p()) // split in Y*Y chunks
.m(function(Z) { return Z.r("w") }) // max of each
.ò(V) // rematrix
.y() // retranspose