text:
Nobody knows GAU Numbers
Let me introduce you to GAU numbers
GAU(1) = 1
GAU(2) = 1122
GAU(3) = 1122122333
GAU(4) = 11221223331223334444
GAU(6) = 11221223331223334444122333444455555122333444455555666666
...
GAU(10) = 11221223331223334444122333444455555122333444455555666666122333444455555666666777777712233344445555566666677777778888888812233344445555566666677777778888888899999999912233344445555566666677777778888888899999999910101010101010101010

This challenge is pretty simple!
Given an integer n>0, find the number of digits of GAU(n)
Example
Let's make GAU(4)
we take the following steps (until we get to 4) and concatenate them
[1][122][122333][1223334444]

you must write every number as many times as its value, but you have to count every time from 1
Let's try to make GAU(5)
we will have to count from 1 to 1
[1]

then from 1 to 2 (but repeating every number as many times as its value)
[122]

then from 1 to 3
[122333]

then from 1 to 4
[1223334444]

and finally from 1 to 5 (this is the last step because we want to find GAU(5))
[122333444455555]

Now we take all these steps and concatenate them
the result is GAU(5)
11221223331223334444122333444455555

We are interested in the number of digits of these GAU numbers.
Test cases
Input⟼Output
n   ⟼ Length(GAU(n))

1   ⟼ 1
2   ⟼ 4
3   ⟼ 10
10  ⟼ 230
50  ⟼ 42190
100 ⟼ 339240
150 ⟼ 1295790

This is a code-golf challenge.
Shortest code in bytes will win.
If you still have any questions please let me know.
I really want everyone here to understand this magic-hidden-complex pattern

What does GAU stand for?

G is for GAU, A and U are just there for no reason

Up until n=9, the lengths are tetrahedral numbers, but beyond that the multi-digit numbers get in the way of a simple closed form

FYI your test case says n   ⟼ Length(GUA(n)), not GAU(n).

@numbermaniac this was an edit by Sanchises. Just above the test cases I state with bold letters "We are interested in the number of digits of these GAU numbers".

@Jose I know, I was just saying GAU is spelt as GUA :)

@numbermaniac thanks for spotting this. GUA numbers are totally different. They haven't been invented yet!

SOGL V0.12, 11 10 8 7 5 bytes
∫∫l*+

Try it Here! - this expects to be called as a function with the input on the stack and the input box empty.
7 byte alternative taking the input from the input box:
0.∫∫l*+

Try it Here!
0      push 0
 .     push the input
  ∫    iterate over a range 1..POP (input) inclusive, pusing the current number
   ∫    iterate over 1..POP (above loops number) inclusive, pusing the current number
    l    push that numbers length without popping the number
     *   multiply the length by the number
      +  add to the zero, or whatever it is now

push that numbers length without popping the number nice

Haskell, 45 bytes
f n=sum[j*length(show j)|i<-[1..n],j<-[1..i]]

Try it online!

A bit more unreadable but one byte cheaper: TIO

Brain-Flak, 166 bytes
<>(((()()())({}){})())<>{({}[()]<({}({}<<>({}[()])((){[()](<()>)}{}){{}((((({})({})){}{}){}))<>(({}<({}())>){()<({}[({})])>}{})(<>)}{}<>>({}({})())))>)}{}({}<{}{}{}>)

Try it online!
Explanation
<>(((()()())({}){})())<>           # Initialize second stack with 9 and 10
{({}[()]<                          # Do main loop n times:
  ({}
    ({}
      <
        <>({}[()])                 # Subtract 1 from counter to next power of 10
        ((){[()](<()>)}{}){        # If reached a power of 10 (say, 10^k):
          {}((((({})({})){}{}){})) # Multiply existing (10^k*0.9) by 10 and push twice
          <>                       # On first stack
          (
            ({}<({}())>)           # Increment length of numbers
            {()<({}[({})])>}{}     # Divide length of new set of numbers by this length
          )                        # Add together to get new set of numbers length
        (<>)}
      {}<>>
      ({}({})())                   # Add number length to number set length
    )                              # Add number set length to new segment length
  )                                # Add new segment length to total length
>)}                                # End main loop
{}({}<{}{}{}>)                     # Put result on stack by itself

Husk, 5 bytes
ṁLΣQḣ

Try it online!
Explanation
ṁ  map over
 L  length
  Σ  sum list
   Q  all sublists
    ḣ  range 1 .. N

Nice algorithm!

Jelly, 7 bytes
Rx`ƤDFL

Try it online!

05AB1E, 5 bytes
LŒJJg

Try it online!
Explanation
L      # push [1 .. a]
 Œ     # all substrings (a)
  J    # numbers to strings (inner)
   J   # numbers to strings (outer)
    g  # length

Welcome to the site :)

Python 2, 53 bytes
lambda x:sum(len(`i`)*i*(x-i+1)for i in range(1,x+1))

Try it online!

51 bytes.

Husk, 7 bytes
ṁLṁṘNḣḣ

Try it online!
Explanation
          Implicit input, e.g 4
      ḣ   Range from 1 to n                               [1,2,3,4]
     ḣ    Prefixes                                        [[],[1],[1,2],[1,2,3],[1,2,3,4]]
  ṁ       Map and then concatenate
   ṘN     Repeat each number in each list by its index    [[],[1],[1,2,2],[1,2,2,3,3,3],[1,2,2,3,3,3,4,4,4,4]]
                                                          [1,1,2,2,1,2,2,3,3,3,1,2,2,3,3,3,4,4,4,4]
ṁ         Map and then sum
 L        Length (of number: 10 -> 2)                     26

Oh another Husk solution :) Didn't see your submission when posting mine, same bytecount but they're sufficiently different, so I'll leave mine here too.

Husk, 7 bytes
Σ∫mS*Lḣ

Try it online!
Ungolfed/Explanation
         -- implicit input N                        | 10
  m   ḣ  -- map the following function over [1..N]  | [1,2,3,4]
   S*L   --   multiply length of number by itself   | [1,2,3,4] (only important for numbers ≥ 10)
 ∫       -- prefix sums                             | [0,1,3,6,10]
Σ        -- sum                                     | 20

Python 2, 59 58 bytes
Another one bytes the dust thanks to Jonathan Frech.
f=lambda n:n and sum(i*len(`i`)for i in range(n+1))+f(n-1)

Try it online!
Not short but eh... what the heck.

len(\i`)i for->ilen(`i`)for`.

53 bytes, non-recursive.

JavaScript (ES6), 57 55 bytes
n=>[...Array(n)].reduce(x=>x+(++y+"").length*y*n--,y=0)

Try it online!

CJam, 20 bytes
q~),(\{),{_s,*+}*+}%

Try it online!
The number is passed in the "input" field.
Ungolfed explanation: (example input = 2)
q~),(\{),{_s,*+}*+}%                                             | Stack:
q                     read input as string                       | "2"
 ~                    eval input (add it to stack as integer)    | 2
  )                   add 1                                      | 3
   ,                  range (convert to array with values 0...N) | [0, 1, 2]
    (                 pop first item of array                    | [1, 2] 0
     \                swap top two values of stack               | 0 [1, 2]
      {           }   for each item in array...                  | 0 1
       )              add 1                                      | 0 2
        ,             range (convert to array with values 0...N) | 0 [0, 1]
         {     }      for every element in the array...          | 0 0
          _           duplicate                                  | 0 0 0
           s          convert to string                          | 0 0 "0"
            ,         get length of string                       | 0 0 1
             *        multiply                                   | 0 0
              +       add                                        | 0 1
                *     fold                                       | 0 1
                 +    add                                        | 1
                   %  repeat                                     | 4

It seems hard when explained lol.

R, 39 bytes
function(n)sum(nchar(rep(1:n,n:1*1:n)))

Verify all test cases!
Simple algorithm; I observed, as most did, that for i in 1:n, i is repeated i*(n-i+1) times. So I create that vector, count the number of characters in each, and sum them.

JavaScript (ES6), 50 42 bytes
Updated: now basically a port of what other answers are doing.
f=(n,i=1)=>n&&`${n}`.length*n*i+f(n-1,i+1)

Test cases

f=(n,i=1)=>n&&`${n}`.length*n*i+f(n-1,i+1)

console.log(f(1))   // 1
console.log(f(2))   // 4
console.log(f(3))   // 10
console.log(f(10))  // 230
console.log(f(50))  // 42190
console.log(f(100)) // 339240
console.log(f(150)) // 1295790

Perl 6, 36 bytes
{[+] 1..*Z*($_...1).map:{.chars*$_}}

Test it
Expanded:
{  # bare block lambda with implicit parameter ｢$_｣

  [+]               # reduce the following using &infix:«+»

    1 .. *          # Range from 1 to infinity

    Z*              # zip using &infix:«*»

    ( $_ ... 1 )    # sequence from the input down to 1
    .map:           # for each one
    { .chars * $_ } # multiply the number of digits with itself
}

J, 24 bytes
[:+/[:+/\[:(*#@":"0)1+i.

Similar high-level approach to dzaima's APL answer, translated into J, except we calculate the number's length by turning it into a string first instead of taking logs, and we get to use J's hook to multiply that length by the number itself: (*#@":"0).  After that it's just the sum of the scan sum.
Try it online!

1(#.]*#\*#\.)1#@":@+i. also works for 22 bytes

@miles That's clever -- it took me a bit to figure it out.  How long have been programming in J for?

A bit after I joined code-golf. I don't actually use it to write any real programs as no I know would be able to read it, but I do use it as an advanced desktop calculator now, and usually always have a window open to calculate something.

Röda, 31 bytes
{f={seq 1,_}f|f|[#`$_`*_1]|sum}

Try it online!

Python 2, 51 50 bytes
lambda n:sum(~k*(k-n)*len(`k+1`)for k in range(n))

@LeakyNun Why? I developed this answer myself. I didn't even check the other answers.

This doesn't even output the right answer, gives 0 for n=1, 3 for n=2 and 14 for n=3

@HalvardHummel Oops, messed up a sign and forgot a +1. Fixed now.

I see that you finally understood the patern! Is there a way to test your code online or the other Python 2 answer covers this, too?

[Dyalog APL], 22 20 bytes
{+/≢¨⍕¨↑,/(/⍨¨⍳¨⍳⍵)}

Try it online!
Explanation:
{+/≢¨⍕¨↑,/(/⍨¨⍳¨⍳⍵)}
{                  } anonymous function with right argument named ⍵
                ⍳⍵   range 1 to right arg
              ⍳¨     for each, range 1 to it
             ¨       for each
           /⍨          for each item, repeat right arg left arg times
          (       )  take that and
        ,/           join the sub-arrays together
       ↑             convert from a nested array to a simple array (or something like that, I don't quite understand it :p)
     ⍕¨              convert each number to a char-array (aka string version)
   ≢¨                get length of each
 +/                  sum that together

Mathematica, 66 bytes
Tr[1^(f=Flatten)[IntegerDigits/@f@(a=Array)[a[#~Table~#&,#]&,#]]]&

Japt, 12 11 10 9 bytes
õõÈ*sÊÃxx

Try it or test all numbers from 1 to 150.

Explanation
Implicit input of integer U.
õõ

Generate an array of integers from 1 to U and then generate sub-arrays from 1 to each integer.
È   Ã

Pass the elements of each sub-array through a function.
*sÊ

Convert the current element to a string (s), get it's length (Ê) and multiply it by the element.
xx

Reduce the main array by addition after first doing the same to each sub-array.

Excel VBA, 66 51 50 Bytes
Anonymous VBE immediate window function that takes input from the range [A1] and outputs to the VBE
For i=1To[A1]:For j=1To i:s=s+j*Len(j):Next j,i:?s

Alternate Version, 94 Bytes
Anonymous VBE immediate window function that takes input,n, from range [A1] constructs the GUA(n) and outputs the length of it to the VBE immediate window
[B1].Resize([A1],1)="=IfError(Offset(B1,-1,0)&Rept(Row(),Row()),1)":?[Len(TextJoin("",1,B:B))]

QBIC, 21 bytes
[:|[a|[c|A=A+!c$}?_lA

Charcoal, 18 14 bytes
ＩΣＥ⊕ＮΣＥ⊕ι×λＬＩλ

Try it online! Link is to verbose version of code. Edit: Using Sum saved me 4 bytes. Explanation:
  Ｅ⊕Ｎ           Map from 0 to the input (loop variable i)
      Ｅ⊕ι       Map from 0 to i (loop variable l)
            Ｉλ  Cast l to string
           Ｌ    Take the length
         ×λ     Multiply by l
     Σ          Sum the results
 Σ              Sum the results
Ｉ               Cast to string
                Implicitly print

:| Sum sums numbers in the strings when given string arguments

@ASCII-only It wasn't that, it was just printing a Σ instead...

@ASCII-only Also, best I can do with Sum is still 18 bytes: Print(Cast(Sum(Map(InclusiveRange(1, InputNumber()), Sum(Map(InclusiveRange(1, i), Times(l, Length(Cast(l)))))))));

wait you keep forgetting Incremented :P

@ASCII-only I tried sum of product but that was 17 bytes: ≔⊕ＮθＩΣＥθ×⁻θι×ιＬＩι. However, using Incremented instead of InclusiveRange shaves 4 bytes off my previous comment!

MATL, 15 bytes
:ttP*Y"10&YlQks

Try it online!
Explanation:
:                range 1:input (implicit input)
 tt              duplicate twice
   P             reverse
    *            multiply elementwise
     Y"          runlength decoding
       10&Yl     log10
            Qk   increment and floor
              s  sum (implicit output)

That logarithm is expensive :-) You can replace it by converting to string, removing spaces, length: :ttP*Y"VXzn

Bash, 48, 44 bytes
Saved 4 bytes thanks to for + curly braces trick
for((;r+=t+=n*${#n},++n<=$1;));{ :;};echo $r

Actually, 13 bytes
R♂R♂i⌠;n⌡Mεjl

Try it online!
Explanation:
R♂R♂i⌠;n⌡Mεjl
R              range(1, n+1)
 ♂R            range(1, x+1) for x in previous
   ♂i          flatten into 1D list
     ⌠;n⌡M     for x in list:
      ;n       repeat x x times
          εj   concatenate to string
            l  length

Jq 1.5, 82 49 43 bytes
[range(.)+1|range(.)+1|"\(.)"*.|length]|add

Expanded
[   range(.)+1        # for i=1 to N
  | range(.)+1        # for j=1 to i
  | "\(.)"*.          # "j" copied j times
  | length            # convert to length
] | add               # add lengths

Sample Run
$ jq -Mr '[range(.)+1|range(.)+1|"\(.)"*.|length]|add' <<< "150"
1295790

Try it online! also jqplay.org

C# (.NET Core), 94 80 74 bytes
n=>{int b=0,a=0,i;while(a++<n)for(i=0;i++<a;)b+=(i+"").Length*i;return b;}

Try it online!
I was hoping to find a direct solution like what @kamoroso94's answer started, but gave up as I was spending too much time on it. There probably is a way of doing it, but the formula needs to adjust for every magnitude step.
Acknowledgements
14 bytes saved thanks to @someone
6 bytes saved thanks to @Kevin Cruijssen

n=>{int b=0,a=0,i;for(;a++<n;)for(i=0;i++<a;)b+=i.ToString().Length*i;return b;} Try it online! for 80 bytes and performance.

i.ToString() can be (i+"") to save some more bytes.

Ruby, 73 bytes
f=->(t){(1..t).map{|n|(1..n).map{|n|Array.new(n,n)}}.flatten.join.length}

Stacked, 28 bytes
[~>[~>[:rep]"!]"!flat''#`#']

Try it online!
Some might ask, "At which point are aliases unreadable?" If this isn't close, you have a very liberal definition of "readability".
Explanation
[~>[~>[:rep]"!]"!flat''#`#']    input: N
 ~>[          ]"!               for each number K from 1 to N
    ~>[    ]"!                  for each number J from 1 to K
       :rep                     repeat J J times
                 flat           flatten the resultant array
                     ''#`       join by the empty string
                         #'     get the length of said string

Ruby, 41 40 bytes
->n{(1..n).map{|x|[x]*x*=-x-~n}*''=~/$/}

Try it online!

Ohm v2, 7 bytes
@@D×JJl

Try it online!

Thunno 2 JL, 3 bytes
RJF

Try it online!
Or, 5 bytes flagless: RJFJl
Explanation
RJFJl  # Implicit input
R      # Range [1..input]
 J     # Join into a string
  F    # All substrings
   J   # Join into a string
    l  # Length of the string
       # Implicit output

Python 3, 47 bytes
f=lambda x,i=1:x and x*i*len(str(x))+f(x-1,i+1)

Try it online!

inb4 44 bytes on Python 2

Mathematica, 34 bytes
Sum[i⌊1+Log10@i⌋,{j,#},{i,j}]&

this is not what the question is asking...

fails for n=100.Please read more carefully, check the test cases and give a final answer

@JoseZaman my bad, sir. It's all good now.

Perl 5, 33 + 1 (-p) = 34 bytes
map{map$\+=$_*y///c,1..$_}1..$_}{

Try it online!

maybe can avoid outer loop $\+=$x+=$_*y///c

05AB1E, 6 bytes
LLD×Jg

Try it online!
Explanation
L        # range [1 ... input]
 L       # for each range [1 ... x]
  D      # duplicate
   ×     # repeat each in the first list a number of times determined by the second list
    J    # join to string
     g   # length

Kotlin, 36 bytes
{x:Int->(1..x).flatMap{1..it}.sum()}

Test:
val GAU = {x:Int->(1..x).flatMap{1..it}.sum()}
GAU(5)
=> 35

GAU(10)=220 does not equal 230 :)

RProgN 2, 12 bytes
{{]Ø.*}S.}S.

Try it online!

Java 8, 76 bytes
n->{int r=0,i=0,j;for(;i++<n;)for(j=0;j++<i;r+=(j+"").length()*j);return r;}

I have the feeling this can be golfed with a more arithmetic approach, instead of using String#length..
Explanation:
Try it here.
n->{                        // Method with integer as both parameter and return-type
  int r=0,                  //  Result-integer
      i=0,j;                //  Index integers
  for(;i++<n;)              //  Loop (1) from 0 to the input (exclusive)
    for(j=0;                //   Reset `j` to 0
        j++<i;              //   Inner loop (2) from 0 to `i` (exlusive)
      r+=                   //    Append the result-String with:
         (j+"").length()*j  //     The length of `j` multiplied by `j`
    );                      //   End of inner loop (2)
                            //  End of inner loop (1) (implicit / single-line body)
  return r;                 //  Return result-String
}                           // End of method

Scala, 44 bytes
(1 to n).map(i=>(i+"").length*i*(n+1-i)).sum

Try it online!

Jelly, 7 bytes
RRx`€VV

Try it online!
Explanation:
RRx`€VV    Example input: 3
R          Range. Result: [1, 2, 3]
 R         Range (vectorizes). Result: [[1], [1, 2], [1, 2, 3]]
    €      Apply to €ach...
  x`       Repeat each number itself times. Result: [[[1]], [[1], [2, 2]], [[1], [2, 2], [3, 3, 3]]]
     VV    Concatenate them into one big friendly number. Result: 1122122333

Powershell, 93 bytes
$a=@();$b=@();1..$n|% $_{$i=0;Do{$a+=$_;$i++}while($i-ne$_);$b+=$a-join''};($b-join'').Length

Code exploded a bit:
$inputNum = 10
$numbers = 1..$inputNum
$array = @()
$bigArray = @()
Foreach ($number in $numbers){
    $i = 0
    Do {
        $array += $number
        $i++
    }
    while ($i -ne $number)
    $bigArray += $array -join ''
}
($bigArray -join '').Length

PocoLithp, 111 bytes
(define gau(#(N I)(if(!(defined I))(gau N 1)(if(!= N 0)(+(*(*(length(expl(str N)))N)I)(gau(- N 1)(+ I 1)))N))))

More readable version:
(define gau (# (N I) (begin
        (if (! (defined I))      ;; I not supplied, recurse with I set to 1
                (gau N 1)
                (begin           ;; I supplied, calculate
                        (define A (length (expl (str N))))  ;; `N`.length
                        (if (!= N 0)
                            ;; N != 0, head recursive calculation
                            (+ (* (* A N) I) (gau (- N 1) (+ I 1)))
                            ;; N == 0, return it
                             N)
                )
        )
)))

Usage:
(gau 123) => 662505
(gau 256) => 7532088

Named function gau, which takes 1 or 2 parameters. If called with 1 parameter, calls self with 2nd parameter set to 1. This implements the default variables used in other implementations.
This could possibly be made tail recursive, but it would likely be even longer than it already is.

Retina, 29 bytes
.+
$*
1
1$`¶
1
1$%`¶
1
$.%_
.

Try it online!
Explanation
.+
$*

Convert input to unary.
1
1$`¶

Turn the input N into a range from 1 to N by inserting the prefix up to each 1 after it, together with a linefeed.
1
1$%`¶

Do the same thing to each value in that range. This time we use $%`, which is just the prefix on the current line. So this gives 1, 1,2, 1,2,3, 1,2,3,4, ... (in unary). Now all we need to do is repeat each value accordingly and converting to decimal.
1
$.%_

This is done by replacing each 1 with the length of the line its on.
.

Finally we count the number of digits.

J-uby, 32 bytes
:+|:*&(:+|:*&~:*%-[I])|:join|:+@

Attempt This Online!
Explanation
:+ | :* & (:+ | :* & ~:* % -[I]) | :join | :+@

:+ | :* & (                    )                # Range, then map with...
           :+ | :* &                            #   Range, then map with...
                     ~:* % -[I]                 #     [n] * n
                                 | :join | :+@  # Then join all elements and get length


text:
Use an editor to write "Hello, World"
Objective
Use any editor or IDE (vim, emacs, IntelliJ, etc) to write a valid "Hello, World" program in any C-like language. The "!" is optional, but you get style points if you use it. You may use publicly available plugins, a publicly available vimrc, etc, but you may not write or make modifications to them specifically for this challenge.
Winning
Fewest key presses and mouse clicks and touchscreen taps :P wins (only counted when the key is pressed down).
Submission:
A valid submission requires the number of key presses, the editor used, the language used, a list of the keystrokes pressed, and the important parts of any vimrc, a list of plugins, or anything else required to replicate your result.

No exclamation mark!?

@JonathanAllan See edits.

@BruceForte See the other edit.

I am voting to close this as too broad, since the user can choose the operating system, the editor, the plugins on the editor, and many other variables. This also doesn't account for the amount of time it takes to activate plugins, or what's in the clipboard.

Even though it would be a fairly obvious loophole it is probably worth explicitly banning all other input methods.

1 mouse click on any of the c like languages supported by TIO

Vim with Ultisnips in C (gcc), 30 keystrokes
imaTabTabputs("Hello, World!");Esc:x
Explanation
To use the above you'll need the mentioned Plugin installed and g:UltiSnipsExpandTrigger and g:UltiSnipsJumpForwardTrigger bound to Tab, further you'll need this snippet in your g:UltiSnipsDir. This also makes the assumption that you opened a file which sets filetype=c:

ima: Change to Insert mode and enter ma
TabTab: Select and expand the main <snip>
puts("Hello, World!");: Insert the remaining characters
Esc: Change to Normal mode
:x: Write the file and exit

The resulting file looks like this:
int main(int argc, char *argv[])
{
  puts("Hello, World!");
  return 0;
}

Note: I couldn't just now find a complete vimrc but here's a StackOverflow post that mentions the relevant parts.

Notepad++, 17 keystrokes, R
cat("Hello, World")

19 keystrokes with !
cat("Hello, World!

Text editors like Sublime Text or notepad++ automatically add a closing ) and ", so in those the keystrokes boil down to cat("Hello, World.

WebStorm in ECMAScript, 16 keystrokes
alEnter"Hello, World

Are you sure this actually prints "Hello, World" when run?

@Okx Accidentally used Tab instead of Enter.

source: Stack Exchange

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

sort: votes


text:
Distinct Reversible Primitive Binary Necklaces
Introduction - What is a necklace?
A necklace is something that OEIS people are obsessed with. The OEIS challenge has like 5 necklace sequences.
A binary necklace of length n is a loop with n beads that are either 0 or 1. Two necklaces are the same if one can be rotated to become the other, and two reversible necklaces are the same if one can be rotated, reversed, or reversed and rotated to become the other.
A primitive necklace is one that cannot be expressed as more than one copy of a string of beads chained together. Note that the copies must be assembled all in the same order (no reversing) for a necklace to be considered non-primitive.
For example, let's take a look at this necklace: 0 1 1 0 1 1. It is not primitive because it can be expressed as 0 1 1 repeated twice. 0 1 0 1 1 is primitive.
0 1 1 0 is primitive because 0 1 and 1 0 are not considered the same string. This necklace is equivalent to 1 1 0 0 because it can be rotated left one bead to become this one, but not equivalent to 0 1 0 1 (which isn't primitive by the way).
Challenge
Given an non-negative integer n, return the number of distinct reversible primitive binary necklaces of length n. Input and output as a single integer each.
The first few terms of this sequence are 1, 2, 1, 2, 3, 6, 8, 16, 24, 42, 69, 124, 208, 378, 668, 1214, 2220, 4110, 0-indexed.
This is OEIS A001371
Reference Implementation in Python 3 - quite slow

Oh, I get it—"primitive" means it can't be partially rotated to get the original necklace, right?

@ETHproductions ... I never thought of it that way. Yes, that is definitely a correct understanding. Nice!

Why is 0 1 0 1 primitive? Isn't it 0 1 repeated twice?

@MishaLavrov Thanks; I meant "not primitive" whoops. Thanks

ಠ_ಠ I was looking for an OEIS sequence to post as a challenge and the next thing I see is... this... necklaces. ._.

@icrieverytim see I had to suffer the first necklace question with unknown terms that almost killed the challenge, so time for revenge mwahahaha

Trying to do this manually for n = 7 before I try to code it, and coming up two short. A string of all 0's or all 1's is not primitive right? That said, I do get 16 if I count those strings that cannot be reversed to get themselves.

@Tahg The sixteen I get are: 0000001, 0000011, 0000101, 0000111, 0001001, 0001011, 0001111, 0010011, 0010101, 0010111, 0011011, 0011111, 0101011, 0101111, 0110111, 0111111

@HyperNeutrino, what's your definition of "almost killed the challenge"? By my criteria you've saved the chain two times but they had nothing to do with necklaces.

@PeterTaylor I guess "killed the challenge" wouldn't be the right way to word it; something like the first one that involved weird math that needed Math.SE to complete (but even then I'm not sure it was the first lol... hm)

Ok, it seems like I was just confused on the definition of a reversible primitive.  I had in mind a number that, when reversed, could be rotated to be itself, but rereading the question doesn't seem to imply that at all.  In the case of n = 7, 14/16 had this property of symmetry, though I couldn't find an OEIS that matched that.

Python 2, 178 171 139 137 bytes
lambda n:sum(1-any(i>int(b[j::-1]+b[:j:-1],2)or j*(i>=int(b[j:]+b[:j],2))for j in range(n))for i in range(2**n)for b in[bin(i+2**n)[3:]])

Try it online! Edit: Saved 7 21 bytes thanks to @HalvardHummel.

157 bytes

@HalvardHummel Thanks, I couldn't work out how to generate all the permutations in a 1-liner.

JavaScript (ES6), 198 192 bytes
I was curious to know what a fully mathematical answer would look like. So here it is. Quite long but very fast.
n=>(g=d=>d&&(n%d?0:(q=n/d,C=(a,b)=>b?C(b,a%b):a<2,M=n=>n%++k?k>n?(q%2+3)/4*(1<<q/2)+(R=d=>d&&(q%d?0:(P=k=>k--&&C(q/d,k)+P(k))(q/d)<<d)+R(d-1))(q)/q/2:M(n):n/k%k&&-M(n/k))(d,k=1))+g(d-1))(n)||1

Demo

let f =

n=>(g=d=>d&&(n%d?0:(q=n/d,C=(a,b)=>b?C(b,a%b):a<2,M=n=>n%++k?k>n?(q%2+3)/4*(1<<q/2)+(R=d=>d&&(q%d?0:(P=k=>k--&&C(q/d,k)+P(k))(q/d)<<d)+R(d-1))(q)/q/2:M(n):n/k%k&&-M(n/k))(d,k=1))+g(d-1))(n)||1

for(n = 0; n <= 30; n++) {
  console.log('a(' + n + ') = ' + f(n))
}

How?
This is based on the following formulas:
A000029(n) =
  (n % 2 + 3) / 4 * 2 ** floor(n / 2) +
  sum(φ(n / d) * 2 ** d, for d in divisors(n)) / (2 * n)

A001371(n) =
  1 if n = 0
  sum(μ(d) * A000029(n / d), for d in divisors(n)) if n > 0

Where φ is Euler's totient function and μ is Möbius function.
n => (g = d =>
  // if d = 0, stop the recursion of g()
  d && (
    // if d is not a divisor of n, ignore this iteration
    n % d ? 0 :
    (
      // define q = n / d, C = function that tests whether a and b are coprime,
      // M = Möbius function (requires k to be initialized to 1)
      q = n / d,
      C = (a, b) => b ? C(b, a % b) : a < 2,
      M = n => n % ++k ? k > n || M(n) : n / k % k && -M(n / k)
    )(d, k = 1) * ( // invoke M with d
      // first part of the formula for A000029
      (q % 2 + 3) / 4 * (1 << q / 2) +
      // 2nd part of the formula for A000029
      (R = d =>
        // if d = 0, stop the recursion of R()
        d && (
          // if d is not a divisor of q, ignore this iteration
          q % d ? 0 :
          // compute phi(q / d) * 2 ** d
          (P = k => k-- && C(Q, k) + P(k))(Q = q / d) << d
        // recursive call to R()
        ) + R(d - 1)
      )(q) / q / 2 // invoke R with q, and divide the result by q * 2
    )
  // recursive call to g()
  ) + g(d - 1)
)(n) || 1

NB: In the current golfed version, the 2nd part of the code is now directly embedded inside M(). But that makes the code harder to read.

Mathematica, 128 125 124 109 99 bytes
1~Max~(L=Length)@(U=Union)[U[#,Reverse/@#]&/@MaximalBy[U@Partition[#,L@#,1,1]&/@{0,1}~Tuples~#,L]]&

How it works

{0,1}~Tuples~# finds all binary sequences of the given length
U@Partition[#,L@#,1,1]&/@... finds all possible rotations of each one of them
MaximalBy[...,L] picks out the entries with the most distinct rotations; these correspond to the primitive necklaces.
U[#,Reverse/@#]&/@... puts the rotations in each entry, and their reversals, into a canonical order...
(L=Length)@(U=Union)[...] ...so that we can delete duplicate primitive necklaces, and then count the elements remaining.
1~Max~... we make sure the result is at least 1 to get the zeroth term right.

-2 bytes thanks to Jonathan Frech, and -2 thanks to me learning from him
-15 more bytes from switching to MaximalBy and related changes
-10 from switching to Partition

I think if you replace Length with L and define L=Length;, you could save a byte.

126 bytes.

125, since I forgot to golf one of the instances of Length. Thanks!

And now it's 124, since I have learned from your example and turned another ==1 into a <2.

Husk, 21 bytes
Ṡ#▲mLüOmȯṁSe↔U¡ṙ1ΠRḋ2

Try it online!
The link shows results from 0 to 10.
Explanation
Ṡ#▲mLüOmȯṁSe↔U¡ṙ1ΠRḋ2  Implicit input, say n=4.
                  Rḋ2  The list [1,0] repeated n times: [[1,0],[1,0],[1,0],[1,0]]
                 Π     Cartesian product: [[1,1,1,1],[0,1,1,1],[1,0,1,1],...,[0,0,0,0]]
       mȯ              For each list, say x=[0,1,0,0]:
              ¡ṙ1        Iterate rotation by one step: [[0,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,0],[0,1,0,0],...
             U           Take prefix of unique values: [[0,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,0]]
         ṁSe↔            After each element, insert its reversal: [[0,1,0,0],[0,0,1,0],[1,0,0,0],[0,0,0,1],[0,0,0,1],[1,0,0,0],[0,0,1,0],[0,1,0,0]]
     üO                Remove duplicates with respect to sorting.
   mL                  Get length of each list of lists.
Ṡ#▲                    Count the number of maximal lengths.

Jelly, 25 bytes
2ḶṗµṙJ;U$ṢḢµ€QµsJṖE€ẸṆµ€S

Try it online!
Very inefficient.

Javascript (ES7), 180 bytes
n=>[...Array(2**n)].filter((_,m)=>![...m=m.toString(2).padStart(n,0)].some(_=>s[m=m.replace(/(.)(.*)/,"$2$1")]|s[[...m].reverse().join``])&!/^(.+)\1+$/.test(m)&(s[m]=1),s=[]).length

Explanation:
n=>[...Array(2**n)].filter((_,m)=>(     // For every number m from 0 to 2^n-1
    m=m.toString(2).padStart(n,0),      // Take the binary representation (padded)

    ![...m].some(_=>(                   // Repeat once for every digit in m
        m=m.replace(/(.)(.*)/,"$2$1"),  // Rotate m one step
        s[m]|s[[...m].reverse().join``] // Search for m and the reverse of m in the
    ))                                  // lookup table

    &!/^(.+)\1+$/.test(m)               // Test if m is primitive
    &(s[m]=1)                           // Add m to the lookup table

),s=[]).length                          // Get the length of the list of numbers that
                                        // satisfy the above conditions

f=n=>[...Array(2**n)].filter((_,m)=>![...m=m.toString(2).padStart(n,0)].some(_=>s[m=m.replace(/(.)(.*)/,"$2$1")]|s[[...m].reverse().join``])&!/^(.+)\1+$/.test(m)&(s[m]=1),s=[]).length
<input id=i type=number value=5/><button onclick="o.innerText=f(i.value)">Test</button>

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


text:
Make a 2d menger sponge
A menger sponge is a fractal made out of cubes within cubes within cubes...
If you start with a cube, on each face there are 9 squares. The middle square becomes empty (or 0). The other 8 squares iterate this process. They each get split up into 9 squares and the middle square face is taken out.
The goal today is to generate a menger sponge face, not the cube.
Here are some example given an input for the number of iterations.
0:
1
(No holes or anything, solid face)

1:
1 1 1
1 0 1
1 1 1

2:
111111111
101101101
111111111
111000111
101000101
111000111
111111111
101101101
111111111

To complete the challenge, based on an input, return a set of 1 (filled in blocks) and 0 (empty blocks) with spaces between or not.
This is code golf, lowest number of bytes wins.

Also known as a Sierpinski carpet

SOGL V0.12, 19 bytes
1¹.{³³┼┼≥:10ŗ;┼┼⁴++

Try it Here!
1¹                   push [1]
  .{                 input times do
    ³³                 duplicate top of stack 4 times, resulting in 5 total copies in the stack
      ┼┼               join the last 3 copies horizontally together
        ≥              put the joined at the bottom of the stack
         :             duplicate top of stack again
          10ŗ          replace 1 with 0 only in the top item
             ;         swap the top 2 items
              ┼┼       join the top 3 items horizontally together
                ⁴      copy the item one below top of stack
                 ++    add together vertically

Wow, impressive. Mind explaining it a little bit for people not as familiar with these types of languages?

@JohnPaulPenaloza while I'm writing an explanation, you could turn on the debug mode, click run, and step trough the program to see it live in action

Thanks for the explanation. I'm new to code-golf style challenges and have never come close to solving one, I didn't know about the debug thing. Seeing these awesome solutions is really cool!


text:
Find the average of a word

Inspired by this chat message

Your task will be to take a word and find the average position of its letters on the keyboard as a letter.
Keyboard Layout
Since layouts vary from keyboard to keyboard, we will be using a standard based of of my own keyboard in this question.
The keyboard has 3 rows, the top row from left to right contains the keys
QWERTYUIOP

The second row contains the letters
ASDFGHJKL

The final row contains
ZXCVBNM

Each letter is 1 unit horizontal from its neighbor to the left.  This means that W is 1 away from Q and E is 1 away from W and so on.
The keys at the beginning of each row have the positions:
Q : 0,0
A : 1/3,1
Z : 2/3,2

This means that the rows are separated one unit vertically and the bottom two rows are shifted by a third from the row above them.

You should take a word as input and output the letter that is closest to the average position of the letters in its word.  The average of a set of vectors is
(average x value, average y value)

When two keys are equidistant from the average you may output either as the "closest" key.
This is code-golf so answers will be scored in bytes with fewer bytes being better.
Example solution
Let's calculate the average of APL.
We convert each letter to a vector
A -> (1/3,1)
P -> (9,0)
L -> (8 1/3,1)

We add these up the three vectors to get (17 2/3, 2). We then divide each coordinate by 3 (The number of letters in the word) to get (5 8/9, 2/3).
The closest letter to (5 8/9, 2/3) is J at (6 1/3,1) so our result is J.
Test Cases
APL  -> J
TEXT -> R
PPCG -> J
QQQQ -> Q
ZZZZ -> Z
PPPP -> P
MMMM -> M
QQSS -> A or W

May the I/O be lowercase, or is uppercase mandatory?

@KevinCruijssen You can do lower case.

Python 3, 130 bytes
lambda w,d={'QAZWSXEDCRFVTGBYHNUJMIKOOLPP'[i]:i%3*1j+i/3for i in range(28)}:min(d,key=lambda c:abs(d[c]-sum(map(d.get,w))/len(w)))

Try it online!
d={'QAZWSXEDCRFVTGBYHNUJMIKOOLPP'[i]:i%3*1j+i/3for i in range(28)} constructs the mapping from letters to points (represented as complex numbers, (x+y*1j)).
As for the lambda body, sum(map(d.get,w))/len(w) computes the average position of word w, and putting that in min(d,key=lambda c:abs(d[c]-…)) finds the closest letter to that position. (For complex numbers, abs(A-B) corresponds to the Euclidean distance between (A.real, A.imag) and (B.real, B.imag).)

C# (.NET Core), 250 + 13 bytes
+13 bytes for using System;
n=>{var a=new[]{"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};float x=0,y=0;int i=0,j=0,l=n.Length;foreach(char c in n){for(i=0,j=0;i<2;){if(a[i][j]==c)break;if(++j>=a[i].Length){i++;j=0;}}x+=j;y+=i;}return a[(int)Math.Round(y/3)][(int)Math.Round(x/l+y/l/3)];}

Try it online!
Little sidenote: This outputs F for TEXT, since that was the original desired output.
Outputting R instead of F was changed after this answer was posted.

Jelly, 37 bytes
ØQi€µT÷3Ḣ+Ṁ;T
Ç€ZÆmðạ²SðÐ€ØAÇ€¤iṂ$ịØA

Try it online!
lol way too long
Explanation
ØQi€µT÷3Ḣ+Ṁ;T            Helper Link; compute the position of a key
   €                     For each row of
ØQ                       ["QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"] (hooray for builtins)
  i                      Find the first occurrence of the argument
    µ                    Start a new monadic chain
     T                   List of indices of truthy values; singleton list with the row of the key
      ÷                  Divide the index by
       3                 3
        Ḣ                Take the first element
         +               Add it to the original list
          Ṁ              Take the maximum (the adjusted horizontal position of the key)
           ;             Append
            T            The index of the truthy value (the row)
Ç€ZÆmðạ²SðÐ€ØAÇ€¤iṂ$ịØA  Main Link
 €                       For each character in the input
Ç                        Compute its position using the helper link
  Z                      Zip (all of the horizontal positions are in the first list; all of the vertical positions are in the second list)
   Æm                    Take the arithmetic mean (of each sublist)
     ðạ²Sð               Dyadic chain to compute the distance (squared) between two coordinates
      ạ                  Take the absolute difference between each coordinate value (auto-vectorization)
       ²                 Square each value
        S                Take the sum (returns the distance squared but for comparison that's fine)
          Ð€             Take the distance between the mean position and each element in
            ØAÇ€¤        [Nilad:] the positions of each character in the uppercase alphabet
               €         For each character in
            ØA           "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
              Ç          Compute its position
                 iṂ$     Find the index of the minimum (closest)
                 i       First occurrence of             in the list of distances
                  Ṃ                          the minimum
                    ị    Index back into
                     ØA  The alphabet

@downvoter the issue with the test case has been fixed; please remove your downvote or explain why you wish to downvote my answer

I think it disagrees again? F doesn't seem to be an allowed output anymore...

@EriktheOutgolfer Ah okay I didn't update that remark after FCM corrected the test case

Somehow Mathematica doesn't have a bultin for keyboard rows.

@Razetime did you mean to comment somewhere else, this isn't Mathematica lol

no, it was strange to see a builtin that was in Jelly but not mathematica :P

@Razetime ah, I see. yeah finding something mathematica doesn't just have a builtin for is always pretty rare :D

JavaScript (ES6), 166 bytes

f=
s=>[...s].map(c=>(h+=c=s.search(c),v+=c%3,l++),h=v=l=0,s='QAZWSXEDCRFVTGBYHNUJMIKKOLLP')&&[...s].map((c,i)=>(i=(i-h/l)*(i-h/l)+(i=i%3-v/l)*i*9,i)<m&&(m=i,r=c),m=9)&&r
<input oninput=o.textContent=/^[A-Z]+$/.test(this.value)?f(this.value):``>

6 bytes could be saved by switching to ES7. Previous 131-byte solution used a simplistic distance check which is no longer acceptable.

f=
s=>([...s].map(c=>(h+=c=s.search(c),v+=c%3,l++),h=v=l=0,s='QAZWSXEDCRFVTGBYHNUJMIKKOLLP'),v=(v/l+.5|0),h=((h/l-v)/3+.5|0),s[h*3+v])
<input oninput=o.textContent=/^[A-Z]+$/.test(this.value)?f(this.value):``>

Java, 257 243 242 237 bytes
char h(String s){int l=s.length(),i=l+28;s="QAZWSXEDCRFVTGBYHNUJMIK
P"+s;float d=9,x=0,y=0,e;for(;i>28;y+=(e=s.indexOf(s.charAt(--i)))%3/l,x+=e/3/l);for(;i-->0;)if((e=(x-i/3f)*(x-i/3f)+(y-i%3)*(y-i%3))<d){d=e;l=i;}return s.charAt(l);}

Saved 14 bytes - the distance away from the best key will be less than 3 units

Java (OpenJDK 8), 452 431 424 400 389 324 322 296 285 281 276 274 260 258 257 bytes
Something to start golfing from
s->{String c="QWERTYUIOPASDFGHJKL;ZXCVBNM";int i=0,r=0,l=0;double x=0,y=0,D=99,t,f=s.length();for(;i<f;x+=l%10+l/10/3d,y+=l/10)l=c.indexOf(s.charAt(i++));for(;r<27;r++)if(D>(t=Math.pow(x/f-r/10/3d-r%10,2)+Math.pow(y/f-r/10,2))){D=t;l=r;}return c.charAt(l);}

Try it online!

Gives me the wrong result for TEXT.

@IanH. It gives me 'R' which is what OP asked for

Didn't see that was changed in the task, my bad.

431 bytes.

I hadn't seen this answer when I posted mine, should I have suggested mine as a comment or are multiple answers for the same language ok?

@Tahg Multiple are fine, nice one for beating me!

for(;i<f;l=c.indexOf(s.charAt(i++)),x+=l%10+l/10/3d,y+=l/10); can be golfed to  //for(;i<f;x+=l%10+l/10/3d,y+=l/10)l=c.indexOf(s.charAt(i++));

Charcoal, 79 bytes
≔⪪”$±=Ｋ≕⦃Vj@η⟲.w\`o:7➙1”¶ηＦθＦ³Ｆ⌕Ａ§ηκι⊞υ⟦λκ⟧ＩＥ²∕ΣＥυ§λιＬθ§§η⁺·⁵∕ΣＥυ⊟ιＬθ⁺·⁵∕ΣＥυ⊟ιＬθ

Try it online!
Neil's golf using string functions.
Charcoal, 107 bytes
Ｐ”$±=Ｋ≕⦃Vj@η⟲.w\`o:7➙1”≔⟦⟧α≔⟦⟧βＦχ«Ｆ³«ＪικＦθ«¿⁼λＫＫ«⊞α⎇›ⅉ⁰⁺∕¹¦³ⅈⅈ⊞βⅉ»»»»Ｊ⌊∕⁺Σα·⁵Ｌθ⌈∕⁺Σβ·⁵Ｌθ≔ＫＫχ⎚χ¶Ｉ∕ΣαＬθ¶Ｉ∕ΣβＬθ

Try it online!
Draws the keyboard on the canvas and finds the average that way.

Jelly, 33 31 bytes
Æịµ÷3Ċ+
ØQœiⱮÇÆmØQŒṪ¤Çạ¥ÐṂœịØQX

Try it online!
Uses some features that were presumably not implemented when HyperNeutrino wrote his solution, so considering this only beats it by 4 6 bytes, I wouldn't be surprised if a modernized version of his would come out shorter--but I started writing this before I even noticed his existed.
Æịµ÷3Ḟ+                    Helper link (monadic):
Æị                         convert list to complex,
  µ   +                    add the complex number to
     Ċ                     the imaginary part of
   ÷3                      its quotient by 3.

ØQœiⱮÇÆmØQŒṪ¤Çạ¥ÐṂœịØQX    Main link:
ØQœiⱮ                      multidimensional indices of input in QWERTY layout,
     Ç                     apply helper link,
      Æm                   average;
        ØQŒṪ¤              for all multidimensional indices in the layout
                ÐṂ         keep those with the smallest
              ạ¥           absolute difference between the average and
             Ç             their result from the helper link;
                  œịØQ     index back into QWERTY
                      X    and choose one key at random.

05AB1E, 44 bytes
žVIšεεžVsδkDZkDŠ3/+à‚]ćøÅA`UòDžVsèŠè€θDX.xkè

Not too happy with it, but it works.. :/ Can definitely be golfed some more using a different approach.
I/O in lowercase.
Try it online or verify all test cases.
Explanation:
Step 1: create a list with all the coordinate-values, and convert the input in a similar matter as well:
žV                     # Push builtin ["qwertyuiop","asdfghjkl","zxcvbnm"]
  Iš                   # Prepend the input-string to this list
    ε                  # Map over each string:
     ε                 #  Inner map over each individual character:
      žV               #   Push ["qwertyuiop","asdfghjkl","zxcvbnm"] again
        s              #   Swap so the current character is at the top of the stack
         δk            #   Get the index of this character in each of the three strings
                       #   (or -1 if it's not found)
           D           #   Duplicate this list of indices
            Z          #   Get the largest index (without popping)
             k         #   Get the index of this largest index in the triplet
              D        #   Duplicate this index
               Š       #   Triple swap the three values on the stack (a,b,c→c,a,b)
                3/     #   Divide it by 3
                  +    #   Add it to each index in the list we duplicated
                   à   #   Pop and push the maximum again
                    ‚  #   And pair it with the duplicated & triple-swapped index
    ]                  # Close the nested maps

Try just this first step.
Step 2: get the average coordinate of the input:
ć                      # Extract head; pop and push remainder-list and first item separated
 ø                     # Zip/transpose; swapping rows/columns
  ÅA                   # Get the arithmetic mean of both inner triplets

Try just the first two steps.
Step 3: get the coordinate closest to this average coordinate, and convert it back to a character to output:
`                      # Pop and push both separated to the stack
 U                     # Pop and store the second one in variable `X`
  ò                    # Round the first value to the nearest integer
   D                   # Duplicate this integer
    žV                 # Push ["qwertyuiop","asdfghjkl","zxcvbnm"] yet again
      s                # Swap so the integer is at the top of the stack
       è               # Index it into the list of strings
        Š              # Triple-swap the values on the stack (a,b,c→c,a,b)
         è             # Index the duplicated integer into the remainder-list
          €θ           # Leave the last value of each inner pair
            D          # Duplicate the list
             X.x       # Pop the copy and leave the value closest to value `X`
                k      # Get the index of this value in the duplicated list
                 è     # And index it into the string we triple-swapped
                       # (after which this character is output implicitly as result)

Mathematica, 234 bytes
(r=(K=Round)@Mean[If[(w=First[q=#&@@Position[(s=X/@{"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"}),#]])==1,q=q-1,If[w==2,q=q+{-1,-2/3},q=q+{-1,-1/3}]]&/@(X=Characters)@#];z=If[(h=#&@@r)==0,r=r+1,If[h==1,r=r+{1,2/3},r=r+{1,1/3}]];s[[##]]&@@K@z)&

Fixed! works for all test cases.

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


text:
Is the group cyclic?
Introduction
You can skip this part if you already know what a cyclic group is.
A group is defined by a set and an associative binary operation \$\times\$ (that is, \$(a \times b) \times c = a \times (b \times c)\$. There exists exactly one element in the group \$e\$ where \$a \times e = a = e \times a\$ for all \$a\$ in the group (identity). For every element \$a\$ in the group there exists exactly one \$b\$ such that \$a \times b = e = b \times a\$ (inverse). For every two elements \$a, b\$ in the group, \$a \times b\$ is in the group (closure).
We can write \$a^n\$ in place of \$\underbrace{a\times a\times a\times ...\times a}_{n \text{ times}}\$.
The cyclic subgroup generated by any element \$a\$ in the group is \$\langle a \rangle = \{e, a, a^2, a^3, a^4, ..., a^{n-1}\}\$ where \$n\$ is the order (size) of the subgroup (unless the subgroup is infinite).
A group is cyclic if it can be generated by one of its elements.
Challenge
Given the Cayley table (product table) for a finite group, determine whether or not it's cyclic.
Example
Let's take a look at the following Cayley table:
1 2 3 4 5 6
2 3 1 6 4 5
3 1 2 5 6 4
4 5 6 1 2 3
5 6 4 3 1 2
6 4 5 2 3 1

(This is the Cayley table for Dihedral Group 3, \$D_3\$).
This is 1-indexed, so if we want to find the value of \$5 \times 3\$, we look in the fifth column on the third row (note that the operator is not necessarily commutative, so \$5 \times 3\$ is not necessarily equal to \$3 \times 5\$. We see here that \$5 \times 3 = 6\$ (also that \$3 \times 5 = 4\$).
We can find \$\langle 3 \rangle\$ by starting with \$[3]\$, and then while the list is unique, append the product of the last element and the generator (\$3\$). We get \$[3, 3 \times 3 = 2, 2 \times 3 = 1, 1 \times 3 = 3]\$. We stop here with the subgroup \$\{3, 2, 1\}\$.
If you compute \$\langle 1 \rangle\$ through \$\langle 6 \rangle\$ you'll see that none of the elements in the group generate the whole group. Thus, this group is not cyclic.
Test Cases
Input will be given as a matrix, output as a truthy/falsy decision value.
[[1,2,3,4,5,6],[2,3,1,6,4,5],[3,1,2,5,6,4],[4,5,6,1,2,3],[5,6,4,3,1,2],[6,4,5,2,3,1]] -> False (D_3)
[[1]] -> True ({e})
[[1,2,3,4],[2,3,4,1],[3,4,1,2],[4,1,2,3]] -> True ({1, i, -1, -i})
[[3,2,4,1],[2,4,1,3],[4,1,3,2],[1,3,2,4]] -> True ({-1, i, -i, 1})
[[1,2],[2,1]] -> True ({e, a} with a^-1=a)
[[1,2,3,4,5,6,7,8],[2,3,4,1,6,7,8,5],[3,4,1,2,7,8,5,6],[4,1,2,3,8,5,6,7],[5,8,7,6,1,4,3,2],[6,5,8,7,2,1,4,3],[7,6,5,8,3,2,1,4],[8,7,6,5,4,3,2,1]] -> False (D_4)
[[1,2,3,4,5,6],[2,1,4,3,6,5],[3,4,5,6,1,2],[4,3,6,5,2,1],[5,6,1,2,3,4],[6,5,2,1,4,3]] -> True (product of cyclic subgroups of order 2 and 3, thanks to Zgarb)
[[1,2,3,4],[2,1,4,3],[3,4,1,2],[4,3,1,2]] -> False (Abelian but not cyclic; thanks to xnor)

You will be guaranteed that the input is always a group.
You may take input as 0-indexed values.

Is 0-indexed input allowed? (e.g. [[0,1,2,3],[1,2,3,0],[2,3,0,1],[3,0,1,2]])?

@Neil Yes; I forgot to specify. Thanks!

@H.PWiz [[2,1],[1,2]] :P

Truthy test case: [[1,2,3,4,5,6],[2,1,4,3,6,5],[3,4,5,6,1,2],[4,3,6,5,2,1],[5,6,1,2,3,4],[6,5,2,1,4,3]] (product of cyclic groups of orders 2 and 3).

@Zgarb Thanks, I'll add that

You should premute the labels of your group elements more in the test cases. Right now the first row and column of the table is always [1..n] which may be hiding flaws in some answers.

@Lynn Hmm good idea. I'll take one of my truthy cases and permute it. thanks for the suggestion

It looks like checking if the group is abelian suffices to pass the test cases. Test cases like Z_2 * Z_2  would fix this.

@xnor That does seem to be an issue; thanks. However, I'm not quite sure what Z_2 * Z_2 means?

@HyperNeutrino: That's the direct product of the two-element group with itself -- also known as the Klein four-group.

@Lynn the 0 and 1 rows/columns of a Cayley table are always trivial: 0e = 0, 1e = e. We could have a bonus problem where one has to decide whether the Cayley table corresponds to a group. Or even decide between {cyclic, non-cyclic abelian, non-abelian, not a group}.

@HenningMakholm thanks

@xnor Isn't Klein 4 abelian too though?

@HyperNeutrino It is, but it isn't cyclic.

@xnor facepalm right. thanks; I'll add that!

Husk, 11 10 9 bytes
VS≡`ȯU¡!1

1-based.
Returns the index of a generator if one exists, 0 otherwise.
Try it online!
Explanation
V          Does any row r of the input satisfy this:
      ¡!    If you iterate indexing into r
   `    1   starting with 1
    ȯU      until a repetition is encountered,
 S≡         the result has the same length as r.

J, 8 bytes
1:e.#@C.

Try it online!
Explanation
1:e.#@C.  Input: matrix M
      C.  Convert each row from a permutation to a list of cycles
    #@    Number of cycles in each row
1:        Constant function 1
  e.      Is 1 a member of the cycle lengths?

This could also be 1 e.#@C., fwiw

Huh, J beats Jelly‽

@Adám Jelly doesn't have a builtin to convert permutations between direct and cycle notation. I could probably add them as atoms later, making ŒCL€1e for 6 bytes in Jelly.

Jelly, 13 11 bytes
ị"⁸$ÐĿ«/E€Ẹ

Try it online!

JavaScript (ES6), 52 bytes
a=>a.some(b=>!a[new Set(a.map(_=>r=b[r],r=0)).size])

Test with group $D_3$ but it outputs true

@SketchySketch Sorry, I should have mentioned that this answer is 0-indexed.

Python 2, 96 91 97 bytes
lambda x:any(g(r,r[i],i+1)==len(r)for i,r in enumerate(x))
g=lambda x,y,z:y==z or 1+g(x,x[y-1],z)

Try it online!

or 1+g -> or-~g.

R, 101 97 bytes
function(m)any(sapply(1:(n=nrow(m)),function(x)all(1:n%in%Reduce(`[`,rep(list(m[x,]),n),x,T,T))))

Verify all test cases
This simply computes <g> for each g \in G and then tests if G \subseteq <g>, then checks if any of those are true. However, since we're always applying $g on the right, we replicate m[g,] (the gth row) and then index into that row with the result of applying $g, accumulating the results rather than using m[g,g$g] every time, which saved about 4 bytes.

Jelly, 15 bytes
JŒ!ị@€µṂ⁼Jṙ'’$$

Try it online!
First silly idea that came to mind: check for isomorphism to Zn. (This code is O(n!)…)
JŒ!ị@€             Generate all ways to denote this group.
                     (by indexing into every permutation of 1…n)
      µṂ⁼          Is the smallest one equal to this?
         Jṙ'’$$      [[1 2 …  n ]
                      [2 3 …  1 ]    (the group table for Z_n)
                      [… … …  … ]
                      [n 1 … n-1]]

Huh this is an interesting approach; never thought of that! +1

Jelly, 8 bytes
JịƬ"ZẈiL

Try it online!
Outputs 0 for False and a non-negative integer for True
Jelly finally ties J!
How it works
JịƬ"ZẈiL - Main link. Takes the Cayley matrix n×n M on the left
    Z    - Transpose M
J        - Yield [1, 2, ..., n]
  Ƭ      - Until reaching a fixed point, do the following and replace i with the result
   "     -   Pair each i (intially 1,2...,n) with each row, then do the following:
 ị       -     Take the i'th element of each row
     Ẉ   - Get the length of each
       L - Yield n
      i  - Index of n in the lengths, or 0 if not present

Python 2, 82 bytes
lambda A:len(A)in[len(set(reduce(lambda a,c:a+[A[a[-1]][n]],A,[n])))for n in A[0]]

Try it online!
0-indexed Cayley table is input; True/False output for cyclic/non-cyclic group.

Clojure, 68 bytes
#(seq(for[l % :when(apply distinct?(take(count l)(iterate l 0)))]l))

JavaScript (Node.js), 42 bytes
a=>a.some(b=>a.every(r=z=>r=1/r?b[r]:[0]))

Try it online!
Starting from element 0, go n-1 steps, if 0 never appear

Zsh, 72 bytes
Input each row as a separate argument; rows are space-delimited.
Exits 0 if cyclic, 1 otherwise.
for r;(set $=r
x=($1)
for i;x+=($@[x[-1]])
x=(${(u)x})
(($#==$#x)))&&bye

Try it online!
Explanation:
for r;                # for each row
  (                     # In subshell:
    set $=r             #   split row on spaces, set as ARGV
    x=($1)              #   initialize $x with the first element
    for i
        x+=($@[x[-1]])  #   use $x[-1] as the index, add that element to $x
    x=(${(u)x})         #   remove duplicates from $x
    (($#==$#x))         #   Compare length of $@ with length of $x
  ) && bye              # If subshell exited true, early-exit whole program true
                      # If we haven't early-exited by the end of the program,
                      # the exit code would be 1 (falsy) since the last loop
                      # had no generator, and therefore returned 1.

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


text:
Generate Numpad-Friendly Numbers
Inspired by Generate Keyboard Friendly Numbers.
Background
Many number pads have the following layout:
789
456
123
    0
We define a number's neighborhood as the set of cells orthogonally adjacent to it on the numpad shown, including itself. For example, 2's neighborhood is {1,5,3,0,2} and 0's neighborhood is {1,2,0}. There is a list of each number's neighborhood below, above test cases.
We define a numpad friendly number as a positive integer where, when written in decimal without leading zeroes, each digit except for the first is in the neighborhood of the previous digit.
For example,

7856 is a numpad friendly number because 8 is in the neighborhood of 7, 5 is in the neighborhoood of 8, and 6 is in the neighborhood of 5.
1201 is a numpad friendly number because 2 is in the neighborhood of 1, 0 is in the neighborhood of 2, and 1 is in the neighborhood of 0.
82 is not a numpad friendly number because 2 is not in the neighborhood of 8.
802 is not a numpad friendly number because 0 is not in the neighborhood of 8 (neighborhoods don't wrap around).

Related OEIS Sequence. Note that this related sequence is distinct because it counts 0 as adjacent to 7 instead of 1 and 2.
Challenge
Given a positive integer n, return the n-th or the first n numpad friendly numbers, where the first is 1. You may use 0-based indexing, where the 0-th numpad friendly number would be 1.
Neighborhoods
Each digits's neighborhood is listed here:
0:{0,1,2}
1:{0,1,2,4}
2:{0,1,2,3,5}
3:{2,3,6}
4:{1,4,5,7}
5:{2,4,5,6,8}
6:{3,5,6,9}
7:{4,7,8}
8:{5,7,8,9}
9:{6,8,9}

Test Cases / Sequence
These are the first 100 terms
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 20, 21, 22, 23, 25, 32, 33, 36, 41, 44, 45, 47, 52, 54, 55, 56, 58, 63, 65, 66, 69, 74, 77, 78, 85, 87, 88, 89, 96, 98, 99, 100, 101, 102, 110, 111, 112, 114, 120, 121, 122, 123, 125, 141, 144, 145, 147, 200, 201, 202, 210, 211, 212, 214, 220, 221, 222, 223, 225, 232, 233, 236, 252, 254, 255, 256, 258, 320, 321, 322, 323, 325, 332, 333, 336, 363, 365, 366, 369, 410, 411, 412, 414, 441, 444, 445, 447]

I like how this challenge only considers positive integers (which keeps the essence and allows more languages to participate) and allows displaying either the n-th or the first n outputs for flexibility

I completely misread the challenge, here's an "is this term valid in the sequence" script: Try it online!

JavaScript (ES6), 104 93 89 88 bytes
Returns the N-th term of the sequence, 1-indexed.
f=(i,k,n=k,N=n/5>>1)=>(N?8530025>>(n%10*6191^N%10*6191)%26&1:!i--)?N?f(i,k,N):k:f(i,-~k)

Demo

f=(i,k,n=k,N=n/5>>1)=>(N?8530025>>(n%10*6191^N%10*6191)%26&1:!i--)?N?f(i,k,N):k:f(i,-~k)

for(n = 1; n <= 50; n++) {
  console.log('a(' + n + ') = ' + f(n))
}

Best I could get is 151 k=(n,a=1)=>n?k(n-([...(x=a+[]).slice(0,-1)].reduce((a,c)=>a*!!~"012 0124 01235 236 1457 24568 3569 478 5789 689".split` `[c].indexOf(x[i++]),i=1)),a+1):a-1 maybe something there helps, my test is probably too long

This answer brings the concept of magic numbers to a whole new level... I don't even understand how you found them o_O

@scottinet To a large extent, my explanation for this answer applies to this one as well. The absolute difference didn't work very well on that one, so I tried with XOR instead. As a side note, I found another formula that worked in 96% of cases without the need for a lookup bitmask. But processing the remaining 4% separately was too costly in JS. I didn't try in Jelly, and now I don't remember the formula anyway... ¯\(ツ)/¯

Thanks for the explanations. This is still impressive :-)

Perl 5, 123 + 1 (-p) = 124 bytes
while($_){$r=@d=++$\=~/./g;map$r&&=(120,1240,12350,236,1457,24568,3569,478,5789,689)[$d[$_-1]]=~/$d[$_]/,1..$#d;$r&&$_--}}{

Try it online!

Jelly, 27 24 bytes
Returns the N first terms of the sequence.
D⁽ÞȦ×^2\%26“⁷wð’æ»ḂẠ
1Ç#

Try it online!
This is a port of my JS answer.
D⁽ÞȦ×^2\%26“⁷wð’æ»ḂẠ    - helper link: test numpad-friendliness of a number, e.g. 1257
D                       - get decimal digits             -> [1, 2, 5, 7]
    ×                   - multiply by ...
 ⁽ÞȦ                    - ... the integer 6191           -> [6191, 12382, 30955, 43337]
     ^2\                - bitwise XOR overlapping reduce -> [10353, 18613, 53666]
        %26             - modulo 26                      -> [5, 23, 2]
                æ»      - right-shift by each value ...
           “⁷wð’        - ... the integer 8530025        -> [266563, 1, 2132506]
                  Ḃ     - isolate the LSB                -> [1, 1, 0] which means that 1->2
                                                            and 2->5 are OK and 5->7 is not
                   Ạ    - all (0 if there's any 0)       -> 0, i.e. not numpad-friendly :'(

1Ç#                     - main link: return the [input] first matching numbers,
                          using our helper link as a monad and starting with 1

05AB1E, 24 23 bytes
µNSü‚εW_iO<ë<3BÆ}ÄR2‹}P

Try it online!
Returns the nth number in the sequence.
Explanations:
µNSü‚εW_iO<ë<3BÆ}ÄR2‹}P    Full program
µ                          Until counter is equal to input
 N                         Push current iteration number (e.g. 1025)
  S                        Split to a list of chars (-> ['1', '0', '2', '5'])
   ü‚                      Group into pairs (-> ['1', '0'], ['0', '2'], ['2', '5'])
     ε                     For each pair
      W_                      Is smallest digit equal to 0?
        iO<                      True: sum all digits and decrement
           ë                     False:
            <                       - decrement all digits
             3B                     - convert to base 3
               Æ                    - reduced substraction
                }             End if
                 Ä            Absolute value
                  R           Reverse
                   2‹         1 if result is < 2, 0 otherwise
                     }     End for each
                      P    Cumulative product (1 if all pair results are
                                     1, 0 otherwise)
                           -- implicit counter increment if stack value is 1

The main idea is that, apart from the 0 key, any digit decremented and converted to base 3 has the following properties:

left and right neighbours have an absolute difference of 1
up and down neighbours have an absolute difference of 10 which, reversed, is conveniently equal to 1
any other pair of numpad keys result in different values, even when reversed

Of course we need a if statement to handle the 0 numpad key.

Solid answer, came to offer more improvements, can't find any. Oooo... and that pairwise put you in the lead too :).

I don't think I would've been able to come up with those 3 rules, pretty impressive tbh; what gave you the idea?

Jelly, 26 bytes
’d-,.⁸?3µ€ạ/S
Dṡ2Ç€<2Ạ
1Ç#

Try it online!
-2 bytes thanks to caird coinheringaahing
-2 bytes thanks to Erik the Outgolfer
Explanation
’d-,.⁸?3µ€ạ/S  Helper Link; compute the distance between two keys z = [x, y]
      ?        Switch:
     ⁸         If z (is not 0):
’              Decrement
 d             Divmod by:
  -,.          Else: [-1, 0.5] (special position for 0)
       3       3; right argument for divmod otherwise ignored
        µ      Begin a new monadic link / end this link
         €     Compute the position for each [x, y]
           /   Reduce on
          ạ    Absolute Difference
            S  Sum (this gives the Manhattan Distance)
Dṡ2Ç€<2Ạ       Helper Link; determine if a number <z> is numpad friendly
D              Convert number to decimal digits
 ṡ             Slice into overlapping slices of length
  2            2 (pairs)
    €          For each pair,
   Ç           The distance between the keys
     <2        Compare with 2 (the distance between two adjacent keys is 1; corners 2; 0 - 1 and 0 - 2 are 1.5)
       Ạ       All; either all of the distances are less than 2 or there were no distances
1Ç#            Main Link; find the first (input) numpad friendly numbers
  #            nfind; counting up from _ collect the first _______ matches that are
1                                      1
                                                           (input)
 Ç             Numpad Friendly

You can remove the [] for 2 bytes

@cairdcoinheringaahing thanks!

Golf a couple off.

MATL, 29 27 bytes
`@J3:qEt!J*+hYAd|2>~A?@]NG-

Outputs the first n numpad-friendly numbers.
Try it online!
Explanation
Each digit from 1 to 9 is encoded as a complex number representing its position in the numpad, using in a step-2 grid, where real part represents vertical position and imaginary part represents horizontal position. So 1 is 0+0j, 2 is 0+2j, 3 is 0+4j, 4 is 2+0j, ..., 9 is 4+4j.
Digit 0 is encoded as 0+1j, i.e. as if it were placed exactly between 1 and 2.
For each candidate numpad-friendly number, a "decimal" base conversion is applied using the above complex numbers instead of the digits 0, 1, ..., 9. This gives an array, of which the absolute consecutive differences are computed. The candidate number is numpad-friendly if and only if all absolute differences are at most 2 (i.e. the grid step). If that's the case, the number is left on the stack.
The code uses a do...while loop, which is exited when the amount of numbers in the stack equals the input n.
A unit grid would have been a more natural choice. Digits 1, 2 and 0 would then correspond to 0+0j, 1+0j and 0.5+0j respecrively. But it's golfier to use a step-2 grid, because multiplying by 2 (function E) and pushing 0+1j (function J) is one byte shorter than pushing 0+0.5j (J2/ or .5j)

Python 2, 134 bytes
g=lambda n,k=1:n and g(n-(lambda l:all(abs(a-b)<1.2for a,b in zip(l,l[1:])))([~-d%3+~-d/3*1j-d/~d*1.5for d in map(int,`k`)]),k+1)or~-k

Try it online!

As you define f and then use it once, you could inline it and save two bytes.

PHP, 124+1 bytes
while($argn-=$r)for($p=$r=~0,$x=++$n;$x>=1;$p=[7,23,47,76,178,372,616,400,928,832][$c],$x/=10)$r&=!!($p&1<<$c=$x%10);echo$n;

Run as pipe with -nR or try it online.

Mathematica, 249 234 202 bytes
(a=o=1;While[a<=#,s=IntegerDigits@o;t=1;p=0;While[t+p<Length@s,If[!FreeQ[(IntegerDigits/@{210,4210,53210,632,7541,86542,9653,874,9875,986})[[s[[t]]+1]],s[[t+1]]],t++,p++]];If[t==Length@s,a++];o++];o-1)&

Try it online!
thanks user202729 for compressing data (-32 bytes)
My results:

100 ->447
  1000 ->20023
  10000 ->788777

I think you can compress the data by using IntegerDigits : IntegerDigits/@{210,4210,53210,632,7541,86542,9653,874,9875,986}, and use FreeQ, Tr, use Do instead of For, use infix notation for AppendTo and use Do instead of While to repeat Tr[1^s] times, also eliminate the variable p. Also you haven't proven that the algorithm is correct, that is, the resulting number is always less than its index squared, which is necessary to make an answer valid.

@user202729 I changed a lot of things.My answer is definately valid. I'll compress the data now.

why the downvote?

Java 8, 192 190 bytes
n->{int r=1,p;a:for(;n>0;){p=-1;for(int c:(r+++"").getBytes())if(p>-1&!"012;0124;01235;236;1457;24568;3568;478;5789;689".split(";")[c-=48].contains(p+""))continue a;else p=c;n--;}return~-r;}

Returns the (1-indexed) n'th number in the sequence.
This was surprisingly harder than I thought.. Probably just having some brain-farts this afternoon..
Explanation:
Try it here.
n->{                 // Method with integer as both parameter and return-type
  int r=1,           //  Return-integer
      p;             //  Previous digit
  a:for(;n>0;){      //  Loop (1) as long as the input is larger than 0
    p=-1;            //   Start `p` at an integer that is not 0-9 (-1 in this case)
    for(int c:(r+++"").getBytes())
                     //   Loop (2) over the digits of the current number
      if(p>=0        //    If this is not the first digit (`p` != -1),
         &!"012;0124;01235;236;1457;24568;3568;478;5789;689".split(";")[c-=48]
           .contains(p+""))
                     //    and the adjacent digits are NOT part of a NumberPad-Friendly Nr:
        continue a;  //     Go to the next iteration of loop (1)
      else           //    Else:
        p=c;         //     Set `p` to the current digit for the next iteration
                     //   End of loop (2) (implicit / single-line body)
      n--;           //   If we haven't encountered the `continue`, decrease `n` by 1
  }                  //  End of loop (1)
  return~-r;         //  Return the result-integer - 1
}                    // End of method


text:
Finding Snakes in a Matrix
Challenge
Given a binary matrix and a binary string, determine if that binary string can be found starting at any point in the matrix and moving in any direction at any subsequent point to form the binary string. That is, can the string be found folded up however inside the matrix?
The string can only be folded at 90 degrees or 180 degrees (edge connections; Manhattan Distance 1) and cannot overlap itself at any point.
Example
Let's take the following example:
Matrix:

010101
111011
011010
011011

Snake: 0111111100101

This is a truthy test case. We can see the snake folded up in the following position:
0-1 0 1 0 1
  |
1 1 1-0 1 1
  | | |   |
0 1 1 0-1-0
  | |
0 1-1 0 1 1

Rules

Standard Loopholes Apply
You may take the length of the string and the width and height of the matrix as input if you'd like
You may take the binary matrix and the binary string as a multiline string/array of strings/newline-joined string/anything else-joined string and a string
You may take the dimensions as a flat array instead of several arguments
Your program must finish for any 5 x 5 matrix with any string of up to length 10 in under a minute

Limitations

The matrix is not necessarily square
The string will be non-empty
The string can be length-1
The string will not contain more squares than available (that is, len(string) <= width(matrix) * height(matrix)

Test Cases
Truthy
01010
10101
01010
10101
01010

0101010101010101010101010

01110
01100
10010
10110
01101

011111000110100

0

0

10
01

1010

100
010
001

100010001

Falsy
00000
00000
00000
00000
00000

1

10101
01010
10101
01010
10101

11

100
010
001

111

10001
01010
00100
01010
10001

1000100010001000101010100

Sandbox Post (Deleted)

Or: Binary Boggle!  Also, can you add a few more test cases?

Related.

@Jonah added a few more

If you wanted your additional test cases to be formatted like your first one is, you could use the program I link to at the bottom of my answer.

@JonathanFrech Cool, thanks. I'll reformat these cuz it's hard to test

Can I take the input as a char[][] and char[] instead of a String?

@Tahg Yes you may

Python 2, 275 271 264 249 bytes

Saved four bytes by replacing -1 with H and removing one slicing operation ([:]).
Saved seven bytes thanks to Halvard Hummel; removing yet another slicing operation ([:]), using multiple-target assignment to give a visited entry a value v not in "01" (S=S[1:];M[y][x]=H; -> S=M[y][x]=S[1:];) and switching from a ternary if/else to a simple logical or (any(...)if S else 1 -> not S or any(...)).
If you somewhat extend your definition of truthy and falsey, you could allow this 257 byte long solution. It raises an exception (ZeroDivisionError) when the snake is found and returns an empty list ([]) when there is no snake to be found, which are two distinct behaviours.
Saved fourteen bytes thanks to user202729; golfing two array deep copies
Saved a byte; golfed not S or to S<[1]or ~ S==[]or.

lambda M,S,w,h:any(H(eval(`M`),S,w,h,x,y)for y in range(h)for x in range(w)if S[0]==M[y][x])
def H(M,S,w,h,x,y):S=M[y][x]=S[1:];return S<[1]or any(H(eval(`M`),S,w,h,x+X,y+Y)for X,Y in[(~0,0),(1,0),(0,~0),(0,1)]if~0<x+X<w>0<=y+Y<h!=S[0]==M[y+Y][x+X])

Try it online!
Explanation
Lambda function which takes in the matrix as a two-dimensional list of strings (either "0" or "1"), the snake as a one-dimensional list and the matrix dimensions as two integers.
The lambda function searches the matrix for entries that match the snake's first element. For every found match, it calls H with a deep copy of the matrix, no copy of the snake, the matrix dimensions and the match's position.
When H is called, it removes S' first entry and sets the given position's matrix entry to something else than "0", "1". If S' length is zero, it returns True; as it calls itself recursively, the snake was found somewhere in the matrix.
If S' length is non-zero, it loops through the four cardinal directions, tests if that position is in the matrix, compares the matrix' element at that position with the first element of S and -- if it matches -- calls itself recursively.
H's return values are funneled up the stack frames, always checking if at least one function found a possible snake.
Formatted Output
I have augmented my program to also output the path the snake slithers (if there is one). It uses the same ASCII output design as the question. TIO link.

264 bytes

@HalvardHummel Thanks; especially for spotting the superfluous slicing operation.

@user202729 You think m[:]for ~> m*1for? Might work.

@user202729 Thanks, the linked tip worked as I think this needs a deep copy.

JavaScript (ES6), 138 134
Not so different from @Neil's, but what else could it be?
Input: matrix as a multi line string, binary string, width (not counting newline)
NB: the logic in the recursive function r is somewhat inverted to save a couple of bytes
(m,s,w)=>[...m].some((c,p,m,r=(p,o)=>s[m[p]=r,o]&&([~w,-~w,1,-1].every(d=>m[d+=p]!=s[o]||r(d,o+1))&&(m[p]=s[o-1])))=>c==s[0]&&!r(p,1))

Less golfed
(m,s,w)=>(
  m=[...m],
  r= (p, o) =>
    (m[p] = -w, s[o])
    && (
         [~w, -~w, 1, -1].every( d =>
            m[d+=p] != s[o] || r(d, o+1)
         )
         && (m[p]=s[o-1])
    ),
  m.some((c,p) =>c == s[0] && !r(p,1))
)

Test

var F=
(m,s,w)=>[...m].some((c,p,m,r=(p,o)=>s[m[p]=r,o]&&([~w,-~w,1,-1].every(d=>m[d+=p]!=s[o]||r(d,o+1))&&(m[p]=s[o-1])))=>c==s[0]&&!r(p,1))

// this slightly modified version tracks the path
var Mark=
(m,s,w)=>(m=[...m]).some((c,p,m,r=(p,o)=>s[m[p]=-o,o]&&([~w,-~w,1,-1].every(d=>m[d+=p]!=s[o]||r(d,o+1))&&(m[p]=s[o-1])))=>c==s[0]&&!r(p,1))
?m.map((c,p)=>c<-1?'.───│┘└.│┐┌.│'[((m[p-1]-c)**2<2)+((m[p+1]-c)**2<2)*2+((m[p+~w]-c)**2<2)*4+((m[p-~w]-c)**2<2)*8]:c<0?'*':c).join``:''

function go()
{
  O.textContent =F(M.value, S.value, M.value.search('\n'))+'\n\n'
  +Mark(M.value, S.value, M.value.search('\n'))
}

go()
#M {width:100px; height:100px }
<textarea id=M>010101
111011
011010
011011</textarea>

<input id=S value='0111111100101' oninput='go()'>
<button onclick='go()'>go</button>

JavaScript (ES6), 149 bytes
(m,s,w)=>[...m].some((c,i)=>c==s[0]&&g(m,s,i),g=(m,s,i)=>!(s=s.slice(1))||[~w,-1,1,-~w].some(o=>m[o+=i]==s[0]&&g(m.slice(0,i)+' '+m.slice(i+1),s,o)))

Takes the matrix as a newline-delimited string, the snake as a string and the width (as an integer). Loosely based on @JonathanFrech's answer.

Mathematica, 180 156 141 153 138 136 104 bytes
MemberQ[#|Table[""<>Part[Join@@#,p],{x,1##4},{y,1##4},{p,FindPath[GridGraph@{##4},x,y,#3,All]}],#2,All]&

Example input
[{{"1","1","1","1","1"},{"0","0","0","0","0"}},"10011001",8,5,2]

Explanation

GridGraph@{##4} is a Graph object for a grid of vertices with adjacent vertices connected by edges, with dimensions {##4} - that is, {#4,#5} or {width,height}.
We iterate over all starting vertices x (numbered 1 to 1##4 = width*height), all ending vertices y, and all paths p of length at most #3 from x to y.
For each such path, ""<>Part[Join@@#,p] extracts the corresponding characters of the matrix and puts them into a string.
We also include the matrix itself, whose characters are all the strings of length 1 that can be found in it.
We see if one of these strings matches s, searching at all levels because this is a very multidimensional list we've built.

Note: Replacing #3 by {#3-1} in FindPath, so that we only find paths of exactly the right length, is a huge improvement in terms of speed - but costs 4 more bytes.

-24 bytes: taking dimensions of things as input
-15 bytes: using StringPart and StringJoin properly
+12 bytes: fixing the length-1 case
-15 bytes: ...
-2 bytes: taking size of the matrix as input as an array
-32 bytes: using Table to iterate over the path lets us avoid using Function, and using MemberQ[...,s,All] lets us just sort of stick the matrix onto the table when dealing with snakes of length 1.

C# (.NET Core), 346 341 336 302 297 bytes
(m,h,w,s,l)=>{for(int y=0;y<h;y++)for(int x=0;x<w;x++)if(N(x,y,l-1))return 0<1;return 1<0;bool N(int x,int y,int p){if(p<0)return 0<1;if(y<0|x<0|y==h|x==w||m[y,x]>1||s[p]!=m[y,x])return 1<0;int g=m[y,x];m[y,x]=2;if(N(x,y-1,--p)||N(x-1,y,p)||N(x,y+1,p)||N(x+1,y,p))return 0<1;m[y,x]=g;return 1<0;}}

Try it online!
5 bytes saved by golfing the p increment
5 bytes saved by taking in the snake length and starting at its tail, and removing an unnecessary space
34 bytes saved by reading the challenge properly and seeing I can take in the matrix's height and width
5 bytes saved, the single element test case failed, and the fix was beneficial
Ungolfed
(m,h,w,s,l)=>{
    // Go through every potential starting point
    for(int y=0; y<h; y++)
        for(int x=0; x<w; x++)
            if(N(x,y,l-1)) // start the recursive steps
                return 0<1; // return true if N returns true, otherwise check the next element

    return 1<0; // return false as the snake doesn't fit into the matrix

    // C#7 local function in a Func
    bool N(int x, int y, int p)
    {
        // if there is no more snake to fit return true
        if(p<0)
            return 0<1;

        // if m element has part of the snake or
        // snake part doesn't match matrix element then return false
        if(y<0 | x<0 | y==h | x==w || m[y,x]>1 || s[p] != m[y,x])
            return 1<0;

        // hold the current matrix element
        int g=m[y,x];
        // set the current matrix element to 2 to indicate it has a part of the snake
        m[y,x]=2;

        // check each of the four neighbours and recurse down that neighbour
        // except if they are outside the matrix
        if(N(x,y-1,--p) ||
           N(x-1,y,p) ||
           N(x,y+1,p) ||
           N(x+1,y,p))
               return 0<1; // return true if remainder of the snake fits into the matrix

        // if snake doesn't fit then set the matrix element as not having part of the snake
        m[y,x]=g;
        // return false to indicate this neighbour direction doesn't fit the snake
        return 1<0;
    }
}

A golfing start would be to remove all unnecessary whitespace...

if(...)return true; -> return ...;.

@JonathanFrech Agreed, but I left it like that to allow others to read it a little more easily until I get a chance to get back to it (sometime tomorrow).

@JonathanFrech Doesn't work, b[y,x] needs to be reset at some point. (Also sorry for misspelling your name in my answer.)

I meant if(N(x,y,0)>0)return 0<1;; the first appearance of return.

@JonathanFrech What good would that do? All the possible starting squares need to be checked...

@Neil Well, true. Ignore that thought.

248 bytes

Kotlin, 413 bytes
var x:(Array<Array<Char>>,String)->Boolean={b,s->fun f(s:String,x:Int,y:Int):Boolean{if(b[x][y]!=s[0])
return 0>1
if(s.length<2)
return 1>0
val v=b[x][y]
b[x][y]='Z'
try{return(-1..1).map{x+it}.flatMap{t->(-1..1).map{y+it}.map{t to it}}.filter{(X,Y)->(x-X)*(x-X)+(y-Y)*(y-Y)==1&&X in b.indices&&Y in b[0].indices&&f(s.substring(1),X,Y)}.any()}finally{b[x][y]=v}}
b.indices.any{x->(0..b[0].size-1).any{f(s,x,it)}}}

Beautified
var x: (Array<Array<Char>>, String) -> Boolean = { b, s ->
    fun f(s: String, x: Int, y: Int): Boolean {
        if (b[x][y] != s[0])
            return 0 > 1
        if (s.length < 2)
            return 1 > 0
        val v = b[x][y]
        b[x][y] = 'Z'
        try {
            return (-1..1).map{ x + it }
                    .flatMap { t -> (-1..1).map{y+it}.map { t to it } }
                    .filter { (X, Y) ->
                        (x - X)*(x - X) + (y - Y)*(y - Y) == 1 &&
                                X in b.indices && Y in b[0].indices &&
                                f(s.substring(1), X, Y) }
                    .any()
        } finally {
            b[x][y] = v
        }
    }
    b.indices.any { x -> (0..b[0].size - 1).any { f(s, x, it) } }
}

Test
var x:(Array<Array<Char>>,String)->Boolean={b,s->fun f(s:String,x:Int,y:Int):Boolean{if(b[x][y]!=s[0])
return 0>1
if(s.length<2)
return 1>0
val v=b[x][y]
b[x][y]='Z'
try{return(-1..1).map{x+it}.flatMap{t->(-1..1).map{y+it}.map{t to it}}.filter{(X,Y)->(x-X)*(x-X)+(y-Y)*(y-Y)==1&&X in b.indices&&Y in b[0].indices&&f(s.substring(1),X,Y)}.any()}finally{b[x][y]=v}}
b.indices.any{x->(0..b[0].size-1).any{f(s,x,it)}}}

data class Test(val board: String, val snake: String, val output: Boolean)

val tests = listOf(
        Test("""01010
            |10101
            |01010
            |10101
            |01010""", "0101010101010101010101010", true),
        Test("""01110
            |01100
            |10010
            |10110
            |01101""", "011111000110100", true),
        Test("""0""", "0", true),
        Test("""10
            |01""", "1010", true),
        Test("""100
            |010
            |001""", "100010001", true),
        Test("""00000
            |00000
            |00000
            |00000
            |00000""", "1", false),
        Test("""10101
            |01010
            |10101
            |01010
            |10101""", "11", false),
        Test("""100
            |010
            |001""", "111", false),
        Test("""10001
            |01010
            |00100
            |01010
            |10001""", "1000100010001000101010100", false)
)

fun main(args: Array<String>) {
    tests.filter {(board, snake, expected) ->
        val boardR = board.trimMargin().lines().map { it.toCharArray().toTypedArray() }.toTypedArray()
        val result = x(boardR, snake)
        result != expected
    }.forEach { throw AssertionError(it) }
    println("Test Passed")
}