text:
Build me a castle Stairway!
You will be given a String consisting of printable ASCII (without newlines). Your task is to build a nice Stairway for my Castle.
How to build a nice Stairway?

First off, you should get all the rotations of the String. For example, the String abcd has the following rotations: abcd, bcda, cdab, dabc (each character is moved to the end until we reach the last character).
We now place each rotation on top of each other:
abcd
bcda
cdab
dabc

We can't really climb on a straight wall, so we must build stairs. That means you should add a number of spaces before each rotation corresponding to its index in the rotation list:
abcd
 bcda
  cdab
   dabc

You also need a Stairway that links to the other side of my castle, so you should build one like below, reversing each rotation and adding some spacing:
abcd      dcba
 bcda    adcb
  cdab  badc
   dabccbad

This is code-golf, hence the shortest code in bytes wins and standard rules for the tag apply.

Test Cases

Input: abcd, Output:
abcd      dcba
 bcda    adcb
  cdab  badc
   dabccbad

Input: aaaa, Output:
aaaa      aaaa
 aaaa    aaaa
  aaaa  aaaa
   aaaaaaaa

Input: Code golf, Output (Notice the spaces):
Code golf                flog edoC
 ode golfC              Cflog edo
  de golfCo            oCflog ed
   e golfCod          doCflog e
     golfCode        edoCflog
     golfCode        edoCflog
      olfCode g    g edoCflo
       lfCode go  og edoCfl
        fCode gollog edoCf

Sandbox

Shouldn't the stairway start going up, and then go down, instead of going down, then up? :P

@StepHen For the purpose of this challenge, it shouldn't :p

Closely related

dabc. -------

05AB1E, 12 bytes
Code:
vDNúsÀ}\».B∞

Uses the 05AB1E encoding. Try it online!
Explanation:
v     }        # Length input times, do.. (N = iteration count)
 DNú           #   Duplicate and prepend N spaces
    sÀ         #   Swap and rotate one to the left
       \       # Discard the top of the stack
        »      # Join the stack by newlines
         .B    # Pad with spaces into a rectangle
           ∞   # Mirror the string

I generated some interesting output...

Jelly, 16 bytes
J’ɓ⁹⁶ẋ;"ṙz⁶Zm€0Y

Try it online!
Of course, -1 using Jonathan Allan's ɓ!

My solution is too similar methinks, here you go: J’ɓ⁹⁶ẋ;"ṙz⁶Zm€0Y (or LḶ for J’)

@JonathanAllan Heh.

Python 3, 85 bytes
x=input()
l=len(x)
for i in range(l):y=x[i:]+x[:i];print(' '*i+y+'  '*(l+~i)+y[::-1])

Try it online!
-1 byte thanks to ovs
-1 byte thanks to Lynn
-4 bytes thanks to p1131

l-i-1 can just be l+~i as ~i == -i-1

' '*(l+~i)*2 equals '  '*(l+~i), which is one byte shorter!

You can save 4 bytes by ommiting the assignment to j and putting the expression directly in the print()! Try it online!

J, 27 bytes
[:(,.|.)i.@#(|.,~' '#~[)"{]

Try it online!

Retina, 47 bytes
.
$.`$* $&$'$`$.'$* ¶
%(`^
$_¶
O$^`.(?=.*$)

¶

Try it online! Explanation: The first stage creates the left stairway by considering each character and creating spaces equal to the current position, then the remainder of the string, then the start of the string, then spaces equal to the remainder of the string. The rest of the script runs over each line just generated in turn. First the line is duplicated, then the characters in the duplicate are reversed, then the line and its duplicate are concatenated.

Haskell, 80 79 bytes
(s:u)#t|q<-(t>>" ")++s:u++t++(u>>" ")=q++reverse q++'\n':u#(t++[s])
u#_=u
(#"")

Try it online!
How it works
(#"")                      -- start with the input string and an empty accumulator

(s:u)#t                    -- let s be the first char and u the rest of the input
                           -- string, and t the accumulator
    |q<-                   -- let q be half of the current line, i.e.
        (t>>" ")++         --   length of t times spaces
        s:u++              --   s and u (aka the input string)
        t++                --   the accumulator
        (u>>" ")           --   length of u times spaces
    = q ++ reverse q ++    -- the current line is q and q reversed
        '\n' :             -- and a newline
        u#(t++[s])         -- and a recursive call with u as the new input
                           -- string and s put at the end of t
_#_=[]                     -- base case: stop if the input string is empty

Edit: Thanks to @Ørjan Johansen for a byte.

u#_=u saves a byte.

@ØrjanJohansen: I first had a list of strings and unlines where u#_=u does not type check and later switched to building a single string ... Thanks!

Charcoal, 23 21 20 bytes
ＦＬθ«ＦＬθ§θ⁺κι↘ＭＬθ←»‖Ｃ

Try it online!
Can probably be golfed more, but I'm posting from the mobile app. Link to the verbose version.

Oh btw if you don't add an explanation at least use -a flag pls

@ASCII-only sorry, I thought the verbose version counted as an explanation.

Wait what nvm didn't see that

I don't think it was true at the time but these days you can fill a polygon with an arbitrary string and get exactly the result you need for 9 bytes: Ｇ→↘←Ｌθθ‖Ｃ.

C (gcc), 126 bytes
i,j,k,l;f(char*s){for(l=strlen(s),i=0;i<l;i++,puts(""))for(j=0;j<4*l-2;j++,putchar(i<=k&k<i+l?s[k%l]:32))k=j<2*l-1?j:4*l-3-j;}

Try it online!

125 bytes: Try it online!

Vyxal, 26 24 23 20 bytes
L(DL‹n-ð$*+mðn*$+,1Ǔ

Try it Online!
Thanks to lyxal for -3 bytes

Try it Online! for 20

Mathematica, 119 bytes
b=StringRotateLeft;j=Table;Column@j[""<>{" "~j~i,b[s=#,i],j["  ",t-i],b[StringReverse@s,-i]},{i,0,t=StringLength@#-1}]&

PHP, 95 bytes
for($e=strlen($s=$argn);$i<$e;$s.=$s[$i],$s[$i++]=" ")echo$t=str_pad($s,2*$e-1),strrev($t),"
";

Run as pipe with -nR or try it online.
breakdown
for($e=strlen($s=$argn);    # import input
    $i<$e;                  # loop length times
    $s.=$s[$i],                 # 2. append current character
    $s[$i++]=" ")               # 3. set current character to space
    echo$t=str_pad($s,2*$e-1),  # 1. print string padded with length-1 spaces
        strrev($t),             #    print reverse
        "\n";                   #    print newline

Pyth, 20 bytes
jms_B.>+.<Qd*\ tlQdl

Try it online!

8th, 173 168 bytes
Code
s:len n:1- ( >r dup s:len n:1- "" ( " " s:+ ) rot times dup 0 r@ s:slice -rot r> -1 s:slice s:+ s:+ dup s:rev swap . . cr null s:/ a:shift a:push "" a:join ) 0 rot loop

Ungolfed version with comments
: shifter \ s -- s
  null s:/     \ convert string into array
  a:shift      \ remove the first item in the array and put it on TOS
  a:push       \ append the former 1st item to array
  "" a:join    \ convert array into string
;

: stairway \ s -- s
  s:len n:1-
  (
    >r                       \ save loop index
    dup                      \ duplicate input string
    s:len n:1-               \ get string length
    "" ( " " s:+ ) rot times \ make filler
    dup                      \ duplicate filler
    0 r@ s:slice             \ make left filler
    -rot                     \ put left filler at proper position
    r> -1 s:slice            \ make right filler
    s:+ s:+                  \ build string ( 1st half of stairway )
    dup s:rev                \ build 2nd half
    swap . . cr              \ print it
    shifter                  \ shift rotate 1st character
  ) 0 rot loop               \ loop from 0 to len(string)-1
;

Usage and examples
ok> "abcd" s:len n:1- ( >r dup s:len n:1- "" ( " " s:+ ) rot times dup 0 r@ s:slice -rot r> -1 s:slice s:+ s:+ dup s:rev swap . . cr null s:/ a:shift a:push "" a:join ) 0 rot loop
abcd      dcba
 bcda    adcb
  cdab  badc
   dabccbad

Or more clearly
ok> "Code golf" stairway
Code golf                flog edoC
 ode golfC              Cflog edo
  de golfCo            oCflog ed
   e golfCod          doCflog e
     golfCode        edoCflog
     golfCode        edoCflog
      olfCode g    g edoCflo
       lfCode go  og edoCfl
        fCode gollog edoCf

Javascript (ES6), 118 bytes
s=>[...s].map((_,y)=>Array(l=(j=s.length)*4-2).fill().map((_,x)=>(x=x<l/2?x:l-x-1)>=y&y+j>x?s[x%j]:" ").join``).join`
`

Example code snippet:

f=
s=>[...s].map((_,y)=>Array(l=(j=s.length)*4-2).fill().map((_,x)=>(x=x<l/2?x:l-x-1)>=y&y+j>x?s[x%j]:" ").join``).join`
`
o.innerText=f("Code golf")
<pre id=o>

Pyth, 19 bytes
jms_BdC.tm+*d;.<QdU

Try it online!

Japt, 22 bytes

l
VÇç +UéZn)+´Vç)ê1Ã·

Leading newline is part of the program.
Try it online!
Run all test cases using my WIP CodePen.
Explanation
Implicit: U = input string. First line is blank to not overwrite U.
Second line implicitly assigns the length (l) of U to V.
Third line:
VÇç +UéZn)+´Vç)ê1Ã·
VoZ{Zç +UéZn)+--Vç)ê1} · Ungolfed
VoZ{                 }   Create array [0, V) and map by...
    Zç                      The current value (Z) times " "
       +UéZn)               Concatenated with U rotated Z times left
             +--Vç)         Concatenated with --V times " ". This decrements V
                   ê1       Palindromize with repeated last char
                       · Join with newlines and implicitly output

Python 2, 85 83 bytes

Thanks @ovs for 2 bytes: l+~i and helped me spot a unwanted space

x=input()
l=len(x)
for i in range(l):r=i*' '+x[i:]+x[:i]+(l+~i)*' ';print r+r[::-1]

Try it online!

APL (Dyalog Unicode), 29 bytes
{w←⍵⋄(⊢,⌽)↑{(-⍵+⍴w)↑⍵⌽w}¨⍳⍴⍵}

Try it online!
Explanation
{w←⍵⋄(⊢,⌽)↑{(-⍵+⍴w)↑⍵⌽w}¨⍳⍴⍵} ⍵ → input
 w←⍵                          assign original input to w
                         ⍳⍴⍵  range from 0 to length of ⍵
           {           }¨     map range to function, loop var i
                    ⍵⌽w       input rotated i characters
            (-⍵+⍴w)           i + length of input, negated
                   ↑          take that much from the rotated string
                              (prepends spaces)
          ↑                   mix the array to create one side of the pattern
     (⊢,⌽)                    append the reverse of the matrix to itself

Perl 5 + -lF -M5.10.0, 57 bytes
@F=@F[1..$#F,!say$"x$-,@F,"  "x($#F-$-++),reverse@F]for@F

Try it online!
Explanation
Using -F (specifying the -F switch without an argument, -F controls how a string is split into @F) the input is split into a list of singular chars. for each char in @F, @F is then set to the slice of index 1 to $#F (which is the last index in @F) followed by the item at index !say... which equates to 0. The effectively shifts the list content backwards by one index each iteration. say is called within the indexing operation to produce the output before the list is re-indexed and is provided with $"x$- ($-, which is a special int only variable that is preinitialised to 0, copies of $", which is the special list separator variable, preinitialised to space) followed by @F, followed by "  "x($#F-$-++) (two spaces repeated by the final index of @F with the current value of $- times - $- is post-incremented here so will increase on the next iteration), finally followed by the reverse of @F.

Python 2, 82 bytes
x=input()
i=l=-len(x)
while i:s=x[i:]+x[:i];i+=1;print' '*(~l+i)+s+'  '*-i+s[::-1]

Try it online!

Pip -l, 21 bytes
aMERF:sX#aRA_a@Y_+,#a

Try it online!
Explanation
                       a is command-line argument; s is space (implicit)
aME                    Map this function to each number in 0 .. len(a)-1:
                  ,#a   Range(len(a))
                _+      Add the function's argument: Range(_, _+len(a))
               Y        Yank that range (just to get the precedence right)
             a@         Use the range as the (modular) indices to slice into the string
      sX#a              Get a string of spaces of the same length as the input string
          RA_           Replace the space at index _ with the slice calculated above
   RF:                  Reflect the string, appending its reverse to it
                       Output the result list one item per line (-l flag)

Japt -R, 15 bytes
¬£éYn)iYçÃú mê1

Try it
¬£éYn)iYçÃú mê1     :Implicit input of string U
¬                   :Split
 £                  :Map each character at 0-based index Y
  é                 :  Rotate U right
   Yn               :    -Y times
     )              :  End rotate
      i             :  Prepend
       Yç           :    Space repeated Y times
         Ã          :End map
          ú         :Right pad with spaces to the length of the longest
            m       :Map
             ê1     :  Mirror
                    :Implicit output joined with newlines


text:
Stream of Letters to Words
Given a string containing only letters (case-insensitive), split it into words of uniformly random lengths, using the distribution below, with the exception of the last word, which can be of any valid length (1-10). Your output is these words, as a space-separated string ("test te tests"), an array of strings (["test","te","tests"]), or any other similar output format.
Word Length Distribution
Word Length - Fractional Chance / 72 - Rounded Percentage
1 - 2 / 72 - 2.78%
2 - 14 / 72 - 19.44%
3 - 16 / 72 - 22.22%
4 - 12 / 72 - 16.67%
5 - 8 / 72 - 11.11%
6 - 6 / 72 - 8.33%
7 - 5 / 72 - 6.94%
8 - 4 / 72 - 5.56%
9 - 3 / 72 - 4.17%
10 - 2 / 72 - 2.78%

Your odds do not need to match exactly - they can be off by 1/144th, or .69%, in either direction (but obviously they still must sum up to 72/72 or 100%).
Data roughly guessed from the fourth page, first figure of this paper.
Test Cases with Sample Output
Behavior on very short (length < 11) test cases is undefined.
Note that I created these by hand, so they may or may not follow the uniform distribution above.
abcdefghijklmnopqrstuvwxyz
abcd efgh i jklmnopq rs tu vwx yz

thequickbrownfoxjumpedoverthelazydog
t heq uick brown fo xj ump edo vert helazydog

ascuyoiuawerknbadhcviuahsiduferbfalskdjhvlkcjhaiusdyfajsefbksdbfkalsjcuyasjehflkjhfalksdblhsgdfasudyfekjfalksdjfhlkasefyuiaydskfjashdflkasdhfksd
asc uyoi uawer k nb a dhcviua hsid ufe r bfa lskd jhv lkcj haius dy faj se fbks dbfkals jcuyasjehf lkjh falk sd blhsgdf asudyfekjf alk sdjfhlk asefyu iaydskfja shdflk as dhf ksd

This is code-golf, so shortest answer in bytes wins.

Sandbox

Can the last word be an empty string?

@rahnema1 you mean in an array output?

Yes, last element of the array output.

@rahnema1 sure, since if you join the array on space you'd just have a trailing space, which I would allow.

Jelly, 28 bytes
“¤Œæ×¿®¬©¥¤‘Jẋ"$FẋLẊ‘1¦+\Ṭœṗ

A monadic link taking a list and returning a list of lists.
Try it online! (the footer separates the resulting list of lists with spaces)
How?
Uses all the percentages in the distribution rounded to their nearest integer (thus being within the 0.69% allowed thresholds).
“¤Œæ×¿®¬©¥¤‘Jẋ"$FẋLẊ‘1¦+\Ṭœṗ - Link: list (of characters), s
“¤Œæ×¿®¬©¥¤‘                 - code page indexes = [3,19,22,17,11,8,7,6,4,3]
               $             - last two links as a monad:
            J                -   range of length = [1, 2, 3, 4, 5,6,7,8,9,10]
              "              -   zip with:
             ẋ               -     repeat list = [[1,1,1],...,[9,9,9,9],[10,10,10]]
                F            - flatten (into one list of length 100)
                  L          - length of s
                 ẋ           - repeat list (one list of length 100*length(s) with the
                             -              correct distribution of integer lengths)
                   Ẋ         - shuffle
                      ¦      - sparse application of:
                    ‘        -   increment
                     1       -   to indexes: 1 (offset indexes for the partition below)
                        \    - cumulative reduce by:
                       +     -   addition (e.g. [4,4,7,1,...] -> [4,8,15,16,...])
                         Ṭ   - untruth (yield a list with 1s at those indexes (1 indexed)
                          œṗ - partition s at truthy indexes (note: excess ignored)

Your script may theoretically output the list whose first element is empty string. Not sure if it is allowed by the question.

@ThePirateBay yeah I actually just noticed this myself - I need to add 1 to the first element of my cumulative lengths; will update shortly to fix.

Fixed, and explanation added (can't ask to allow the leading space as the 1st word length would actually be using the wrong distribution).

PHP, 94 bytes
for(;$c=$argn[$k++];print$c." "[--$e])if(!$e)for($r=rand(0,71);$r>ord(x^"ywgSKAF:=?"[$e++]););

Run as pipe with -nR or try it online.
breakdown
for(;$c=$argn[$i++];            # loop $c through string
    print$c                         # 2. print current character,
        ." "                        # 4. if remaining length is 0, print space
        [--$e]                      # 3. decrement remaining length
    )
    if(!$e)                         # 1. if remaining length is 0,
        for($r=rand(0,71);              # get random value from 0 to 71
            $r>ord(x^"ywgSKAF:=?"[$e++])    # and increment $e while $r is > probability
        ;);

Note: ywgSKAF:=? represents the increasing probabities -1: [1,15,31,43,51,57,62,66,69,71]

I wonder: Would the probabilities change if I´d call rand() for every comparison? If not, I could save 5 bytes.

They would certainly change, e.g. the probability of length 2 would be 70/72*16/72, which is higher than 14/72.

@ØrjanJohansen Something told me that would happen. Pity: That way I´d waste at least 5 bytes.

This is not the first time I've seen a supposedly complete PHP solution that didn't start with <? or <?php. Run as a standalone program, PHP needs that. Or am I missing something?

@manassehkatz You are missing Run as pipe with -nR. I.e. this code is supposed to be a parameter to php, not a file. Use echo <input> | php -nR '<code>' on the command line to execute.

@Titus Aha! I checked and the other 2 where I commented on this did NOT have -nR mentioned. I saw a rule that command line otpions should count as extra bytes, but you show the count as 94, which is the actual code length. Is there an exemption for this?

@manassehkatz https://codegolf.meta.stackexchange.com/questions/2424/running-php-with-r-instead-of-code-tags Hmm seems I´d have to update a lot of byte counts. Will consider it for future posts.

The reality is that, unfortunately for those of us who love PHP, PHP rarely comes close to lowest on Code Golf. But I see the extra byte(s) for command line or compiler options included with other languages and "fair is fair". Arguably when a PHP entry is set up as a function() you could say that is the definition of a function (as opposed to a full program) and then the extra characters would not be needed, but most of the time a full program ends up shorter.

Octave, 108 bytes
@(s)mat2cell(s,1,[k=(w=repelems(1:10,[1:10;'AMOKGEDCBA'-63])(randi(72,1,n=nnz(s))))(cumsum(w)<=n) n-sum(k)])

Try it online!
*Takes the string as input and outputs an array of strings.
*The last element of the output may be an empty string.

Python 2, 154 150 147 145 bytes
Allright, this is my first attempt on code golf. Straight up with the code:
import numpy.random as r
def f(s):
 i=0
 while i<len(s):
    i+=r.choice(11,p=[x/72. for x in [0,2,14,16,12,8,6,5,4,3,2]])
    s=s[:i]+' '+s[i:]
    i+=1
 return s

The second indent is by a tab char as you can see in my TIO version:
Try it Online.
What I do is adding a space in the string according to the given distribution. I veryfied my distribution by using:
import collections
dist = r.choice(11,100000,p=[x/72. for x in [0,2,14,16,12,8,6,5,4,3,2]])
print collections.Counter(dist)

Which gave me:
Word Length - Rounded Percentage as asked - Rounded Percentage as counted
1 - 2.78% - 2.794%
2 - 19.44% - 19.055%
3 - 22.22% - 22.376%
4 - 16.67% - 16.638%
5 - 11.11% - 11.246%
6 - 8.33% - 8.362%
7 - 6.94% - 7.063%
8 - 5.56% - 5.533%
9 - 4.17% - 4.153%
10 - 2.78% - 2.780%

Which I think is correct enough. I then repeat that process of adding a space until the length of my string is succeeded. I also increment my position index by one after adding a space. I hope someone can help me golf this line out but I did not see how to get it out without falsifying the first space.
As I see my text I recognice that I have to learn alot about this Site. Could someone link me a guide how to use the Stackoverflow answer function in the comments so I can learn for my next posts.

Edit:
Apperently while rereading my post I did figure out a way to get rid of the i+=1. So i saved 4 bytes by doing that. The new code looks like this:
import numpy.random as r
def f(s):
 i=-1
 while i<len(s):
  i+=r.choice(11,p=[x/72. for x in[0,2,14,16,12,8,6,5,4,3,2]])+1
  s=s[:i]+' '+s[i:]
 return s

Try it online!

Edit:
I figured out that i can remove some linebreaks.
import numpy.random as r
def f(s):
 i=-1
 while i<len(s):i+=r.choice(11,p=[x/72. for x in[0,2,14,16,12,8,6,5,4,3,2]])+1;s=s[:i]+' '+s[i:]
 return s

Edit:
I modyfied my import and placed the definition of i inside the function.
from numpy.random import*
def f(s,i=-1):
 while i<len(s):i+=choice(11,p=[x/72. for x in[0,2,14,16,12,8,6,5,4,3,2]])+1;s=s[:i]+' '+s[i:]
 return s

Try it online!

Welcome on Programming Puzzles & Code Golf! Nice first post! I've edited your answer a bit to improve the formatting (title, syntax highlight), you can have a look at what changed to see the commands for your future posts. (I don't have any link to give you sadly, but hopefully someone else will)

Thanks for the welcome and formatting my text. This helped me out and I did already use it in my Edit.

Python 2, 155 bytes
from random import*
def f(s):
 i=sum([[i+1]*[2,14,16,12,8,6,5,4,3,2][i]for i in range(10)],[])[randint(0,71)]
 return s if len(s)<11else s[:i]+' '+f(s[i:])

Try it online!

Mathematica, 164 bytes
(s=Length[c=Characters@#];t=0;l={};While[t<s,If[t+(r=RandomChoice[{2,14,16,12,8,6,5,4,3,2}->Range@10])<=s,l~AppendTo~r];t=Tr@l];""<>#&/@FoldPairList[TakeDrop,c,l])&

takes a string as input
outputs array of strings

Charcoal, 43 39 bytes
ＦθＦ⁺¹Ｉ‽⪫Ｅχ×Ｉκ⌕α§”v↷£o8″!”κω⊞υ⎇κω Ｆθ⁺ι⊟υ

Try it online! Link is to verbose version of code. Outputs a trailing space if the last word was the exact size randomly chosen.

Yeah it does seem too long :/ Any idea for new features that would shorten it?

@ASCII-only I can't think of a good way of generating the probability table, which is already over 50% of the code. It would be nice if I didn't have to work around Assign(Slice(q, i), q); not working though.

That would work, just it's ambiguous, not entirely sure of the best way to fix that, sorry

Woah so much nesting

@ASCII-only Who cares if it saves bytes?

Perl 5, 107 bytes
@B=((1,10,9,5,2)x2,(2,3,4)x12,(5,6)x6,7,(3,7,8)x4,9);while(10<length){$i=$B[rand 72];s/.{$i}//;print"$& "}

Try it online!
106 bytes of code +1 for -p

Welcome on the site! Nice to see a new Perl golfer, great answer! (you can still save a few bytes though). Also, I recommend adding some explanations, so non-Perl people have an idea of how you did it (and even for Perl coder, it saves a bit of time), but that's not mandatory and just up to you.

Dyalog APL, 90 bytes
{k←⍵⋄{' '~⍨(2⊃⍵)↓k↑⍨⊃⍵}¨(↓(o[1;2]),0),↓o←1↓⍉2(1-⍨≢⍵)⍴+\((2 14 16 12 8,⌽1+⍳5)\⍳10)[72?⍨≢⍵]}

Try it online! Hit Run a few times to see how it changes.
How?
72?⍨≢⍵ - roll 72 sided dice length of input times
[...] - index inside
(2 14 16 12 8,⌽1+⍳5)\⍳10 - expand range of 10 by 2 14 16 12 8 6 5 4 3 2 (to create weighted random)
+\ - cummulative sum
⍉2(1-⍨≢⍵)⍴ - shape as a zipped table x y z → z x, x y, y z
o←1↓ - drop first element
(↓(o[1;2]),0),↓o - encase with its first coordinate paired with 0
¨ - for each pair (x, y)
(2⊃⍵)↓k↑⍨⊃⍵ - take input from index x to y
' '~⍨ - and remove spaces

Ruby, 96+1 = 97 bytes
Uses the -p flag.
i=0
m=[3,19,22,17,11,8,7,6,4,3].flat_map{|k|[i+=1]*k}
i=0
$_[i-1,0]=' 'while~/$/+1>i+=1+m.sample

Try it online!

><>, 168 152 bytes
<v?(0:i
~/<r
/x\/oo \
012\oo~\!/ !ox\
\v/:1=?^?\ooo>>
 x^
v\:1\/>> o
|/o\=\x^!/
voo/? >x
v\o~/ v_
>" "\?\x>xoo\
^oooooo<<< \
^.22/ \>x!/xv
^ooooooo_o<<<

Try it online, or watch it at the fish playground!
Randomness is tricky in ><>: there's only one random instruction, x, which sets the fish's direction to either up, down, left or right. This is a complicated program, so here's a colour-coded diagram to help you:

I tried to split up the probabilities into chunks so that the probabilities within and between the chunks were fairly simple (preferring, say, 1/3 to 25/72). I did this as follows:

The fish starts at the grey bit of the code (X). This is fairly standard ><> code to read in all of the input. It gets more interesting, so let's move on.
Next, the fish comes to the light and dark green sections (Y). You may notice from the probability tree that the three major branches each sum to 1/3, and that each of these branches splits into a 2/3 sub-branch and a 1/3 sub-branch. The green sections of code cover these two levels of the tree. First, we pick a random number out of 0, 1, 2 with equal chance of each, in the top lobe of the light green bit. We can simulate a 1/3 chance using the four-way instruction x by cutting off one of the exits so that it just redirects the fish back to the x — then there are only three escape routes from the x, and by symmetry they have equal probabilities.
The next x, a little below this one, sends the fish to the ^ next to it with 2/3 chance — note that the fish wraps around if it swims left from the x — and down to a \ with 1/3 chance. The fish then swims along one of the two tails of the light green section. These tails are functionally the same: each checks if we pushed 0, 1 or 2 earlier, and branches out accordingly. And this completes the first two levels of the tree.
The next six sections (A–F), in essence, use more xs to branch the fish further, and then use some number of os to print a number of letters from the input. These sections range from straightforward (e.g. dark blue, C, which just prints three letters) to, well, not so straightforward (e.g. orange, D, which needs two xs to simulate a 3/8–5/8 split, printing letters in multiple stages). The details of these are left as an exercise. (I'm particularly pleased with yellow, E, which sends the fish in a loop-the-loop!)
After each of these branches, the fish ultimately reaches the pink section (Z). This draws all the branches back together, prints a space, then finally makes the fish jump to position (2,2) in the grid and start again at the first x.

In case the "it's complicated" explanation above doesn't convince you that this gives the correct probabilities, I also tested this on a length 65,000 input string (64 KiB, only 13 seconds in TIO!), and the resulting distribution of word lengths was
{{1,0.027377},{2,0.191237},{3,0.226599},{4,0.164128},{5,0.113064},{6,0.0818627},{7,0.0703885},{8,0.0543515},{9,0.0426089},{10,0.0283835}}

These probabilities are at most 0.0044 away from the expected probabilities.

source: Stack Exchange

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

sort: votes


text:
Verify Topology
Challenge
Given a set T of subsets of a finite set S={1,2,3,...,n}, determine whether T is a topology or not.
Explanation
The powerset P(S) of some set S is the set of all subsets of S. Some examples:
S = {}, P(S) = {{}}
S = {1}, P(S) = {{}, {1}}
S = {1,2}, P(S) = {{}, {1}, {2}, {1,2}}
S = {1,2,3}, P(S) = {{}, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}}

A topology T on the set S is a subset of P(S) with following properties:

{} is in T and S is in T
If A and B are in T then so is their intersection A ∩ B
If A and B are in T then so is their union A ∪ B *

* This definition is not quite correct, but it is true for finite sets, which is sufficient for the purposes of this challenge. The actual axiom would allow for infinite unions as well, but that is irrelevant in the finite case.
Details

You can assume that S = {1,2,...,n} (or alternatively S = {0,1,...,n}) where n is the largest integer that appears in the sets of T.
The input format is flexible: You can use a string, a list of lists or set of lists or any similar format your langauge can handle. You can also use sets like S = {0,1,...,n} if it is more convenient.
The output must be truthey or falsey.
You are allowed to take n (or alternatively n+1 or n-1) as an additional input.
If you work with ordered lists, you can assume that the numbers within a set are sorted. You can also assume that the list has a certain order (e.g. lexicographical.
As we represent sets, you can assume that no two entries of their list-representation are equal.

Examples
Topologies
{{}}  over {}
{{},{1}} over {1}
P(S) over S (see in the explanation)
{{},{1},{1,2}} over {1,2}
{{},{1},{2,3},{1,2,3}} over {1,2,3}
{{1}, {1,2,3}, {1,4,5,6}, {1,2,3,4,5,6}, {}, {2,3}, {4,5,6}, {2,3,4,5,6}}
{{}, {1}, {2,3}, {2}, {4,5,6}, {5,6}, {5}, {2,5,6}, {2,5}, {1,5}, {1,2,3,4,5,6}, {1,2,3}, {1,2}, {1,4,5,6}, {1,5,6}, {1,2,5,6}, {2,3,4,5,6}, {2,3,5,6}, {2,3,5}, {1,2,3,5}, {2,4,5,6}, {1,2,5}, {1,2,3,5,6}, {1,2,4,5,6}}
{{}, {1}, {1,2}, {1,2,3}, {1,2,3,4}, {1,2,3,4,5}, {1,2,3,4,5,6}, {1,2,3,4,5,6,7}, {1,2,3,4,5,6,7,8}, {1,2,3,4,5,6,7,8,9}}
{{}, {1}, {1,2,3}, {1,2,3,4,5}, {1,2,3,4,5,6,7}, {1,2,3,4,5,6,7,8,9}}

non-Topologies
{{1}} because {} is not contained
{{},{2}} because {1,2} is not contained
{{},{1,2},{2,3}} because the union {1,2,3} is not contained
{{},{1},{1,2},{2,3},{1,2,3}} because the intersection of {1,2} and {2,3} is not contained
{{},{1},{2},{3},{1,2},{2,3},{1,2,3}} because the union of {1} and {3} is not contained
{{}, {1}, {2,3}, {2}, {4,5,6}, {5,6}, {5}, {2,5,6}, {2,5}, {1,5}, {1,2,3,4,5,6}, {1,2,3}, {1,2}, {1,4,5,6}, {1,5,6}, {1,2,5,6}, {2,3,4,5,6}, {2,3,5,6}, {2,3,5}, {2,4,5,6}, {1,2,5}, {1,2,3,5,6}, {1,2,4,5,6}} because {1,2,3,5} is missing
{{}, {1}, {2}, {1,2,3}, {1,2,3,4,5}, {1,2,3,4,5,6,7}, {1,2,3,4,5,6,7,8,9}} because {1,2} is missing

It seems like a lot of the answers to this question would on the input {{}, {2}} because they don't explicitly check that S is in the set while for that input, S is implicitly assumed to be {1,2}. Is this a valid reading of the specs, or am I missing something?

@Carmeister Sorry for the confusion, yes your interpretation is correct!

Can input be a binary matrix where each row is a set, each column is an element, and the value indicates whether the element is in the set?

Yes I think that is acceptable.

Since T is a set, I think it's reasonable to assume that no subset in the input is repeated (i.e. {{}, {1,2}, {1,2}} is not valid input). Can you clarifiy that in the challenge, either affirmatively or negatively?

I'm using an ordered list as input. May I assume a specific ordering on the input list (the overall list)?

If I choose to work on the assumption that S = {0,1,...,n} and to take n+1 as an additional input, what value will be supplied as the additional input for the first test case? 0?

@PeterTaylor I think -1 would be reasonable, in order to produce an empty base set S. But I see that this might be cumbersome, so I think it is ok to ignore this pathological case and assume that |S|>0

@isaacg Yes that should be ok!

@LuisMendo Yes you can assume that you do not get the same element of a set twice in its representation.

Python 2, 117 99 97 91 bytes
n,x=input();sum(set.union(*x))!=n*-~n/2>q
[map(x.index,(i-i,i|j,i&j))for i in x for j in x]

Try it online!
Output is via exit code

Mathematica, 87 73 66 63 bytes
Outer[{#⋂#2,#⋃#2}&,#,#,1]~Flatten~2⋃{{},Range@#2}==#⋃#&

Takes [T, n] as input.
Explanation
{#⋂#2,#⋃#2}&

Function that returns the intersection and the union of the inputs
Outer[ ... ,#,#,1]

Map that function onto the input list at level 1.
... ~Flatten~2

Flatten the result (the Outer part returns a bunch of nested Lists).
... ⋃{{},Range@#2}

Take the union between the flattened list and {{}, S}. This removes duplicates and adds {} and S to the resulting list.
... ==#⋃#

Check whether the list from above is equal to the sorted version of the input.

Haskell, 95 89 74 78 bytes
import Data.List
t#n=all(`elem`t)$sort<$>[1..n]:[]:([union,intersect]<*>t<*>t)

Try it online!
Explanation:
                              ([union,intersect]<*>t<*>t) -- create all unions & intersections
                    [1..n]:[]:                            -- add the empty list and the full list
             sort<$>                                --sort them all
                                -- (as 'union' does not necessarily produce sorted outputs)
all(`elem`t)$                   -- check whether they are all already contained

What about [[],[2]]? It's a topology, but not over the implied ("You can assume that...") set.

@ChristianSievers corrected!

MATL, 38 bytes
!t~hXAs1>GXBXH2Z^!"@Z}Z|1MZ&hHm]vAGn~+

Input is a binary matrix where each row is a set, each column is an element, and each entry indicates membership. For example, {{},{1},{1,2}} is expressed as [0 0;1 0;1 1]. Use the linked Octave program to convert to this format.
Try it online! Or verify all test cases.
Explanation
!        % Implicit input. Transpose
t~       % Push a negated copy
h        % Horizontally concatenate both matrices
XA       % All: true for columns containing only 1
s        % Sum
1>       % Does it exceed 1? If so, both the empty set and the total
         % set are in the input
G        % Push input again
XB       % Convert each row from binary to decimal. This gives a column
         % vector of numbers that encode each set's contents. Union and
         % intersection will be done as bitwise XOR and AND
XH       % Copy to clipboard H
2Z^!     % Cartesian square transposed: gives all pairs of numbers as
         % columns of a matrix
"        % For each column
  @      %   Push current column
  Z}     %   Split into the two numbers
  Z|     %   Bitwise XOR
  1M     %   Push the two numbers again
  Z&     %   Bitwise AND
  h      %   Concatenate the two results horizontally
  Hm     %   Are they members of the vector of encoded sets? This gives
         %   a row vector with the two results
]        % End
v        % Concatenate all stack contents into a vertical vector
A        % Does it only contain ones? This is the main result: true iff
         % input is a non-empty topology. The empty input gives false,
         % and so it needs to be special cased
G        % Push input again
n~       % Is it empty?
+        % Add thw two results. Implicit display

D: your program takes up more space than your title!

Python 2, 92 71 122 bytes

Thanks a lot to @ovs for a heavy 19 bytes reduction: & and | shorthands for set operations.
Thanks @notjagan for 5 bytes
Thanks to @ovs for 2 bytes: set() as i-i

Lambda that takes a list of sets as input, and returns True/false. Simply checks if there is an empty set and the union and intersection of each sets(two sets iterated as i and j) exists in the given list of sets.
lambda x:x.sort()or all(k in x[-1]for k in range(1,max(x[-1])))and all(a in x for i in x for j in x for a in[i-j,i|j,i&j])

Try it online!

71 bytes

@ovs Thanks a lot, didn't know the shorthands!

@ovs I am actually explicitly converting the list-items from the input() to set() in the footer.

66 bytes.

@flawr should be fixed now...

You can replace set() with i-i or i^i

@notjagan Doesn't that return True for the empty set/list, which is not a topology?

@ovs This also returns True for the empty list.

Pyth, 24 23 bytes
q@aasm,@Fd{Ssd*QQYJUEyJ

Test suite
This program takes input as an ordered list of ordered lists. The inner lists must be in ascending order and the order list must be sorted by length then lexicographically. I have confirmed that this is an allowed input format. Numbers start at 0, and N+1 is also taken as input.
As for how it works, we filter out anything not in P(S), then add S, [], the intersection of every pair and the union of every pair, deduplicate, and check that the result is equal to the input.

CJam (23 bytes)
{[,M2$2m*{_~&\~|$}/]^!}

Online test suite. This is an anonymous block (function). I assume S = {0,1,...,n}; the block takes an array of sorted arrays and n+1 as parameters and leaves 0 or 1 on the stack. In the case {{}} the code and test framework assume that n+1 = 0.

Axiom, 358 bytes
t(a,s)==(aa:=sort(removeDuplicates(a));ss:=sort(removeDuplicates(s));a:=sort(a);s:=sort(s);a~=aa or s~=ss=>false;a:=map(sort, a);~member?([],a) or ~member?(s,a)=>false;for x in a repeat(for j in x repeat if ~member?(j,s) then return false;for y in a repeat if ~member?(sort(setIntersection(x,y)),a) or ~member?(sort(setUnion(x,y)),a) then return false);true)

ungolfed and results:
-- all the List have to be sorted because in list [1,2]~=[2,1]
-- So here "set" means: "List without duplicate, sorted with sort() function"
-- Return true if
-- 1) a,s are set for above definition
-- 2) a is in P(s)
-- 3) s,[] are in a
-- 4) for all x and y in a => xUy is in a and x intersect y is in a
t1(a:List List INT, s:List INT):Boolean==
    aa:=sort(removeDuplicates(a));ss:=sort(removeDuplicates(s))
    a :=sort(a);                  s :=sort(s)
    a~=aa          or s~=ss        =>false   -- they are not sets but list with element duplicate
    a:=map(sort, a)                          -- subset of a has to be sorted too
    ~member?([],a) or ~member?(s,a)=>false
    for x in a repeat
       for j in x repeat if ~member?(j,s) then return false
       for y in a repeat if ~member?(sort(setIntersection(x,y)),a) or ~member?(sort(setUnion(x,y)),a) then return false
    true

(4) -> t([[]], [])
   (4)  true
                                                            Type: Boolean
(5) -> t([[],[1]], [1])
   (5)  true
                                                            Type: Boolean
(6) -> t([[],[1],[2,1]], [1,2])
   (6)  true
                                                            Type: Boolean
(7) -> t([[],[1],[2,3],[1,2,3]], [3,1,2])
   (7)  true
                                                            Type: Boolean
(8) -> t([[1], [1,2,3], [1,4,5,6], [1,2,3,4,5,6], [], [2,3], [4,5,6], [2,3,4,5,6]], [1,2,3,4,5,6])
   (8)  true
                                                            Type: Boolean
(9) -> t([[], [1], [2,3], [2], [4,5,6], [5,6], [5], [2,5,6], [2,5], [1,5], [1,2,3,4,5,6], [1,2,3], [1,2], [1,4,5,6], [1,5,6], [1,2,5,6], [2,3,4,5,6], [2,3,5,6], [2,3,5], [1,2,3,5], [2,4,5,6], [1,2,5], [1,2,3,5,6], [1,2,4,5,6]], [1,2,3,4,5,6])
   (9)  true
                                                            Type: Boolean
(10) -> t([[], [1], [1,2], [1,2,3], [1,2,3,4], [1,2,3,4,5], [1,2,3,4,5,6], [1,2,3,4,5,6,7], [1,2,3,4,5,6,7,8], [1,2,3,4,5,6,7,8,9]], [1,2,3,4,5,6,7,8,9])
   (10)  true
                                                            Type: Boolean
(11) -> t([[], [1], [1,2,3], [1,2,3,4,5], [1,2,3,4,5,6,7], [1,2,3,4,5,6,7,8,9]], [1,2,3,4,5,6,7,8,9])
   (11)  true
                                                            Type: Boolean
(2) -> t([[1]], [1])
   (2)  false
                                                            Type: Boolean
(4) -> t([[],[2]], [1,2])
   (4)  false
                                                            Type: Boolean
(5) -> t([[],[1,2],[2,3]], [1,2,3])
   (5)  false
                                                            Type: Boolean
(6) -> t([[],[1],[1,2],[2,3],[1,2,3]], [1,2,3])
   (6)  false
                                                            Type: Boolean
(7) -> t([[],[1],[2],[3],[1,2],[2,3],[1,2,3]] , [1,2,3])
   (7)  false
                                                            Type: Boolean
(8) -> t([[], [1], [2,3], [2], [4,5,6], [5,6], [5], [2,5,6], [2,5], [1,5],[1,2,3,4,5,6], [1,2,3], [1,2], [1,4,5,6], [1,5,6], [1,2,5,6], [2,3,4,5,6], [2,3,5,6], [2,3,5], [2,4,5,6], [1,2,5], [1,2,3,5,6], [1,2,4,5,6]], [1,2,3,4,5,6])
   (8)  false
                                                            Type: Boolean
(9) -> t([[], [1], [2], [1,2,3], [1,2,3,4,5], [1,2,3,4,5,6,7], [1,2,3,4,5,6,7,8,9]] , [1,2,3,4,5,6,7,8,9])
   (9)  false
                                                            Type: Boolean
(10) -> t([[], [1], [2,3], [2], [4,5,6], [5,6], [5], [2,5,6], [2,5], [1,5],[1,2,3,4,5,6], [1,2,3], [1,2], [1,4,5,6], [1,5,6], [1,2,5,6], [2,3,4,5,6], [2,3,5,6], [2,3,5], [2,4,5,6], [1,2,5], [1,2,3,5,6], [1,2,4,5,6]], [1,2,3,4,5,6])
   (10)  false
                                                            Type: Boolean

Python, 87 bytes
lambda n,T:(set(range(n))in T)&all(x in T for i in T for j in T for x in [i-i,i&j,i|j])
Takes the number n and a list of sets T as input.

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

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


text:
Secret Message Part 1, Elements
You and your friend want to send each other secret messages.  However, because you are conspiracy theorists and think that the government has a quantum computer that can crack any standard encryption.  Therefore, you are inventing one of your own.  The first step of this is as follows: taking an input string, you check if all the letters can be represented by the symbols for the elements of the periodic table (case insensitive).  If they can be, you replace each section with the name of the element the symbol represents.  If all letters cannot be replaced in this way, you simply use the original string.
Your Task:
You are to write a program or function that encodes a message, as outlined previously.  Remember that if your program fetches data from an outside source, the size of the outside source must be added to the byte count (this loophole).  The elements and symbols used are here:
H   Hydrogen
He  Helium
Li  Lithium
Be  Beryllium
B   Boron
C   Carbon
N   Nitrogen
O   Oxygen
F   Fluorine
Ne  Neon
Na  Sodium
Mg  Magnesium
Al  Aluminum
Si  Silicon
P   Phosphorus
S   Sulfur
Cl  Chlorine
Ar  Argon
K   Potassium
Ca  Calcium
Sc  Scandium
Ti  Titanium
V   Vanadium
Cr  Chromium
Mn  Manganese
Fe  Iron
Co  Cobalt
Ni  Nickel
Cu  Copper
Zn  Zinc
Ga  Gallium
Ge  Germanium
As  Arsenic
Se  Selenium
Br  Bromine
Kr  Krypton
Rb  Rubidium
Sr  Strontium
Y   Yttrium
Zr  Zirconium
Nb  Niobium
Mo  Molybdenum
Tc  Technetium
Ru  Ruthenium
Rh  Rhodium
Pd  Palladium
Ag  Silver
Cd  Cadmium
In  Indium
Sn  Tin
Sb  Antimony
Te  Tellurium
I   Iodine
Xe  Xenon
Cs  Cesium
Ba  Barium
La  Lanthanum
Ce  Cerium
Pr  Praseodymium
Nd  Neodymium
Pm  Promethium
Sm  Samarium
Eu  Europium
Gd  Gadolinium
Tb  Terbium
Dy  Dysprosium
Ho  Holmium
Er  Erbium
Tm  Thulium
Yb  Ytterbium
Lu  Lutetium
Hf  Hafnium
Ta  Tantalum
W   Tungsten
Re  Rhenium
Os  Osmium
Ir  Iridium
Pt  Platinum
Au  Gold
Hg  Mercury
Tl  Thallium
Pb  Lead
Bi  Bismuth
Po  Polonium
At  Astatine
Rn  Radon
Fr  Francium
Ra  Radium
Ac  Actinium
Th  Thorium
Pa  Protactinium
U   Uranium
Np  Neptunium
Pu  Plutonium
Am  Americium
Cm  Curium
Bk  Berkelium
Cf  Californium
Es  Einsteinium
Fm  Fermium
Md  Mendelevium
No  Nobelium
Lr  Lawrencium
Rf  Rutherfordium
Db  Dubnium
Sg  Seaborgium
Bh  Bohrium
Hs  Hassium
Mt  Meitnerium
Ds  Darmstadtium
Rg  Roentgenium
Cn  Copernicium
Nh  Nihonium
Fl  Flerovium
Mc  Moscovium
Lv  Livermorium
Ts  Tennessine
Og  Oganesson

Input:
A string to be encoded.  You may take this in all caps or lowercase if you wish, as long as you specify that requirement in your answer.
Output:
The string, encoded as outlined previously if possible.
Examples:
Hi!                --> HydrogenIodine!
This is an example --> This is an example
Neon               --> NeonOxygenNitrogen
Snip               --> SulfurNitrogenIodinePhosphorus OR TinIodinePhosphorus
Nag                --> NitrogenSilver

Scoring:
This is code-golf, shortest code in bytes wins!

Comments are not for extended discussion; this conversation has been moved to chat.

Can everyone just take the elements and symbols as a dictionary as input because as of now, this challenge is basically all about compressing that?

@Dopapp, no, as that would make the answers that have already been submitted, and that people have worked very hard on, completely uncompetitive.  Compressing the elements was always going to be most of the challenge anyway.

Mathematica, 404 (239) bytes
S="";l=ToLowerCase;e=ElementData;Unprotect[e];a="Abbreviation";n="Name";e[113,a]="Nh";e["Nh",n]="Nihonium";e[115,a]="Mc";e["Mc",n]="Moscovium";e[117,a]="Ts";e["Ts",n]="Tennessine";e[118,a]="Og";e["Og",n]="Oganesson";r=StringReplace;A=Reverse@SortBy[Table[e[j,a],{j,118}],StringLength];If[StringFreeQ[r[l@S,Table[l@A[[j]]->"",{j,118}]],Alphabet[]],r[l@S,Table[l@A[[j]]->Capitalize@e[A[[j]],n],{j,118}]],S]

Using Mathematica's built-in database to fetch element names and their abbreviation. Input can be mixed lower and upper case and is stored in the variable S. The output is the expression's result, it is not explicitly printed.
The at this time fully working code takes up 404 bytes, as Mathematica's built-in chemical database is a bit behind. ElementData[118, "Name"] returns ununoctium instead of oganesson (the super-heavy elements where only recently properly named, ununoctium was a placeholder name for element 118).
To update ElementData, I unprotect it and fix the values for elements Nihonium (113), Moscovium (115), Tennessine (118) and Oganesson (118).
If Mathematica's database were up to date, I would only require 239 bytes.
S="";l=ToLowerCase;e=ElementData;r=StringReplace;A=Reverse@SortBy[Table[e[j,"Abbreviation"],{j,118}],StringLength];If[StringFreeQ[r[l@S,Table[l@A[[j]]->"",{j,118}]],Alphabet[]],r[l@S,Table[l@A[[j]]->Capitalize@e[A[[j]],"Name"],{j,118}]],S]

JavaScript (ES6), 881 871 bytes
Takes the input string in all caps.
s=>(o={},'HEelLIithBEeryllMGagnesCAalcTIitanVanadCRhromGAallGEermanSEelenRBubidSRtrontYttrZRirconTCechnetRUuthenRHhodPDalladCDadmTEellurBAarCEerPRraseodymNDeodymPMromethSMamarEUuropGDadolinTBerbDYysprosERrbTMhulLUutetREhenIRridTLhallFRrancRAadACctinTHhorPArotactinUranAMmericCMurESinsteinFMermMDendelevLRawrencRFutherfordDBubnSGeaborgMTeitnerDSarmstadtRGoentgenFLlerovMCoscovLVivermorHydrogenBoronCarbonNitrogenOxygenFluorineNEeonALluminumPhosphorusSulfurCLhlorineARrgonMNanganeseZNincASrsenicBRromineKRryptonMOolybdenumIodineXEenonLAanthanumTAantalumPTlatinumATstatineRNadonTSennessineOGganessonNAsodiumKpotassiumFEironAGsilverWtungstenAUgoldHGmercury'.split(/([A-Z]+|[a-z]+)/).map((r,i,a)=>i%4-3?0:o[e=a[i-2]]=i>339?r[0].toUpperCase()+r.slice(1):e[0]+r+(i<235?'ium':'')),g=([c,...s],r)=>c?c<'A'|c>'Z'?g(s,r+c):o[c]&&g(s,r+o[c])||o[c+=s.shift()]&&g(s,r+o[c]):r)(s,'')||s

Extended test cases
Because this challenge is also a variant of the exact cover set problem, I've added the following test cases:

"NA" → "Sodium"
"NAG" → "N" + "AG" → "NitrogenSilver"
"NAP" → "NA" + "P" → "SodiumPhosphorus"

let f =

s=>(o={},'HEelLIithBEeryllMGagnesCAalcTIitanVanadCRhromGAallGEermanSEelenRBubidSRtrontYttrZRirconTCechnetRUuthenRHhodPDalladCDadmTEellurBAarCEerPRraseodymNDeodymPMromethSMamarEUuropGDadolinTBerbDYysprosERrbTMhulLUutetREhenIRridTLhallFRrancRAadACctinTHhorPArotactinUranAMmericCMurESinsteinFMermMDendelevLRawrencRFutherfordDBubnSGeaborgMTeitnerDSarmstadtRGoentgenFLlerovMCoscovLVivermorHydrogenBoronCarbonNitrogenOxygenFluorineNEeonALluminumPhosphorusSulfurCLhlorineARrgonMNanganeseZNincASrsenicBRromineKRryptonMOolybdenumIodineXEenonLAanthanumTAantalumPTlatinumATstatineRNadonTSennessineOGganessonNAsodiumKpotassiumFEironAGsilverWtungstenAUgoldHGmercury'.split(/([A-Z]+|[a-z]+)/).map((r,i,a)=>i%4-3?0:o[e=a[i-2]]=i>339?r[0].toUpperCase()+r.slice(1):e[0]+r+(i<235?'ium':'')),g=([c,...s],r)=>c?c<'A'|c>'Z'?g(s,r+c):o[c]&&g(s,r+o[c])||o[c+=s.shift()]&&g(s,r+o[c]):r)(s,'')||s

console.log(f('HI!'))
console.log(f('THIS IS AN EXAMPLE'))
console.log(f('NEON'))
console.log(f('SNIP'))
console.log(f('NA'))
console.log(f('NAG'))
console.log(f('NAP'))

How?
Preliminary optimization
We ignore the following 26 elements entirely, because they can safely be replaced with two symbols of one character among BCFHIKNOPSUVWY:
Bh, Bi, Bk, Cf, Cn, Co, Cs, Cu, Hf, Ho, Hs, In, Nb,
Nh, Ni, No, Np, Os, Pb, Po, Pu, Sb, Sc, Si, Sn, Yb

Encoding and decoding the elements
We use an interlaced list of element symbols in upper case and element names in lower case. Symbols are always stored as-is, while names are shortened according to the following rules:

If the first letter of the name matches the first letter of the symbol, we omit it.
If the element passes rule #1 and its name ends in "ium", we omit this suffix.

Examples:

Ag / Silver: "AGsilver"
K / Potassium: "Kpotassium"
Zn / Zinc: "ZNinc"
He / Helium: "HEel"

The 58 elements that trigger both rules are stored at the beginning of the list, followed by the 27 elements that trigger rule #1 only, followed by the 7 elements that do not trigger any rule.
We decode this list to populate the lookup table o, where the keys are the symbols and the values are the decoded element names:
"HEelLIith[...]HGmercury"       // encoded list
.split(/([A-Z]+|[a-z]+)/)       // split it by character case, which gives:
                                // [ '', 'HE', '', 'el', '', 'LI', '', 'ith', etc. ]
.map((r, i, a) =>               // for each item 'r' at position 'i' in this array 'a':
  i % 4 - 3 ?                   //   if we're not currently pointing to an element name:
    0                           //     do nothing
  :                             //   else:
    o[e = a[i - 2]] =           //     save o[e], where e = element symbol
      i > 339 ?                 //     if symbol/name first letters do not match:
        r[0].toUpperCase() +    //       we need to capitalize the first letter of the name
        r.slice(1)              //       and keep the rest unchanged
      :                         //     else:
        e[0] +                  //       we use the first letter of the symbol,
        r +                     //       followed by the name,
        (i < 235 ? 'ium' : '')  //       followed by the 'ium' suffix when appropriate
)                               // end of map()

Covering the input string
We try to replace all upper-case letters in the input string with element symbols, using the recursive function g() which eventually returns a replacement string or undefined if no exact cover is found:
g = ([c,                                  // c = next character
         ...s],                           // s = array of remaining characters
                r) =>                     // r = replacement string
  c ?                                     // if there's still at least one character:
    c < 'A' | c > 'Z' ?                   //   if it's not an upper-case letter:
      g(s, r + c)                         //     just append it to 'r'
    :                                     //   else:
      o[c] && g(s, r + o[c]) ||           //     try to find a symbol matching 'c'
      o[c += s.shift()] && g(s, r + o[c]) //     or a symbol matching 'c' + the next char.
  :                                       // else:
    r                                     //   success: return 'r'

Javascript, 1487 1351 1246 1170 1243 1245 bytes
saved 234 bytes thanks to @musicman523
saved 174 bytes thanks to @ovs
saved 7 bytes thanks to @Shaggy
added  75 bytes to make it work for 2 letter elements
b=>~((o=0,d=Array.from([...b].map((u,i,a)=>(h=e=>("he0Hel2h0Hydrogen1li0Lith2be0Beryll2b0Boron1c0Carbon1n0Nitrogen1o0Oxygen1f0Fluorine1ne0Neon1na0Sod2mg0Magnes2al0Aluminum1p0Phosphorus1s0Sulfur1cl0Chlorine1ar0Argon1k0Potass2ca0Calc2ti0Titan2v0Vanad2cr0Chrom2mn0Manganese1fe0Iron1ni0Nickel1cu0Copper1zn0Zinc1ga0Gall2ge0German2as0Arsenic1se0Selen2br0Bromine1kr0Krypton1rb0Rubid2sr0Stront2y0Yttr2zr0Zircon2nb0Niob2mo0Molybdenum1tc0Technet2ru0Ruthen2rh0Rhod2pd0Pallad2ag0Silver1cd0Cadm2in0Ind2te0Tellur2i0Iodine1xe0Xenon1cs0Ces2ba0Bar2la0Lanthanum1ce0Cer2pr0Praseodym2nd0Neodym2pm0Prometh2sm0Samar2eu0Europ2gd0Gadolin2tb0Terb2dy0Dyspros2ho0Holm2er0Erb2tm0Thul2lu0Lutet2hf0Hafn2ta0Tantalum1w0Tungsten1re0Rhen2ir0Irid2pt0Platinum1au0Gold1hg0Mercury1tl0Thall2at0Astatine1rn0Radon1fr0Franc2ra0Rad2ac0Actin2th0Thor2pa0Protactin2u0Uran2np0Neptun2pu0Pluton2am0Americ2cm0Cur2bk0Berkel2cf0Californ2es0Einstein2fm0Ferm2md0Mendelev2no0Nobel2lr0Lawrenc2rf0Rutherford2db0Dubn2sg0Seaborg2bh0Bohr2hs0Hass2mt0Meitner2ds0Darmstadt2rg0Roentgen2nh0Nihon2fl0Flerov2mc0Moscov2lv0Livermor2ts0Tennessine1og0Oganesson".replace(/2/g,'ium1').split(1).map(a=>a.split(0)).find(a=>a[0]==e)||[,0])[1],o?(o=0,''):((p=a[i+1])&&(o=1,h(u+p))||(o=0,h(u)))))).join``).search(0))?b:d

(Slightly more) readable version:
b=>~((o=0,d=Array.from([...b].map((u,i,a)=>(h=e=>(
"he0Hel2h0Hydrogen1li0Lith2be0Beryll2b0Boron1c0Carbon1n0Nitrogen1o0Oxygen1f0Flu
orine1ne0Neon1na0Sod2mg0Magnes2al0Aluminum1p0Phosphorus1s0Sulfur1cl0Chlorine1ar0
Argon1k0Potass2ca0Calc2ti0Titan2v0Vanad2cr0Chrom2mn0Manganese1fe0Iron1ni0Nickel1
cu0Copper1zn0Zinc1ga0Gall2ge0German2as0Arsenic1se0Selen2br0Bromine1kr0Krypton1rb
0Rubid2sr0Stront2y0Yttr2zr0Zircon2nb0Niob2mo0Molybdenum1tc0Technet2ru0Ruthen2rh0
Rhod2pd0Pallad2ag0Silver1cd0Cadm2in0Ind2te0Tellur2i0Iodine1xe0Xenon1cs0Ces2ba0Ba
r2la0Lanthanum1ce0Cer2pr0Praseodym2nd0Neodym2pm0Prometh2sm0Samar2eu0Europ2gd0Gad
olin2tb0Terb2dy0Dyspros2ho0Holm2er0Erb2tm0Thul2lu0Lutet2hf0Hafn2ta0Tantalum1w0Tu
ngsten1re0Rhen2ir0Irid2pt0Platinum1au0Gold1hg0Mercury1tl0Thall2at0Astatine1rn0Ra
don1fr0Franc2ra0Rad2ac0Actin2th0Thor2pa0Protactin2u0Uran2np0Neptun2pu0Pluton2am0
Americ2cm0Cur2bk0Berkel2cf0Californ2es0Einstein2fm0Ferm2md0Mendelev2no0Nobel2lr0
Lawrenc2rf0Rutherford2db0Dubn2sg0Seaborg2bh0Bohr2hs0Hass2mt0Meitner2ds0Darmstadt
2rg0Roentgen2nh0Nihon2fl0Flerov2mc0Moscov2lv0Livermor2ts0Tennessine1og0Oganesson
".replace(/2/g,'ium1').split(1).map(a=>a.split(0)).find(a=>a[0]==e)||[,0])[1],o?
(o=0,''):((p=a[i+1])&&(o=1,h(u+p))||(o=0,h(u)))))).join``).search(0))?b:d

"readable version", yeah, totally readable.  Nice job though.  This is going to be a byte-intensive challenge for any lang that doesn't have a built-in for elements (anything that isn't Mathematica).

Can you factor out "ium" to save bytes?

That's a good idea, @musicman523

@Gryphon You could also try factoring out on. Also, if you want to make it more human readable, use more readable delineators than 0 and 1. E.g. any of ,;.!/-_:~ *|=+'".

@DanTheMan no, that's 5 bytes longer

You don't need to encode elemnts like copernicium (CN) as you can always use carbon and nitrogen instead

Expanding on @ovs' improvments: 1170  bytes

I only saved you 7 bytes; credit for the other 69 should go to @ovs.

@Shaggy fixed that

This fails to identify 2-character elements in the input string.


text:
Counting up and down while doubling the increments
Input:
A non-empty list / vector where each element holds a value/character, indicating if you'll count up  or down. I'll use 1 and -1, but you may choose whatever you like. You can only use two values, you can't use 1,2,3... and -1,-2,-3..., for up and down respectively.
Challenge:
You'll use the numbers in the geometric series 1, 2, 4, 8, 16, 32.... Every time you start counting up or down, you'll count in increments of 1, then 2, then 4 and so on. If you change and start counting the other way then you'll subtract 1, then 2, then 4 and so on. The output shall be the number you get to in the end.
Examples:
In the example below, the first line is the input, the second line is the numbers you're counting up/down, the third line is the cumulative sum, and the last line is the output.
Example 1:
1   1   1   1   1   1   1   1   1   1
1   2   4   8   16  32  64  128 256 512
1   3   7   15  31  63  127 255 511 1023
1023

Example 2:
1   1   1   1   1   1   -1  -1  -1  -1  1   1   1
1   2   4   8   16  32  -1  -2  -4  -8  1   2   4
1   3   7   15  31  63  62  60  56  48  49  51  55
55

As you can see, the first 1 or -1 "resets" the value we're counting, and consecutive sequences of 1 or -1 means doubling the value.
Example 3:
-1  -1  1   1   -1  -1  -1
-1  -2  1   2   -1  -2  -4
-1  -3  -2  0   -1  -3  -7
-7

Some additional test cases to account for some potential corner cases.
The input is on the first line. The output is on the second.
1
1
-------
-1
-1
-------
-1   1  -1   1  -1   1  -1   1  -1   1  -1   1
0

This is code-golf so the shortest submission in each language wins.

Husk, 3 bytes
ṁḋg

Try it online!
Explanation
ṁḋg
  g  Group equal adjacent elements,
ṁ    take sum of
 ḋ   base-2 decoding of each group.

MATL, 6 bytes
Y'Wq*s

Try it online! Or verify all test cases.
Explanation
Consider input [1 1 1 1 1 1 -1 -1 -1 -1 1 1 1].
     % Implicit input
     % STACK: [1 1 1 1 1 1 -1 -1 -1 -1 1 1 1]
Y'   % Run-length encoding
     % STACK: [1 -1 1], [6 4 3]
W    % Exponentiation with base 2, element-wise
     % STACK: [1 -1 1], [64 16 8]
q    % Subtract 1
     % STACK: [1 -1 1], [63 15 7]
*    % Multiply, element-wise
     % STACK: [63 -15 7]
s    % sum of array
     % STACK: 55
     % Implicit display

Japt, 8 6 bytes
-2 bytes thanks to @ETHproductions
ò¦ xì2

Try it online!
Explanation
Implicit input: [1, 1, 1, -1, -1, -1, -1, 1, 1]
ò¦

Partition input array (ò) between different (¦) elements:
[[1, 1, 1], [-1, -1, -1, -1], [1, 1]]
ì2

Map each partition to itself parsed as an array of base-2 digits (ì): [7, -15, 3]
x

Get the sum (x) of the resulting array: -5

Nice technique. I believe you can change ®ì2Ãx to xì2 to save two bytes.

@ETHproductions Man, you've been all over my posts. Thanks again!

Cubix, 65 bytes
W(?\q.p)w.;0.w;/0>I!U-unP(nwUs;q\^q:;^!u?P(w!u+w.;;>2p!u/@Os..sr\

Try it online!
        W ( ? \
        q . p )
        w . ; 0
        . w ; /
0 > I ! U - u n P ( n w U s ; q
\ ^ q : ; ^ ! u ? P ( w ! u + w
. ; ; > 2 p ! u / @ O s . . s r
\ . . . . . . . . . . . . . . .
        . . . .
        . . . .
        . . . .
        . . . .

Watch it run
As a brief explanation of this:

Read in each integer (1 or -1) and compare it to previous. If:

the same push it to the bottom as the start of a counter
else bring counter to top and increment/decrement it as appropriate.

Once input is finished bring each counter to the top and handling negatives do 2 ^ counter - 1
Sum the results and output

JavaScript (ES6), 38 bytes
a=>a.map(e=>r+=d=d*e>0?d+d:e,r=d=0)&&r

Python 3, 57 56 bytes
-1 byte thanks to @notjagan
f=lambda a,*s,m=1:m*a+(s>()and f(*s,m=(m*2)**(a==s[0])))

Try it online!

-1 byte with this or this.

That s>() took me a second. That's really smart.

R, 32 bytes
sum((2^(R=rle(scan()))$l-1)*R$v)

Try it online!
This is the same method as a few others here.
With the input of -1  -1  1   1   -1  -1  -1

Do a Run Length Encoding on the input.  Results with lengths of 2, 2, 3 and values -1, 1, -1
Do 2 to power of lengths - 1.  Results in 3, 3, 7
Multiply by the RLE values giving -3, 3, -7
Return the sum -7

Brachylog, 13 bytes
ḅ⟨{ȧᵐ~ḃ}×h⟩ᵐ+

Try it online!
Brachylog uses _ instead of -.
Explanation:
?ḅ⟨{ȧᵐ~ḃ}×h⟩ᵐ+. Predicate (implicit ?.)
?               The input
 ḅ              A list where its elements' elements are equal, and when concatenated is ?
            ᵐ   The result of mapping this predicate over ?
  ⟨        ⟩      The result of forking two predicates over ? with a third
   {    }           The result of this predicate on ?
     ᵐ                The result of mapping this predicate over ?
    ȧ                   The absolute value of ?
      ~               An input where the result of this predicate over it is ?
       ḃ                A list that represents the digits of ? in base I (default 2)
          h         An object that is the first element of ?
         ×          A number that is the product of ?
             +  A number that is the sum of ?
              . The output

Jelly, 4 bytes
ŒgḄS

Try it online!

C++14, 58 bytes
[](auto v,int&s){int p=s=0;for(auto x:v)s+=p=x*p<1?x:2*p;}

Takes input via the v argument (std::vector, or any iterable container), outputs to the s argument (by reference). Each element of v must be either 1 or -1.
Example usage and test cases.

05AB1E, 6 bytes
γε2β}O

Try it online!

Ahhh... Base-2 conversion... and I thought I was being cute with lift. γε¬sƶÄ<o*}OO

Haskell, 54 53 bytes
k#(a:b:c)=k+last(b:[k*2|a==b])#(b:c)
k#_=k
(#)=<<head

Try it online!
A simple recursion that either doubles the accumulator k or resets it to 1/-1 and adds the values of each step.

Python, 76 72 bytes
f=lambda s,k=1:len(s)and(f(s,s[0])if s[0]*abs(k)/k-1else k+f(s[1:],2*k))

Try it online!

Pyth, 12 bytes
sm*edt^2hdr8

Try it online!

PHP, 51 bytes
while($d=$argv[++$i])$s+=$x=$d*$x>0?2*$x:$d;echo$s;

Run with -n or try it online.

CJam (13 bytes)
{e`{(*2b}%1b}

Online test suite. This is an anonymous block (function) which takes an array of ints on the stack and leaves an int on the stack. The last test shows that it handles an empty array correctly, giving 0.
The approach is straightforward run-length encoding followed by a manual run-length decode of each run and base conversion. Using the built-in for run-length decode I get one byte more with {e`1/:e~2fb1b} or {e`{ae~2b}%1b}.

Java, 91 bytes
int f(int[]a){int s=0,r=0,i=-1;while(++i<a.length)r+=s=s!=0&s>0==a[i]>0?2*s:a[i];return r;}

Pyth, 11 bytes
s.b*t^2NYr8

Try it online
How it works
         r8    run-length encode input
 .b            map (N, Y) ↦
     ^2N           2^N
    t              minus 1
   *    Y          times Y
s              sum

Mathematica, 60 bytes
Tr[Last@*Accumulate/@(#[[1]]2^(Range@Tr[1^#]-1)&/@Split@#)]&

Mathematica, 25 bytes
Tr[Fold[#+##&]/@Split@#]&


text:
Divisibility of numbers
Challenge
HP is doing research in mathematics . After doing lots of research, she struck in a problem . She found four numbers n,a, b and c .Now, She wants to know how many number exists which are less than or equal to n and are divisible by a ,b or c .
Input :
4 integers denoting n,a,b and c separated by space
Output :
intger which denotes the count of the numbers which are divisible a,b,c
Scoring:
This is code-golf, shortest code in bytes wins.

Can you add test cases? Does the count include 0 and negative numbers?

What are the ranges of the input parameters?

Python 2, 72 65 bytes
Note: This solution works for positive integers:
lambda a,b,c,n:len([x for x in range(1,n+1)if x%a*(x%b)*(x%c)<1])

Try it online!

Python 2, 52 bytes
lambda n,a,b,c:n/a+n/b+n/c-n/a/b-n/a/c-n/b/c+n/a/b/c

Try it online!
By the inclusion–exclusion principle.


text:
Do I have a prime twin?
An Integer is prime if and only if it is positive and has exactly 2 distinct divisors: 1 and itself. A twin prime pair is made of two elements: p and p±2, that are both prime.
You will be given a positive integer as input. Your task is to return a truthy / falsy depending on whether the given integer belongs to a twin pair, following the standard decision-problem rules (the values need to be consistent).
Test Cases

Truthy (Twin Primes): 3, 5, 7, 11, 13, 17, 19, 29, 31, 41, 43

Falsy (not Twin Primes): 2, 15, 20, 23, 37, 47, 97, 120, 566

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

is 13 a prime twin?

@LiefdeWen Yes, because it belongs to the pair (11, 13)

This is OEIS A001097.

Brachylog, 9 8 bytes
ṗ∧4√;?+ṗ

Try it online!
Explanation
ṗ           Input is prime
 ∧          And
  4√        A number whose square is 4 (i.e. -2 or 2)
    ;?+     That number + the Input…
       ṗ    …is prime

Beating Jelly and tying 05AB1E, nice

Clever √ usage! +1

Jelly, 10 9 bytes
%6+_2_ÆP⁺

Try it online!
Background
With the exception of (3, 5), all twin prime pairs are of the form (6k - 1, 6k + 1).
Since (6k - 1) + (6k - 1) % 6 - 3 = 6k - 1 + 5 - 3 = 6k + 1 and
(6k + 1) + (6k + 1) % 6 - 3 = 6k + 1 + 1 - 3 = 6k - 1, given an input n > 3, it is sufficient to check whether n and n + n % 6 - 3 are both prime.
This formula happens to work for n = 3 as well, as 3 + 3 % 6 - 3 = 3 is prime and 3 is a twin prime.
How it works
%6+_2_ÆP⁺  Main link. Argument: n

%6         Compute n%6.
  +        Add n to the result.
   _2      Subtract 2.
     _ÆP   Subtract 1 if n is prime, 0 if not.
           If n is not a prime, since (n + n%6 - 2) is always even, this can only
           yield a prime if (n + n%6 - 2 = 2), which happens only when n = 2.
        ⁺  Call ÆP again, testing the result for primality.

Python 3, 53 bytes
lambda n:sum((n+n%6-3)*n%k<1for k in range(2,4*n))==2

Try it online!
Background
All integers take one of the following forms, with integer k: 6k - 3, 6k - 2, 6k - 1, 6k, 6k + 1, 6k + 2.
Since 6k - 2, 6k, and 6k + 2 are all even, and since 6k - 3 is divisible by 3, all primes except 2 and 3 must be of the form 6k - 1 or 6k + 1. Since the difference of a twin prime pair is 2, with the exception of (3, 5), all twin prime pairs are of the form (6k - 1, 6k + 1).
Let n be of the form 6k ± 1.

If n = 6k -1, then n + n%6 - 3 = 6k - 1 + (6k - 1)%6 - 3 = 6k - 1 + 5 - 3 = 6k + 1.
If n = 6k + 1, then n + n%6 - 3 = 6k + 1 + (6k + 1)%6 - 3 = 6k + 1 + 1 - 3 = 6k - 1.

Thus, if n is part of a twin prime pair and n ≠ 3, it's twin will be n + n%6 - 3.
How it works
Python doesn't have a built-in primality test. While there are short-ish ways to test a single number for primality, doing so for two number would be lengthy. We're going to work with divisors instead.
sum((n+n%6-3)*n%k<1for k in range(2,4*n))

counts how many integers k in the interval [2, 4n) divide (n + n%6 - 3)n evenly, i.e., it counts the number of divisors of (n + n%6 - 3)n in the interval [2, 4n).  We claim that this count is 2 if and only if n is part of a twin prime pair.

If n = 3 (a twin prime), (n + n%6 - 3)n = 3(3 + 3 - 3) = 9 has two divisors (3 and 9) in [2, 12).
If n > 3 is a twin prime, as seen before, m := n + n%6 - 3 is its twin. In this case, mn has exactly four divisors: 1, m, n, mn.
Since n > 3, we have m > 4, so 4n < mn and exactly two divisors (m and n) fall into the interval [2, 4n).
If n = 1, then (n + n%6 - 3)n = 1 + 1 - 3 = -1 has no divisors in [2, 4).
If n = 2, then (n + n%6 - 3)n = 2(2 + 2 - 3) = 2 has one divisor (itself) in [2, 8).
If n = 4, then (n + n%6 - 3)n = 4(4 + 4 - 3) = 20 has four divisors (2, 4, 5, and 10) in [2, 16).
If n > 4 is even, 2, n/2, and n all divide n and, therefore, (n + n%6 - 3)n. We have n/2 > 2 since n > 4, so there are at least three divisors in [2, 4n).
If n = 9, then (n + n%6 - 3)n = 9(9 + 3 - 3) = 81 has three divisors (3, 9, and 21) in [2, 36).
If n > 9 is a multiple of 3, then 3, n/3, and n all divide n and, therefore, (n + n%6 - 3)n. We have n/3 > 3 since n > 9, so there are at least three divisors in [2, 4n).
Finally, if n = 6k ± 1 > 4 is not a twin prime, either n or m := n + n%6 - 3 must be composite and, therefore, admit a proper divisor d > 1.
Since either n = m + 2 or m = n + 2 and n, m > 4, the integers d, m, and n are distinct divisors of mn. Furthermore, m < n + 3 < 4n since n > 1, so mn has at least three divisors in [2, 4n).

Wow. Such short code and yet so many special cases it must handle correctly. Any reason you say Python 3? As far as I can tell it also works in Python 2.

Yes, this will work just as well in Python 2. The 3 is part of the auto-generated SE post from TIO.

05AB1E, 10 9 bytes
Saved 1 byte thanks to Datboi
ÌIÍ‚pZIp*

Try it online!
or as a Test Suite
Explanation
Ì           # push input+2
 IÍ         # push input-2
   ‚        # pair
    p       # isPrime
     Z      # max
      Ip    # push isPrime(input)
        *   # multiply

Use ÌIÍ‚ instead of 40SÍ+ for -1 byte

PHP, 52 bytes
<?=($p=gmp_prob_prime)($n=$argn)&&$p($n+2)|$p($n-2);

without GMP, 84 bytes
(using my prime function from stack overflow)
<?=p($n=$argn)&&p(2+$n)|p($n-2);function p($n){for($i=$n;--$i&&$n%$i;);return$i==1;}

Run as pipe with -nF. Empty output for falsy, 1 for truthy.
Dennis´ great solution ported to PHP, 56 bytes
while($i++<4*$n=$argn)($n+$n%6-3)*$n%$i?:$s++;echo$s==3;

Run as pipe with -nR or try it online.

Perl 6, 24 bytes
?(*+(0&(-2|2))).is-prime

Try it online!
* is the argument to this anonymous function.  0 & (-2 | 2) is the junction consisting of the numbers 0 AND either -2 OR 2.  Adding * to this junction produces the junction of the number * AND either of the numbers * - 2 OR * + 2.  Calling the is-prime method on this junction returns a truthy value if * is prime AND either * - 2 OR * + 2 are prime.  Finally, the ? collapses the truthy junction to a boolean value, satisfying the consistent-return-values condition.

Retina, 45 44 bytes
.*
$*
11(1+)
$1¶$&¶11$&
m`^(11+)\1+$

1<`1¶1

Returns 1 if the input is a twin prime, 0 otherwise
Try it online!
Explanation
.*
$*

Convert to Unary
11(1+)
$1¶$&¶11$&

Put n-2, n, and n+2 on their own lines
m`^(11+)\1+$

(Trailing newline) Remove all composites greater than 1
1<`1¶1

Check if there are two consecutive primes (or 1,3 because 3 is a twin prime)

Pyth, 14 12 11 bytes
&P_QP-3+%Q6

Test Suite.

Saved 3 bytes using the formula in @Dennis' answer. Saved 1 byte thanks to @Dennis.

Pyth, 14 bytes *Initial Solution
&|P_ttQP_hhQP_

Test Suite.

Mathematica, 33 bytes
(P=PrimeQ;P@#&&(P[#+2]||P[#-2]))&

Try it online!

MATL, 11 bytes
HOht_v+ZpAa

Output is 0 or 1.
Try it online!
Explanation
H    % Push 2
O    % Push 0
h    % Concatenate horizontally: gives [2 0]
t_   % Push a negated copy: [-2 0]
v    % Concatenate vertically: [2 0; -2 0]
+    % Add to implicit input
Zp   % Isprime
A    % All: true for columns that only contain nonzeros
a    % Any: true if there is at least a nonzero. Implicit display

Factor + math.primes, 42 bytes
[| x | 0 2 -2 [ x + prime? ] tri@ or and ]

Try it online!
Originally inspired by trying to golf Michael Chatiskatzi's answer, I've then modified it enough that I thought worth posting it as a separate answer.
Explanation
This is a lambda function using the local variable x to refer to the element at the top of the stack when the function is called (its argument).
[ x + prime? ] defines a function that adds x to a number and checks if the result is prime. This is then applied using tri@ to the three values 0,2,-2, resulting in three booleans determining if x,x+2 and x-2 are primes. We combine the last two with or, and the result of this with the first with and.
The total function is then equivalent to isprime(x+0) and (isprime(x+2) or isprime(x-2))

Excel VBA, 102 100 Bytes
No primality built-ins for VBA :(
Code
Anonymous VBE immediate window function that takes input from cell [A1] and outputs either 1 (truthy)  or 0 (falsy) to the VBE Immediate window
a=[A1]:?p(a)*(p(a-2)Or p(a+2))

Helper Function
Function p(n)
p=n>2
For i=2To n-1
p=IIf(n Mod i,p,0)
Next
End Function

Alternatively, 122 Bytes
Code
Recursive primality checking function based solution
a=[A1]:?-1=Not(p(a,a-1)Or(p(a-2,a-3)*p(a+2,a+1)))

Helper Function
Function p(n,m)
If m>1Then p=p(n,m-1)+(n Mod m=0)Else p=n<=0
End Function

JavaScript, 91 bytes, 81 bytes thanks to Jared Smith
p=n=>{for(i=2;i<n;)if(n%i++==0)return !!0;return n>1},t=n=>p(n)&&(p(n+2)||p(n-2))

Explanation
p tells wether the given number n is prime or not, and t tests given number n and n±2.
Example

var twinPrimes = [3, 5, 7, 11, 13, 17, 19, 29, 31, 41, 43];
var notTwinPrimes = [2, 15, 20, 23, 37, 47, 97, 120, 566];

p=n=>{for(i=2;i<n;)if(n%i++==0)return !!0;return n>1},t=n=>p(n)&&(p(n+2)||p(n-2))

for (var n of twinPrimes) {
  console.log(n, ': ', t(n));
}

for (var n of notTwinPrimes) {
  console.log(n, ': ', t(n));
}

You don't need the var, the parentheses around the n in the function definition, etc.

I think you could edit your snippet to show the value of  n beside the value of t(n) for increased clarity (Eg. 7:   true)

Thx to both of you

05AB1E, 8 bytes
Port of Dennis' Jelly answer
6%+ÍIp-p

Try it online!
or as a Test Suite
Explanation
6%         # n mod 6
  +        # add n
   Í       # subtract 2
    Ip-    # subtract isPrime(n)
       p   # isPrime

Ruby, 38 + 6 = 44 bytes
Requires options -rprime.
->n{n.prime?&[n-2,n+2].any?(&:prime?)}

Try it online!

You can save a byte using & instead of &&

Japt, 13 bytes
j ©[U+2U-2]dj

Returns true and false for whether or not the number is part of a prime twin pair.
Try it online!
Explanation
Implicit: U = input integer
j ©

Check if the input is prime (j), AND (©) ...
[U+2U-2]dj

Using the array [U+2, U-2], check if any items are true (d) according to the primality function (j).
Implicit output of the boolean result of is input prime AND is any ±2 neighbor prime.

Hmm... I feel like [U+2U-2] could be much shorter, but I can't figure out how...

JavaScript(ES6), 54 bytes
a=x=>f(x)&(f(x+2)|f(x-2));f=(n,x=n)=>n%--x?f(n,x):x==1

a=x=>f(x)&(f(x+2)|f(x-2));f=(n,x=n)=>n%--x?f(n,x):x==1

console.log("True")
console.log("---------------------")
console.log(a(3))
console.log(a(5))
console.log(a(7))
console.log(a(11))
console.log(a(13))
console.log(a(17))
console.log(a(19))
console.log(a(29))
console.log(a(31))
console.log(a(41))
console.log(a(43))
console.log("False")
console.log("---------------------")
console.log(a(2))
console.log(a(15))
console.log(a(20))
console.log(a(23))
console.log(a(37))
console.log(a(47))
console.log(a(97))
console.log(a(120))
console.log(a(566))

J, 23 bytes
1&p:*.0<+/@(1 p:_2 2+])

Try it online!
how?
1&p:                               is the arg a prime?
    *.                             boolean and
                                   one of +2 or -2 also a prime
                     (1 p:_2 2+])  length 2 list of booleans indicating if -2 and +2 are primes
               @                   pipe the result into...
      0<+/                         is the sum of the elements greater than 0
                                   ie, at least one true

16 bytes with 3>0#.@p:0 2 _2&+

@miles nice.  very clever use of base 2 to process the results.

Husk, 8 bytes
Vṗ(§e+-2

Try it online!

Factor + math.primes, 46 bytes
[ dup 2 [ + ] 2keep - [ prime? ] tri@ or and ]

Demonstartion of every state of the stack for the example number 43:
  43   dup    2  [ + ]  2keep    - [ prime? ] tri@   or   and

|    |     |    |  + |    2   |    | prime? |      |    |     |
|    |     |  2 |  2 |   43   | 41 |     41 |    t |    |     |
|    |  43 | 43 | 43 |   45   | 45 |     45 |    f |  t |     |
| 43 |  43 | 43 | 43 |   43   | 43 |     43 |    t |  t |   t |

Try it online!

Regex (ECMAScript or better), 48 35 29 28 bytes
-20 bytes thanks to H.PWiz
^(xx)?(?!(xx(x*))\3?\2+$)xxx

Try it online! - ECMAScript
Try it online! - Perl
Try it online! - Java
Try it online! - Python
Try it online! - Ruby
Try it online! - PCRE
Try it online! - .NET
Takes its input in unary, as a string of x characters whose length represents the number.
Commented and indented:
^                 # tail = N = input number
# Assert either that N-2 and N are prime, or that N and N+2 are prime.

(xx)?             # tail -= 2, optionally
# Assert that neither tail nor tail+2 are composite. For testing that they are both prime,
# this has false positives for tail=0, tail=1, and tail=2.
(?!               # Assert that the following can't match:
    (xx(x*))      # \2 = any number >= 2; \3 = \2 - 2
    \3?           # tail -= \3, optionally; if this is done, we're asserting that tail+2 is
                  #             composite (divisible by \2 with a quotient >= 3), otherwise
                  #             we're asserting tail is composite (quotient >= 2).
    \2+$          # Assert that tail is positive and divisible by \2
)
xxx               # Assert that tail >= 3, preventing the false positives.
                  # The "quotient >= 3" requirement above is why tail=2 can be one of them,
                  # as it prevents 2+2 from being seen as composite.

29 bytes
^                  # tail = N = input number
# Assert either that N-2 and N are prime, or that N and N+2 are prime.

(xx)?              # tail -= 2, optionally
# Assert that neither tail nor tail+2 are composite. For testing that they are both prime,
# this has false positives for tail=0 and tail=1.
(?!                # Assert that the following can't match:
    (xx)?          # tail -= 2, optionally; if this is done, we're asserting that tail is
                   #            composite, otherwise we're asserting tail+2 is composite.
    (x*)           # \3 = S-2, where S is a potential divisor to test against M = tail+2;
                   # tail -= \3
    (\3xx)+$       # assert that tail is positive and divisible by \3+2, which is
                   # equivalent to asserting M is divisible by S with a quotient >= 2
)
xx                 # Assert that tail >= 2, preventing the false positives.

48 bytes
This misses the fact that we can switch between testing N-2 and N or testing N and N+2. Instead, this regex switches between testing N and N-2 or testing N and N+2, which results in tests not having enough in common to be collapsed together.
^   # tail = N = input number
(
    # Assert that neither N nor N-2 are composite. But we want N and N-2 to be prime, so
    # this gives false positives for 0, 1, and 2.
    (?!              # Assert that the following can't match:
        (xx)?        # tail -= 2, optionally
        (xx+)        # \3 = any number >= 2
        \3+$         # Assert that tail is positive and divisible by \3
    )
|   # or...
    # Assert that neither N nor N+2 are composite. But we want N and N+2 to be prime, so
    # this gives false positives for 0 and 1.
    (?!              # Assert that the following can't match:
        (xx(x*))     # \4 = any number >= 2; \5 = \4 - 2
        \4*(xx)?\5$  # Assert that either tail or tail+2 is positive and divisible by \4
    )
)
xxx                  # Block the false positives on every number less than 3

51 bytes (not golfed at all)
^                      # tail = N = input number
(?!(xx+)\1+$)          # Assert that N is not composite. But we want N to be prime,
                       # so this gives false positives for 0 and 1.
(
    (?!xx(xx+)\3+$)    # Assert that N-2 is not composite. But we want N-2 to be prime, so this
                       # gives false positives for 0, 1, and 2.
|   # or...
    (?!(x*)(xx\4)+$)   # Assert that N+2 is not composite. Has no false positives for primality.
)
xxx                    # Block the false positives on every number less than 3

Regex (ECMAScript), 67 bytes
Just for kicks, here is a port of Dennis's Jelly algorithm:
^(?!(xx+)\1+$)(?=(x{6})*(x*))xxx(?!(xx+)(?=\4*(x*)).*(?=\5\3$)\4+$)

Try it online!
^                      # tail = N = input number
(?!(xx+)\1+$)          # Assert N is not composite
(?=(x{6})*(x*))        # \3 = N % 6
xxx                    # assert N>=3; tail -= 3
# Assert tail + \3 is not composite
(?!                    # Assert the following can't match:
    (xx+)              # \4 cycles through all values such that 2 <= \4 <= tail,
                       #    and is tested as a possible divisor of tail + \3
    (?=\4*(x*))        # \5 = tail % \4
    .*(?=\5\3$)        # tail = \5 + \3
    \4+$               # Assert that tail is positive and divisible by \4
)

\$\large\textit{Anonymous functions}\$
JavaScript (ES6), 50 bytes
n=>/^(..)?(?!(..(.*))\3?\2+$).../.test(Array(n+1))

Try it online!
Ruby, 41 bytes
->n{?x*n=~/^(xx)?(?!(xx(x*))\3?\2+$)xxx/}

Try it online!
Try it online! - test cases only
\$\large\textit{Full programs}\$
Retina, 34 bytes
.*
$*
^(11)?(?!(11(1*))\3?\2+$)111

Try it online! - test cases only

APL (Dyalog Unicode), 35 bytes
{∨/2∧/∊∘{(⊢~∘.×⍨)1↓⍳⍵}¨⍨|2(-,⊢,+)⍵}
 ∨/ ⍝ reduce by bitwise OR
   2∧/ ⍝ logical AND bit array, two at a time (overlapping)
     ∊∘{...}¨⍨ ⍝ for each, check if in list of primes
       (⊢~∘.×⍨)1↓⍳⍵ ⍝ find element of range that is not in matrix of composite numbers (list of primes)
         | ⍝ absolute value of array
           2(-,⊢,+)⍵ ⍝ create array (2-n, n, 2+n)

Try it online!

Python 2, 75 bytes
lambda x:p(x)*(p(x-2)|p(x+2))
p=lambda z:(z>1)*all(z%i for i in range(2,z))

Try it online!

PHP, 85 bytes 24 bytes  thanks to Mayube
e($n){return f($n)&&((f($n-2)||f($n+2)))
f($n){for($i=$n;--$i&&$n%$i;)return $i==1;}

This can be golfed considerably by changing the names of both functions to 1 character each (eg a and b)

Doesn´t PHP need the function keyword anymore?

Excel, 84 bytes
Current Excel 365:
=LET(x,SEQUENCE(A1+2),(SUM((MOD(A1,x)=0)*1)=2)*(SUM((MOD(A1+MOD(A1,6)-3,x)=0)*1)=2))

Future Excel (73 bytes):
=LET(p,LAMBDA(a,SUM((MOD(a,SEQUENCE(a))=0)*1)=2),p(A1)*p(A1+MOD(A1,6)-3))


text:
Making octogonal words
Last Thursday user @SpookyGengar delighted us with his/her first challenge about Making Squared Words. What if we double the number of sides?
The challenge
Take a string as input in any reasonable format you need (string, char array...) and output an octogonal representation of the input (also in any reasonable format: string, list of strings, char matrix...) as in the next examples:
Input: golf
Output:

   golf
  o    l
 l      o
f        g
l        o
o        l
g        f
 o      l
  l    o
   flog

Input: HelloWorld
Output:

         HelloWorld
        e          l
       l            r
      l              o
     o                W
    W                  o
   o                    l
  r                      l
 l                        e
d                          H
l                          e
r                          l
o                          l
W                          o
o                          W
l                          o
l                          r
e                          l
H                          d
 e                        l
  l                      r
   l                    o
    o                  W
     W                o
      o              l
       r            l
        l          e
         dlroWolleH

Input: a
Output:

a

Input: ab
Output:

 ab
b  a
a  b
 ba

Input: code golf
Output:

        code golf
       o         l
      d           o
     e             g

   g                 e
  o                   d
 l                     o
f                       c
l                       o
o                       d
g                       e

e                       g
d                       o
o                       l
c                       f
 o                     l
  d                   o
   e                 g

     g             e
      o           d
       l         o
        flog edoc

Notes

Input will consist only of printable ASCII characters.
Leading and/or trailing whitespaces and newlines allowed as long as the octogonal shape is maintained.
This is code-golf, so may the sortest program/function for each language win!

"What if we double the number of sides?" <-- then charcoal would still win

Suggested testcase: code golf

@LeakyNun is <Space> considered printable?

@V.Courtois yes

@LeakyNun added test case.

Charcoal, 16 bytes (10 bytes noncompeting)
Ｆ⁸«✂θ⁰±¹↷¹Ａ⮌θθ»θ

Try it online! Link is to verbose version of code. Explanation:
Ｆ⁸«                 Repeat for each side of the octagon
   ✂θ⁰±    ¹        Print the input except the last character
        ↷¹          Rotate 45° clockwise
          Ａ⮌θθ      Reverse the input string
              »θ    Print the input again, to handle the length 1 case

Alternative length 1 fix, also 16 bytes: Verbose version.
ＰθＦ⁸«✂θ⁰±¹↷¹Ａ⮌θθ

A Charcoal bugfix means that the following 10-byte code now works: Verbose version.
Ｆ⁴«θ←↘⮌θ↖⟲

⟲ seems like it should just do this. Lol

Umm, I don't think code golf works does it?

Oh, and this is in fact 16 bytes (replace θθθ with θθ»θ).

@EriktheOutgolfer Oops, sorry about that, I didn't think to test my fix for the length 1 case... my test record on the question hasn't been very good has it?

@Neil But what about the issue with code golf? I think that has to do with how Charcoal takes input, which, unfortunately, disqualifies it completely from this challenge as that can't be circumvented.

@EriktheOutgolfer I think it's because of the way TIO passes input to Charcoal; if you add a newline you get a different result.

@Neil TIO doesn't explicitly add trailing stuff to the input, I think Charcoal uses something like .split() for input where if there's only one line it splits on spaces while if it's over multiple lines it splits on newlines.

@EriktheOutgolfer Well since Charcoal can take input as a Python array it can be circumvented

@Neil Invited you as a collaborator if you want to/don't mind fixing bugs (I can explain how it works in chat or something), also even if you don't accept would you mind opening issues? Thanks in advance

@Neil It isn't exactly the way TIO passes input, rather it's the way Charcoal parses input (python eval -> split by newline -> split by space, using the first one that works)

Also verbose of the second one

Finally fixed the bug (theoretical one) (sorry)

@ASCII-only Actually I'd since golfed the second one down so that it doesn't trigger the verbose bug, sorry about that. The original code was θ←↘⮌θ↖↓θ⟲ＯＯ↙²⁴⁶Ｌθ which can't be written in Verbose mode.

@ASCII-only Wow that means I can even have input with newlines!

@Neil Oh, yeah I fixed that, so that's what you were talking about haha

JavaScript (ES6), 156 bytes

f=
s=>[...Array((l=s.length-1)*3+1)].map((_,i,a)=>a.map((_,j)=>s[i+j-l?l*5-i-j?i+l*2-j?j+l*2-i?i%(l*3)?j%(l*3)?-1:j?i-l:l+l-i:i?l+l-j:j-l:j:l-i:l*3-i:i]||` `))
<input oninput=o.textContent=this.value?f(this.value).map(function(a){return(a.join``)}).join`\n`:``><pre id=o>

Returns a character array.

It seems to work only with strings of length 4.

@CarlosAlejo Sorry, didn't check carefully enough. Conveniently, fix saved 2 bytes!

Oh my that's a lot of ternary ?:s!

@EriktheOutgolfer good thing it's not python or that would be really verbose :P

Mathematica, 247 bytes
(T=Table;k=Length[s=Characters@#];If[k==1,#,Column[Flatten@{#,T[""<>{s[[i]],T["  ",k/2-2+i],s[[-i]]},{i,2,k}],T[""<>{s[[-i]],T["  ",k+k/2-2],s[[i]]},{i,2,k}],T[""<>{s[[i]],T["  ",3k/2-1-i],s[[-i]]},{i,2,k-1}],StringReverse@#},Alignment->Center]])&

You don't need Alignment and you'd save bytes by using delayedset (:=) to reduce the repetition of s[[i]] and s[[-i]], You get down to 224 bytes with these ideas:
(T=Table;q:=s[[i]];r:=s[[-i]];k=Length[s=Characters@#];If[k==1,#,Column[Flatten@{#,T[""<>{q,T["  ",k/2-2+i],r},{i,2,k}],T[""<>{r,T["  ",k+k/2-2],q},{i,2,k}],T[""<>{q,T["  ",3k/2-1-i],r},{i,2,k-1}],StringReverse@#},Center]])&
Also, I have an alternate solution that's only 145 bytes at the time of this comment.

Japt, 84 79 bytes
-5 bytes thanks to @ETHproductions.

Ål
VoA{A?(UÅw +Uê)£Y¥V*2+AªY¥V-A?X:SÃ:Vç +U+Vç
Wf cU¬£V?(V*3 ç hUg~Y)+X:XÃcWz2

Leading newline is part of program. Takes a string as input and returns an array of strings.
Try it online! with the -R flag to join the resulting array with newlines.
Not my proudest work, but I got it down from ~100 bytes, at least. My idea here was to create the top and middle parts, then append the top portion, rotated 180°.

Nice. I don't see a lot of improvements right away, but you could change Ul É to UÅl, and switch V and W to save 2 more bytes: https://codepen.io/justinm53/full/NvKjZr?code=CsVsClZvQXtBPyhVxXcgK1XqKaNZpVYqMitBqlmlQW5WID9YOlPDOlbnICtVK1bnCldmIGNVcSCjVj8oViozIOcgaFVnflkpK1g6WMNjV3oy&inputs=ImdvbGYi,IkhlbGxvV29ybGQi,ImEi,ImFiIg==,ImNvZGUgZ29sZiI=&flags=LVI=

Also, AnV ? -> V-A?, and Uq £ -> U¬£

@ETHproductions Awesome, thanks! Can't believe I forgot about ¬.

Pyth, 79 69 65 bytes
j++K+]+*dJtlzzm+++*;-Jd@zd*;+ytdlz@z_hdSJjL*;t*3tlztC_B_zt__MC.tK

Test suite.

Python 2, 220 213 bytes

Surprisingly longer than I had imagined.

a=input()
l=len(a)
r=range(l)
print'\n'.join(p.center(l*3-2)for p in[a]+(l>1)*([a[i]+(2*i-2+l)*' '+a[~i]for i in r[1:-1]]+[a[~i]+(l*3-4)*' '+a[i]for i in r]+[a[i]+(3*l-2*i-4)*' '+a[~i]for i in r[1:-1]]+[a[::-1]]))

Try it online!

PHP 7.1, 230 156 155 bytes
for($x=$e=strlen($s=$argn)-1;$n<9;$r[$y][$x+=$n+1&3?$n&4?-1:1:0]=$s[$i],$i+=($n+=!$i||$i==$e)&1?:-1)$r[$y+=$n-1&3?$n<6?:-1:0]=$r[$y]?:"";echo join("
",$r);

Run as pipe with -nR or try it online.
breakdown
for($x=$e=strlen($s=$argn)-1;   # import to $s, set $e to length-1, init $x
    $n<9;                       # loop through 8 repetitions of string
    $r[$y][
        $x+=$n+1&3?$n&4?-1:1:0      # 3. increment/decrement $x depending on $n
    ]=$s[$i],                       # 4. copy character to current position
    $i+=(
        $n+=!$i||$i==$e             # 5. if first or last character of string, increment $n
    )&1?:-1                         # 6. if odd repetition next, else previous character
)
    $r[
        $y+=$n-1&3?$n<6?:-1:0       # 1. increment/decrement $y depending on $n
    ]=$r[$y]?:"";                   # 2. if empty, init row to string
echo join("\n",$r);             # output

Mathematica, 168 166 147 127 bytes
(n=Length@#;b=Array[" "&,3{n,n}-2];Do[l={{1,n+k-1},{k,n-k+1}};l=Join[l,Cross/@l];b=ReplacePart[b,Join[l,-l]->#[[k]]],{k,n}];b)&

This takes a list of one-character strings and outputs a matrix of one-character strings.
I saved 18 bytes by exploiting the symmetry to use -l and Cross/@l which takes something like a cross-product of each of the two single 2D vectors to take {x,y} to {-y,x}. Basically, the two initial directions are East (top edge) and Southwest (top right edge). Then we add in 90-degree counterclockwise rotations of them with Cross: North for left edge and Southeast for bottom left edge. Then we add in the other four pieces using -l to flip the four we covered.
You can test it out on the sandbox with something like:
(n=Length@#;b=Array[" "&,3{n,n}-2];Do[l={{1,n+k-1},{k,n-k+1}};l=Join[l,Cross/@l];b=ReplacePart[b,Join[l,-l]->#[[k]]],{k,n}];b)&[{"H","e","l","l","o"," ","G","o","l","f"}]//MatrixForm

Canvas, 14 bytes
４Ｈ┐⁸ｋ⁸±＼＋⁸Ｌ１╋↶

Try it here!