text:
Find all the Anagrams!
Despite having 17 questions tagged anagrams, we still don't have this question, so here it is.
Your Task
You must write a program or function that, when receiving a string, prints out all possible anagrams of it.  For the purposes of this question, an anagram is a string that contains the same character as the original string, but is not an exact copy of the original string.  An anagram does not have to be or contain actual words.
Input
You may accept the string, which may be of any length > 0, by any standard input method.  It may contain any ASCII characters.
Output
You may output all of the possible anagrams of the inputted string in any standard way. You must not output the same string twice, or output a string equal to the input.
Other Rules
Standard Loopholes are disallowed
Scoring
This is code-golf, least bytes wins.

May we abide by the normal "program or function" standard?

@JonathanAllan I think if its not explicitly mentioned, you may submit a program or a function.  I've generally left that implicit in my questions with no problems

Yes, of course either a program or a function will work fine.

Closely related

@gryphon how are you editing things

Umm, I'm hitting the edit button under them.  It's not that hard.

05AB1E, 3 bytes
œÙ¦

A function that leaves the stack with a list of the anagrams on top (and as its only item). As a full program prints a representation of that list.
Try it online!
How?
    - push input
œ   - pop and push a list of all permutations (input appears at the head)
 Ù  - pop and push a list of unique items (sorted by first appearance)
  ¦ - pop and push a dequeued list (removes the occurrence of the input)
    - As a full program: implicit print of the top of the stack

Should have guessed 05AB1E would be excessively short.

Ruby, 45 bytes
->x{(x.chars.permutation.map(&:join)-[x])|[]}

Try it online!
Despite having a built-in, the word "permutation" is really long :(

The |[] seems unnecessary?

@sethrin, not quite. The spec says that duplicates should be removed. |[] is shorter than .uniq.

pyth, 8 4
-{.p

Online test.
  .pQ     # all permutations of the (implicit) input string
 {        # de-duplicate
-    Q    # subtract (implicit) input

Great golfing job.  Congrats on tying the very impressive 05AB1E answer.

Sorry, but this outputs the same string twice if there is the same character in the input two times.  Please fix that.

Thanks for fixing that.  Too bad about it upping your byte count though.

I came up with the same answer but also forgot to de-duplicate. Great minds think alike?

Japt, 6 bytes
á â kU

Try it online!
Explanation
 á â kU
Uá â kU   // Ungolfed
          // Implicit: U = input string
Uá        // Take all permutations of U.
   â      // Remove duplicates.
     kU   // Remove U itself from the result.
          // Implicit: output resulting array, separated by commas

Congrats on stealing the win.  +1

@Gryphon Not so fast, I'd be shocked if this isn't 3 bytes in 05AB1E...

I did mean for now.  It's not like i'm marking you as accepted yet.

If @Dennis does this in Jelly, it'll probably be like 2 bytes.  One does not simply outgolf Dennis.

@JonathanAllan just tied you.

Unfortunately, k only removes the first occurrence of the string from the array; if a character appears more than once in the input then the array will contain multiple copies of the input. Try abb.

Good catch @Shaggy.  Unfortunately I will have to disqualify this.  The 05AB1E answer is only 3 bytes anyway.

The 3 byte prediction was good, but is there a 2?!

@Shaggy Gosh darn it, I thought á removed duplicates...

MATL, 7 bytes
tY@1&X~

Try it online!
Explanation
t     % Implicitly input a string, say of length n. Duplicate
Y@    % All permutations. May contain duplicates. Gives a 2D char array of
      % size n!×n with each permutation in a row
1&X~  % Set symmetric difference, row-wise. Automatically removes duplicates.
      % This takes the n!×n char array and the input string (1×n char array)
      % and produces an m×n char array containing the rows that are present
      % in exactly one of the two arrays
      % Implicitly display

Haskell, 48 40 bytes
import Data.List
a=tail.nub.permutations

Try it online!
Saved 8 bytes thanks to Leo's tail tip.

You can use tail instead of delete x, since the original string will always come first in the list of permutations. This will let you switch to a point-free solution, and then to an unnamed function, lots of bytes to be saved!

@Leo Great, thanks!

CJam, 8 bytes
l_e!\a-p

Try it online!
Explanation
l    e# Read string from input
_    e# Duplicate
e!   e# Unique permutations. Gives a list of strings
\    e# Swap
a    e# Wrap in a singleton array
-    e# Set difference. This removes the input string
p    e# Pretty print the list

@JonathanAllan Thanks, corrected

@Gryphon Well, 7 after Jonathan's very appropripate correction ;-)

I have now answered that question.

Umm, the TIO is still outputting the original string for me?

@Gryphon Sorry, it should be working now. I'm clearly too tired for this; going to bed :-P

Jelly, 4 bytes
Œ!QḊ

A monadic link taking a list of characters and returning a list of lists of characters - all distinct anagrams that are not equal to the input.
Try it online! (the footer forms a program that joins the list by newlines and prints to avoid the otherwise smashed representation).
How?
Œ!QḊ - Link: list of characters     e.g. "text"
Œ!   - all permutations of the list      ["text","tetx","txet","txte","ttex","ttxe","etxt","ettx","extt","extt","ettx","etxt","xtet","xtte","xett","xett","xtte","xtet","ttex","ttxe","tetx","text","txte","txet"]
  Q  - de-duplicate                      ["text","tetx","txet","txte","ttex","ttxe","etxt","ettx","extt","xtet","xtte","xett"]
   Ḋ - dequeue (the first one = input)          ["tetx","txet","txte","ttex","ttxe","etxt","ettx","extt","xtet","xtte","xett"]

Impressive.  Will there be an explanation, because I don't Jelly?

Yes, of course!

I took it off ages ago, hence why I had the "(4?)" in the header and the text about removing Y if functions were allowed... I see you just reversed my edit to the question though :/

Mathematica, 47 bytes
Drop[StringJoin/@Permutations[Characters@#],1]&

I was waiting for one of these, but I was pretty sure it wasn't going to win.  Kinda surprised there isn't just one built in.

StringJoin/@Rest@Permutations@Characters@#& is 43 bytes.

Python 3, 85 76 63 bytes
As a function, and returning strings as list of characters (thanks to @pizzapants184 for telling me it is allowed):
from itertools import*
lambda z:set(permutations(z))-{tuple(z)}

As a function:
from itertools import*
lambda z:map("".join,set(permutations(z))-{tuple(z)})

85 bytes as a full program:
from itertools import*
z=input()
print(*map("".join,set(permutations(z))-{tuple(z)}))

Could be reduced a bit if outputting strings as ('a', 'b', 'c') is allowed (I am not sure it is).

If only python was a golfing language, eh.

Outputting as ('a', 'b', 'c') should be fine, this pyth answer does (basically).

Java 8, 245 239 236 232 bytes
import java.util.*;s->{Set l=new HashSet();p("",s,l);l.remove(s);l.forEach(System.out::println);}void p(String p,String s,Set l){int n=s.length(),i=0;if(n<1)l.add(p);for(;i<n;)p(p+s.charAt(i),s.substring(0,i)+s.substring(++i,n),l);}

-6 bytes thanks to @OlivierGrégoire
-4 bytes thanks to @ceilingcat
Typical verbose Java.. I see a lot of <10 byte answers, and here I am with 200+ bytes.. XD
Explanation:
Try it here.
import java.util.*;         // Required import for the Set and HashSet

s->{                        // Method with String parameter and no return-type
  Set l=new HashSet();      //  Set to save all permutations in (without duplicates)
  p("",s);                  //  Determine all permutations, and save them in the Set
  l.remove(s);              //  Remove the input from the Set
  l.forEach(                //  Loop over the Set
    System.out::println);}  //   And print all the items

// This method will determine all permutations, and save them in the Set:
void p(String p,String s,Set l){
  int n=s.length(),         //  Length of the first input String
      i=0;                  //  Index-integer `i`, starting at 0
  if(n<1)                   //  If the length is 0:
    l.add(p);               //   Add the permutation input-String to the Set
                            //  Else:
    for(;i<n;               //   Loop `i` in the range [0,length):
      p(                    //    And do a recursive-call with:
        p+s.charAt(i),      //     Permutation + `i`'th character
        s.substring(0,i)+s.substring(++i,n),l);}
                            //     Everything except this character

Use l.forEach(System.out::println); instead of your printing loop. Also, I don't like Set being defined at the class level without its enclosing class, a lambda defined no one knows where and a method. This just too much for me. I can understand the imports being separated from the rest, but there is nothing self-contained there, it looks more like a collection of snippets than anything else. I'm sorry, but for the first time in PCG, I give -1 :(

@OlivierGrégoire First of all thanks for the tip for the forEach. As for the class-level Set, what is the alternative? Post the entire class including main-method? Post the entire class excluding the main-method, but including the class itself, interface and function name?

I'd write a full class. That's the smallest self-contained I can find. No need to add the public static void main, just say "the entry method is...". The thing is that your answer as it currently is breaks all the "self-contained" rules. I'm not against binding the rules, but breaking? Yeah, I mind :(

Another idea: pass the Set as parameter? The helper function, I can totally understand that, but it's defining the Set outside of everything that makes me tick.

@OlivierGrégoire Ok, went for your second suggestion. Indeed makes more sense as well, so I will use that from now on. Thanks for the honest feedback.

K (oK), 13 bytes
Solution:
1_?x@prm@!#x:

Try it online!
Explanation:
Evaluation is performed right-to-left.
1_?x@prm@!#x: / the solution
           x: / store input in variable x
          #   / count length of x, #"abc" => 3
         !    / range, !3 => 0 1 2
     prm@     / apply (@) function permutations (prm) to range
   x@         / apply (@) these pumuted indixes back to original input
  ?           / return distinct values
1_            / drop the first one (ie the original input)

Perl 6,  39  38 bytes
*.comb.permutations».join.unique[1..*]

Try it
*.comb.permutations».join.unique.skip

Try it
Expanded
*               # WhateverCode lambda (this is the parameter)
.comb           # split into graphemes
.permutations\  # get all of the permutations
».join          # join each of them with a hyper method call
.unique         # make sure they are unique
.skip           # start after the first value (the input)

C++, 142 bytes
#include<algorithm>
void p(std::string s){auto b=s;sort(begin(s),end(s));do if(s!=b)puts(s.data());while(next_permutation(begin(s),end(s)));}

ungolfed
#include <algorithm>

void p(std::string s)
{
    auto b = s;                    // use auto to avoid std::string
    sort(begin(s), end(s));        // start at first permutation
    do
      if (s != b)                  // only print permutation different than given string
        puts(s.data());
    while (next_permutation(begin(s), end(s))); // move to next permutation
}

JavaScript (ES6), 101 bytes
Adopted from a past answer of mine.
S=>(R=new Set,p=(s,m='')=>s[0]?s.map((_,i)=>p(a=[...s],m+a.splice(i,1))):R.add(m),_=p([...S]),[...R])

f=
S=>(R=new Set,p=(s,m='')=>s[0]?s.map((_,i)=>p(a=[...s],m+a.splice(i,1))):R.add(m),_=p([...S]),[...R])

console.log(
  f('ABC'),
  f('ABCD'),
  f('ABCC'),
  f('AABBC')
)

Perl 5, 89 + 2 (-F) = 91 bytes
$,=$_;$"=",";map{say if!$k{$_}++&&$,ne$_&&(join"",sort@F)eq join"",sort/./g}glob"{@F}"x@F

Try it online!

You may want to add an explanation.

Husk, 3 bytes
Look ma, no Unicode!
tuP

Try it online!
05AB1E, but reversed, and cooler, cause it's ASCII only.

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


text:
The dot is chasing me!
Your Task
Write a program that displays a dot that moves toward the position of your mouse at 4 pixels per second. The dot must be 100 pixels big and the window must fill the computer screen.
Input
None
Output
A window showing an animated dot moving towards the mouse at a fixed, non-changing speed.
Scoring
This is code-golf, so the shortest code in bytes wins.

Edits that invalidate existing answers are not advised.  Just sayin

What is the formula for speed? Is Manhattan distance allowed?

Please leave it at "the window must fill the computer screen"; it's more objective anyway.

I assume ruffle means roughly; however, this is also subjective, and we like 100% objective challenges here.

thanks MD XF  did not relies that things need to be 100%

IMO this question is really clear right now. What else is missing? Unfortunately, the answers dont match the question anymore. I like the concept behind this question. Maybe re-asking might be an idea? Any opinions on that?

@Blauhirn Note that no edits were made between when I cast the final close-vote and all of these reopen votes. First of all, "100 pixels big" for a "dot" is very vague; is it a circle, a square, a star, or what? Secondly, should the dot trace the mouse's movement, or on each update move towards the mouse (real-time updating)?

Mathematica, 89 bytes
Graphics[Disk[Dynamic[MousePosition["Graphics",{0,0}]],.1],PlotRange->10,ImageSize->1000]

HTML + JavaScript, 140 bytes
Infinite speed

t=c.getContext`2d`
c.onmousemove=e=>(x=e.clientX,y=e.clientY)
setInterval(_=>t.clearRect(0,0,1e5,1e5)||t.fillRect(x,y,10,10),9)
<canvas id=c>

Non-cheaty, 188 bytes

x=y=0,t=c.getContext`2d`
c.onmousemove=e=>(z=e.pageX,w=e.pageY)
f=_=>t.clearRect(0,0,1e5,1e5)||(m=((a=z-x)**2+(b=w-y)**2)**.5)|t.fillRect(x+=a/m,y+=b/m,10,10)
setInterval(f,9)
<canvas id=c>

Larger and faster:

x=y=0,s=3,t=c.getContext`2d`
c.onmousemove=e=>(z=e.pageX,w=e.pageY)
f=_=>t.clearRect(0,0,1e5,1e5)||(m=((a=z-x)**2+(b=w-y)**2)**.5)|t.fillRect(x+=s*a/m,y+=s*b/m,10,10)
setInterval(f,9)
<canvas id=c height=999 width=999>

did you see my edit

I think there is a problem with you second code ASCII-only it dos'nt  follow my mose it just flouts above it

never mind it works now

Python 3 + Tkinter, 264 262 259 254 bytes
import tkinter as t,numpy as n
f=t.Tk()
p=n.array([1,1])
q=n.array([0.]*2)
c=t.Canvas(f)
c.pack()
def s(e):p[:]=e.x,e.y
c.bind("<Motion>",s)
z=c.create_oval(0,0,2,2)
def r():d=p-q;u=(d*d.T+.1)**-0.5;c.move(z,*u*d);q[:]+=u*d;c.after(9,r)
r()
f.mainloop()

Thanks to @Gryphon for saving 2 bytes, to @Jonathan Allan for another one, and to @Challenger5 for five.
Changed 1e-9 to .1 for another two.

You can remove the space before the * to remove 2 bytes.

Welcome to PPCG! If I am reading it correctly (and the only references used are tkinter.Tk and two numpy.arrays) then import tkinter,numpy as n...f=tkinter.Tk()...p=n.array([1,1])...q=n.array([0.]*2) saves two.

There is Canvas from tkinter as well, so it only saves a byte, but thanks!

I don't have enough reputation to comment on the corresponding answer yet, but @Gryphon could save a few bytes by writing 4*(x>b)-2 in their solution.

You can put the body of r in a single line to save indentation: def r():d=p-q;u=(d*d.T+.1)**-0.5;c.move(z,*u*d);q[:]+=u*d;c.after(9,r)

Upvote for *u*

Python 2 + Pygame, 178 Bytes
-2 bytes thanks to @ASCII-only, because I was being an idiot
-12 bytes thanks to @officialaimm, also because I was being an idiot
-11 bytes thanks to @JonathanAllan, for telling me the default window size was the screen size
-2 bytes thanks to @WheatWizard, also because I was being an idiot
-18 bytes thanks to @nore, because I didn't have to use the if/else statements
-24 bytes thanks to @nore, who reminded me to put the whole loop on one line.
-42 bytes thanks to @WheatWizard
-3 bytes thanks to @ASCII-only
from pygame.locals import*
from pygame import*
init()
a=display.set_mode()
b=c=0
while 1:a.fill((0,0,0));x,y=mouse.get_pos();draw.rect(a,(9,9,9),
(b,c,b+10,c+10));display.update()

This is definitely no longer the best way to do this, so I may come out with a version that's better suited to the new requirements of the question.  The dot is 10 pixels by 10 pixels.  The screen size is the size of the computer screen.
 If you can see the dot, I'm impressed, as it is almost the exact same colour as the background, to save on byte counts for RGB colours.

Noncompeting status is reserved for languages that were made after the challenge; however, I rolled back the OP's useless edits.

I'm assuming 100 pixels means 10x10

You can strip off few bytes by using:  b+=2if x>b else-2 for updating b & c both.

@officialaimm, Ummm, where?  I'm looking and I can't see anywhere where I can do that, but I'm sure I'm just being an idiot again.

3rd and 4th lines within the while loop

I don't have pygame installed but the docs for pygame.display.set_mode say "If no resolution is passed or is set to (0, 0) and pygame uses SDL version 1.2.10 or above, the created Surface will have the same size as the current screen resolution.". Maybe an 11 byte save? (otherwise could they be floats like 1e5 saving two?)

b,c=0,0 can be b=c=0 for a few bytes off.

You can also use 4*(x>b)-2 (and same with y and c) to strip a few more bytes off. You can also probably put the whole loop body on a single line to save the indentation.

Thanks, @nore.  You saved me a total of 24 bytes!  You also put me into third place, as of now.

Whats the deal with 4*(x>b)-2;4*(y>c)-2? As far as I can tell it doesn't do anything.  Both of these lines just create value but neither of these values are used.

You can also be far smarter with your imports, Here is a version with you inputs fixed up and my last change suggested.

BTW you should be able to change while True to while 1

source: Stack Exchange

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

sort: votes


text:
Find all the Anagrams, and the Subanagrams too!
This question is heavily based off this question, but should pose a number of additional difficulties.
Your Task
You must write a program or function that, when receiving a string, prints out all possible anagrams of it.  For the purpose of this question, an anagram is a string that contains the same character as the original string, but is not the original string.  A subanagram is an anagram of a substring of an inputted string.  Anagrams and subanagrams do not have to be or contain actual words.
Input
You may accept a string, which may be of any length > 0, by any standard input method.  It may contain any ASCII characters.
Output
You may output all of the possible anagrams and subanagrams of the inputted string in any standard way. You must not output the same string twice, or output a string equal to the input.
Other Rules
Standard Loopholes are disallowed
Scoring
This is code-golf, least bytes wins.

Is the empty string a possible anagram?

Is outputting the original string/sustrings allowed?

@CalculatorFeline "You must not output the same string twice, or output a string equal to the input."

@DigitalTrauma, "You may accept a string, which may be of any length > 0, by any standard input method".  (emphasis added)

Some Test cases would be helpful

"an anagram is a string that contains the same character as the original string, but is not the original string": it's unclear to me whether it applies to subanagrams as well (in which case AB is not a valid subanagram of ABCD, but BA is). Could you please clarify?

Should tt be an anagram of test? If yes, then quite some given solutions are not working. If not, then I guess that aa shouldn't be an anagram of aabb and again some solutions are not working. Some examples to explain this would be helpful :)

No, tt is not an anagram or a subanagram of "test".  However, I never specifically said you couldn't output additional strings, which was a mistake in the question.  I just said you couldn't output the same string twice, which I don't think any answer is doing, or output the original string, which I also don't think any answer is doing.  I would change the question to not allow substrings of the input, but it's too late now, as that would invalidate existing answers.

05AB1E, 7 bytes
Œ€œ˜Ù¹K

A function that accepts a string from input and leaves a list of strings on the stack. As a full program a representation of the list is printed.
Try it online!
How?
        - push input
Œ       - all substrings
 €œ     - for €ach: all permutations
   ˜    - flatten
    Ù   - de-duplicate
     ¹  - push 1st input onto top of stack
      K - pop a,b; push a without any b's (remove the copy of the input from the list)
        - as a full program: implicit print of the top of the stack

And... you managed something even shorter.

It's the same algorithm, just less bytes.

Yes, the language change was all, but its still impressive.

@ais523 Looks like I got both the wrong way around!

@ais523 I think that it is fixed.

Brachylog (2), 7 bytes
{sp}ᶠdb

Try it online!
Explanation
{sp}ᶠdb
{  }ᶠ    Find all
  p        permutations of
 s         a substring of {the input}
     d   Remove duplicates (leaving the list otherwise in the same order)
      b  Remove the first (the input itself)

What does the (2) mean?

@Gryphon (afaik) there are 2 versions of branchylog, this is using V2.

Ok, wasn't sure if it was version number or a possible byte count using a different, and possibly illegal method.

That's the second time I've been asked now. I guess I'll have to start writing it as (v2).

Jelly, 9 bytes
ẆŒ!€;/QḟW

A monadic link accepting a list and returning a list of all distinct sub-anagrams except the input itself.
Try it online! (the footer pretty-prints the resulting list by joining with newlines.)
How?
ẆŒ!€;/QḟW - Link: list of characters, s
Ẇ         - all contiguous sublists of s
 Œ!€      - all permutations for €ach sublist now a list of lists of lists)
     /    - reduce by:
    ;     -   concatenation (flattens the list by one level)
      Q   - de-duplicate (gets the unique entries)
        W - wrap s in a list (otherwise filtering will attempt to remove characters)
       ḟ  - filter discard from left if in right (remove the one equal to the input)

Pyth, 12
-{.n.pM.:Q)]

Online test.
         Q       # input
       .: )      # all substrings
    .pM          # all permutations of all substrings
  .n             # flatten
 {               # deduplicate
-          ]Q    # subtract (list of) (implicit) input

@ais523 Redone - I think it is correct now.

Japt, 10 bytes
à má c â Å

Try it online!
I got to use à, á, and â all in one answer, in order too. What a coincidence...
Explanation
 à má c â Å
Uà má c â s1  // Ungolfed
              // Implicit: U = input string
Uà            // Take all combinations of characters in the input string.
   má         // Map each combination to all of its permutations.
      c       // Flatten into a single array.
        â     // Uniquify; remove all duplicates.
          s1  // Remove the first item (the input) from the resulting array.
              // Implicit: output resulting array, separated by commas

You even managed Å too.

Mathematica, 60 bytes
DeleteCases[""<>#&/@Permutations[c=Characters@#,Tr[1^c]],#]&

Permutations takes an optional numerical argument which tells it how many of the input values to use for the permutations. If we give it the length of the input, it will generate the permutations for all subsets of the input without duplicates. All we need to do is remove the input.

Java 8, 313 312 306 297 bytes
import java.util.*;s->{Set l=new HashSet();for(int z=s.length(),i=0,j;i<z;i++)for(j=i;j<z;)p("",s.substring(i,++j),l);l.remove(s);l.forEach(System.out::println);}void p(String p,String s,Set l){int n=s.length(),i=0;if(n<1)l.add(p);for(;i<n;p(p+s.charAt(i),s.substring(0,i)+s.substring(++i,n),l));}

Modified version of my answer here, where p("",s,l); has been replaced with for(int z=s.length(),i=0,j;i<z;i++)for(j=i;j<z;p("",s.substring(i,j+++1),l));
-6 bytes thanks to @OlivierGrégoire in my linked answer
-9 bytes thanks to @ceilingcat
Try it online.
Explanation of this part:
for(int z=s.length(),i=0,j;i<z;i++) // Loop `i` in the range [0,length):
  for(j=i;j<z;)                     //  Inner loop `j` in the range [i,length):
    p("",                           //   Call the permutation-method,
      s.substring(i,++j),l));       //   with a substring at index-range [i,j]

Vyxal, 9 bytes
ǎƛṖ;fU'⁰≠

Explanation
<implicit input>
ǎ                 - Get substrings
 ƛṖ;              - Map over substrings: Get permutations
    f             - Flatten it
     U            - Uniquify, remove all duplicates
      '⁰≠         - Filter lambda: Keep all elements that don't equal input
<implicit output>

Try it Online!

Perl 6, 75 bytes
{unique(flat $_,.comb.combinations.skip».permutations.map(*».join)).skip}

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

  unique(            # return each (sub)anagram once

    flat             # unstructure the following (List of Lists into flat List)
      $_,            # the input (so we can skip it at the end)

      .comb          # split the input into graphemes
      .combinations  # get all the combinations
      .skip\         # skip the first empty combination
      ».permutations # get all the permutations of each combination
      .map(*».join)  # join the inner permutations

  ).skip             # skip the first value (the input)
}

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


text:
This will eventually stop…
Given an input string S, print S followed by a non-empty separator in the following way:

Step 1: S has a 1/2 chance of being printed, and a 1/2 chance for the program to terminate.

Step 2: S has a 2/3 chance of being printed, and a 1/3 chance for the program to terminate.

Step 3: S has a 3/4 chance of being printed, and a 1/4 chance for the program to terminate.

…

Step n: S has a n/(n+1) chance of being printed, and a 1/(n+1) chance for the program to terminate.

Notes

The input string will only consist of characters that are acceptable in your language's string type.

Any non-empty separator can be used, as long as it is always the same. It is expected that the separator is printed after the last print of S before the program terminates.

The program has a 1/2 chance of terminating before printing anything.

A trailing new line is acceptable.

Your answer must make a genuine attempt at respecting the probabilities described. Obviously, when n is big this will be less and less true. A proper explanation of how probabilities are computed in your answer (and why they respect the specs, disregarding pseudo-randomness and big numbers problems) is sufficient.

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

Can the separator be an empty string?

@rturnbull Well no, because in that case there is no separator.

Do we have to print these one after the other, or can we just print all of them when the program terminates?

@Dennis One after the other.

Pyth, 7 bytes
WOh=hZQ

Try it online!
How it works
Pseudocode:
while rand_int_below(1 + (Z += 1)):
    print(input)

Pyth beats 05AB1E again doesn't it?

Doesn't the print statement need it's own probability along with the termination probability?

@tuskiomi Nah, n/(n+1) is just 1-1/(n+1), or 1 - (probabilty of termination).

C#, 94 85 bytes
My first answer!
using System;s=>{var r=new Random();for(var i=2;r.Next(i++)>0;)Console.Write(s+" ");}

Previous attempt (I liked that goto):
using System;s=>{var i=2;var r=new Random();a:if(r.Next(i++)>0){Console.Write(s+" ");goto a;}}

Ungolfed:
using System;
class P
{
    static void Main()
    {
        Action<string> f = s =>
        {
            var r = new Random();
            for (var i = 2; r.Next(i++) > 0;) Console.Write(s + " ");
        };

        f("test");

        Console.ReadKey();
    }
}

Note: in C# the Random.Next(N) method returns a nonnegative integer in the [0, N-1] range, so we can just check that the number returned is greater than 0.

You need to include using System; into your byte count. You can declare r inline, no need to set it to a variable: new Random().Next(i++). You don't need the trailing semicolon on the golfed func.

Oh and nice first answer! Would have been shorter than my attempt :)

@TheLethalCoder thank you for your comments! I tried to use new Random().Next(i++) but when I tried to execute that, the result was always either the program stops without printing anything, or the program never stops. When I declare r=new Random() and use the r variable, the program stops more randomly as the OP asks.

Ahhh probs because the loop is so tight.

@TheLethalCoder - Yes, thight loop means a chance that the seed of the generator will be the same. See: https://msdn.microsoft.com/en-us/library/system.random.aspx#Instantiate

R, 47 46 43 bytes
43 bytes due to Robin Ryder in the comments.
s=scan(,"")
while(sample(T<-T+1)-1)print(s)

Try it online!
Explanation
s=scan(,"")  # Takes input from stdin.
             T<-T+1    # T is 1 by default, so this
                       # evaluates to 2, and will increment
                       # at each step.
      sample(T<-T+1)   # Take a sample of size 2, i.e. generate
                       # a list of integers from 1 to 2 in random order
      sample(T<-T+1)-1 # Subtract one from every element of this list.
while(sample(T<-T+1)-1)# while() will treat the first value in this list
                       # as a logical value, i.e. FALSE for zero and TRUE
                       # for nonzero values. The other elements of the list
                       # are ignored, triggering a warning.
                       print(s) # print s

Does this ever terminate?

@mfloren Yes, like all the other answers here, it's stochastic, with termination chance decreasing as it progresses, but it will eventually terminate. There's a .5 chance it will print nothing! Try running it several times and compare the outputs.

function(s) is shorter than s=scan(,'');

And pryr::f(while(runif(1)<T/(T<-T+1))print(s)) is even shorter.

Ran it about 25 times, each time the number of iterations continued until I stopped the operation.

Update: Ran it on R 3.3.2 and worked fine. Just updated to R 3.4.0 and didn't ever terminate (after another 20 tries).

@JarkoDubbeldam Unfortunately you can't (ab)use T and F with anonymous functions, as it modifies a global variable and means that the function can only be called once. See here: "the solution function performs consistently regardless of how many times it has been called previously".

@mfloren That's very odd! I can't see anything in the update notes to suggest what might have changed about the language spec to cause that. For now, I've modified the post to specify that it's just R version 3.2 and below.

@mfloren After testing around with the latest version of R, it seems to work fine on my machine. Half the time it doesn't output anything.

@rturnbull Bizarre! Well: sorry for the fuss! I'll start hunting around on my installations and see what is going on...

@rturnbull Ah, I think I have it! I was not resetting T=1 on every new run (so T was constantly building). Again, apologize for the fuss and thanks for the help!

As far as I can tell, your code is 47 bytes, not 46. Here is a 43 byte version.

@RobinRyder It's 46, not 47. I've updated the post with your (excellent!) version now.

05AB1E, 8 bytes
[NÌL.R#,

Try it online!
Explanation
[         # start loop
 NÌL      # push range [1 ... current_iteration+2]
    .R    # pick a random number
      #   # if true (1), exit loop
       ,  # print input

@Fatalize: It does for me. Try running it a few times. It has a 50% chance of not outputting anything so you may have been "unlucky".

The inherit problem of random tasks. Sometimes all odds are against you.

@J_F_B_M inherent?

@LeakyNun No, it's the "Inherit Problem" (the probability of events is not inherited from previous events). J_F_B_M was clearly referring to the Gambler's Fallacy.

Javascript, 60 58 54 bytes
f=(s,n=1)=>Math.random()<n/++n?console.log(s)+f(s,n):0

Will output string s. The seperator which is printed if the program terminates is NaN or 0.

f=(s,n=1)=>Math.random()<n/++n?console.log(s)+f(s,n):0

f('test')

Math.random() returns a value between 0 and 1. If that value is under n/(n+1), then s will be pritned.
4 bytes saved thanks to @Neil

Why not use n/++n?

@Neil thanks, saved 4 bytes!

If your environment was a browser you could use alert instead of console.log to save 6 bytes - the snippet could set alert = console.log to show non obtrusive output if desired (if allowed - doesn't save bytes, just helps keep one sane)

Java 8, 72 62 61 bytes
s->{for(int n=2;Math.random()<1f/n++;System.out.println(s));}

-10 bytes thanks to @cliffroot.
-1 byte thanks to @JollyJoker.
Delimiter is a new-line.
Explanation:
Try it here.
s->{                          // Method with String parameter and no return-type
  for(                        //  Loop
    int n=2;                  //   Start `n` on 2
    Math.random()<1f/n++;     //   Continue loop as long as a random decimal (0.0-1.0)
                              //   is smaller than 1/`n` (and increase `n` by 1 afterwards)
    System.out.println(s)     //   Print the input-String
  );                          //  End of loop
}                             // End of method

i am unable to check in the moment but why not put if condition inside for condition block?

@cliffroot It is in the for loop.

@Okx I meant condition when for loop should end so that it does not need explicit return.  The second expression inside for statement.

@cliffroot Ah, I  understand.

@cliffroot Thanks.. that was pretty stupid to miss.. ;)

Would int n=2 and 1f/n++ work?

Mathematica, 43 bytes
(n=1;While[RandomInteger@n>0,Print@#;n++])&

JungHwan Min saved 1 byte (above) and suggested something better (below)
Mathematica, 37 bytes
For[n=1,RandomInteger@n++>0,Print@#]&

RandomInteger@n!=0 is the same as RandomInteger@n<1 in this case, and n++ can be merged with RandomInteger@n. Also, For is (almost always) shorter than While: -5 bytes For[n=1,RandomInteger@n++>0,Print@#]&

"For" wins! I posted your answer too

For[n=1,!n∣Hash[# n++],Print@#]& would also work at 34 bytes, assuming the hash is fairly random.  The randomness depends on the input, however.  For example try % /@ Alphabet[]

Clojure, 61 56 bytes
Oh why didn't I go with a for in the first place? But actually to be pedantic doseq has to be used as for is evaluated lazily.
#(doseq[n(range):while(>(rand-int(+ n 2))0)](println %))

Original:
#(loop[n 2](if(>(rand-int n)0)(do(println %)(recur(inc n)))))

isn't (>(+(rand-int n)2)0) always true?

Ah good catch, I meant to increment n!

><>, 124 112 bytes
i:0( ?v
 &5a ~/
&p0[^ >"\_\^x0!>"0&1+:&p1&:&p2&:&p3&:&p4&:&p0&1+:&p3&:&p4&:
=?v[/!}l]:?!;1
{:   ?^  >
:o>_ {:?!^

Try it online! (You can also watch it at the fish playground, but due to some bugs you have to add a } after the l in the fourth line and add a bunch of newlines after the code to make it work properly.)
Randomness is tricky in ><>. The only random instruction is x, which picks the fish's direction randomly from four choices (left, right, up and down), so turning that into something with probability 1/n is not straightforward.
The way this code does it is by using ><>'s self-modifying capabilities to build a Tower of Randomness below the code, so at the fourth stage, for example, the code looks like:
i:0( ?v
 &5a ~/
&p0[^ >"\_\^x0!>"0&1+:&p1&:&p2&:&p3&:&p4&:&p0&1+:&p3&:&p4&:
=?v[/!}l]:?!;1
{:   ?^  >
:o>_ {:?!^
>!0x^
\  _\
>!0x^
\  _\
>!0x^
\  _\
>!0x^
\  _\

The fish starts at the bottom of the tower. At each level of the tower, the x is trapped between two mirrors, so the fish can only escape by going left or right. Either of these directions sends the fish up to the next level of the tower, but going left also pushes a 0 to the stack. By the time the fish gets to the top of the tower, the stack contains some number of 0s, and this number follows a binomial distribution with n trials and p = 1/2.
If the length of the stack is 0 (which has probability 1/2n), the program halts. If the length is 1 (with probability n/2n), the fish prints the input and a newline and builds another level of the tower. If the length is anything else, the fish discards the stack and goes back to the bottom of the tower. In effect, out of the possibilities that actually do something, n of them print the input string and one of them halts the program, giving the required probabilities.

Python 3, 72 69 66 bytes

Saved 3 bytes thanks to Jonathan Allan: Import shorthand and start count from 2.
Saved 3 bytes thanks to  L3viathan : Pointed randint() was inclusive and also shortened while condition.

from random import*
s=input();i=1
while randint(0,i):print(s);i+=1

Try it online!

There's a setting to turn off the output cache - like so

I think it's acceptable to be "off" for large n (I can't get English brain in gear, "...(and why they respect the specs, disregarding pseudo-randomness and big numbers problems)..." disregarding - right?) If so then you can do random()<1/i.

Doesn't this start with probability ⅓? randint is inclusive. You could then shorten that line to while randint(0,i):print(s);i+=1

I just came up with the same solution.

Updated TIO link. Now the byte count is the same as the floating point version too.

QBIC, 19 17 bytes
Dropped =1, switched conditionals, saved 2 bytes
{p=p+1~_rp||?;\_X

Explanation
{       Infinitely DO
p=p+1   Add 1 to p (p starts as 0, so on first loop is set to 1, then 2 etc...)
~       IF
  _rp|| a random number between 0 and p
        (implicitly: is anything but 0)
?;      THEN print A$ (which gets read from the cmd line)
\_X     ELSE QUIT
        END IF and LOOP are auto-added at EOF

Braingolf, 23 bytes
#|V12[R!&@v!r?<1+>1+]|;

Try it online!
Generates random number x where 0 <= x < n+1, terminates if x is 0, otherwise increments n and loops. Separator is |
Explanation:
#|V12[R!&@v!r?<1+>1+]|;  Implicit input of commandline args to stack
#|                       Push |
  V                      Create stack2 and switch to it
   12                    Push 1, then 2
     [..............]    Do-While loop, will run indefinitely unless conditional skips
                         Closing bracket
      R                  Return to stack1
       !&@               Print entire stack without popping
          v              Switch to stack2
           !r            Generate random number 0 <= x < n where n is last item on stack
             ?           If last item is greater than 0..
              <          ..Move first item to end of stack
               1+        ..and increment, this is the loop counter number
                 >       ..Move back
                  1+     ..and increment, this is the upper range of the RNG
                    ]    ..end loop
                     |   Endif
                      ;  Suppress implicit output

Alice, 18 bytes
/?!\v
\iO/>]qhUn$@

Try it online!
Explanation
/     Reflect to SE. Switch to Ordinal.
i     Read all input as a string and push it to the stack.
!     Store the string on the tape.
/     Reflect to E. Switch to Cardinal.
>     Ensure that the IP moves east. This begins the main loop.

  ]   Move the tape head to the right. We'll be using the tape head's
      position as a counter variable. Note that this tape head is independent
      of the one used in Ordinal mode to point at the input string.
  q   Push the tape head's position to the stack.
  h   Increment it (so that it's 2 initially).
  U   Get a uniformly random number in [0,n).
  n   Logical NOT. Gives 1 with probability 1/n and 0 otherwise.
  $@  Terminate the program if we got a  1.
  \   Reflect to NE. Switch to Ordinal.
  ?   Retrieve the input from the tape.
  O   Print it with a trailing linefeed.
  \   Reflect to E. Switch to Cardinal.

v     Send the IP south where it runs into the > to start the next
      loop iteration.

PHP, 31 bytes
for(;rand()%~++$c;)echo$argn._;

Try it online!

Perl, 26 bytes
24 bytes code + 2 for -nl.
print while rand++$i+1|0

Try it online!

Charcoal, 14 bytes
Ａ²γＷ‽γ«θ_Ａ⁺γ¹γ

Try it online! Link is to verbose version of code. Uses _ as the separator. Note: output caching is disabled, so please don't hammer Dennis's server!

MATL, 9 bytes
`G@QYrq]x

Try it online!
Explanation
`        % Do...while
  G      %   Push input
  @      %   Push iteration index k, starting at 1
  QYrq   %   Random integer uniformly distributed in {0, 1, ..., k}. This is the
         %   loop condition. If non-zero (which occurs with probability k/(1+k))
         %   proceed with next iteration; else exit loop
]        % End
x        % Delete, as there are one too many strings. Implicitly display the stack

Perl 6,  50 41 38 36  26 bytes
{put $_//last for (($,$_),*⊎$_...*).map(*.pick)}

Try it
{eager ->{(++$).rand>.5??.put!!last}...*}

Try it
{eager ->{(++$).rand>.5??.put!!0}...0}

Try it
{eager ->{(++$).rand>.5&&.put}...!*}

Try it
.put while (++$/).rand>.5

(with -n commandline argument)
Try it

Python 3, 55 bytes
v=s=input();i=2
while hash(v)%i:print(s);i+=1;v=hash(v)

Explanation
To save having to import random, I've exploited the fact that the hash built-in is randomly seeded each time a python process is fired up (at least in MacOS). Each hash of the last hash should generate a series of pseudo-random integers.
If the hash is pseudo-random enough, the modulo with i is zero with probability 1/i.
Notes
I'm a little bothered by the redundant hash, but without a do-while, or in-condition assignment in Python, I'm a little stuck.

Do you know whether iterated hashing is always going to cover the full space of random numbers, or can it potentially get stuck in a cycle? Most programming languages use randomized hash algorithms nowadays in order to avoid people intentionally causing hash collisions, but I'm not sure how the randomness guarantees of the hash algorithms compare to those of a PRNG.

It's a fair point. And I'm not sure, it would take some analysis of the Python hash implementation to check (without a more exhaustive check).
I thought it was a fun solution, even if there's a chance it might not be 100% pseudo-random =p

I'm a little bothered... recursion?

C#
This is same length as the top C# answer, but:
using System;s=>{var x=(1<<31)/new Random().Next();for(;++x>0;)Console.Write(s+" ");}

Just wanted to point out that some math can produce the correct probability.
int.MaxValue/new Random().Next()-1

Is equivalent to
(int)(1 / new Random().NextDouble()) - 1;

And the function f(x)=1/x-1 is:
f(1) = 0
f(1/2) = 1
f(1/3) = 2
f(1/4) = 3
So 1/2 a chance to be rounded down to 0, 1/6 a chance to be rounded down to 1, and 1/(n+1)(n+2) a chance to be rounded down to n.
Maybe some other language could capitalize on this.
EDIT:
Fixed my mistake
I thought of something to make it smaller.
EDIT EDIT: I am just all kinds of wrong. Pulled the Random out of the loop because if it's evaluated multiple times, it won't work.
EDIT EDIT EDIT: I got rid of the variable i. I'm going to stop trying to shrink it now. Nope, lied. Got rid of another byte.

Vyxal ROM, 7 bytes
{&›¥℅|,

Try it Online!
Explanation:
{    |   # While...
 &›      # ...Increment the register (initially 0)...
   ¥     # ...Retrieve value n from the register...
    ℅    # ...Random value from range[0..n]...
     |   # ...Returns true, do:
      ,  #   Print the input string

Can i use this ROM on my nintendo gamecube

@Razetime I don't see why not, but no guarantees it'll actually do anything. ;p

Charcoal, 17 bytes
ＳαＡ²βＷ‽β«⁺α¶Ａ⁺β¹β

Try it online! Verbose code included. Respects specs because it uses a random range from 0 to n.

C++, 97 96 57 bytes
Here my first try on codegolf :)
#include<iostream>
int main(){std::string S;std::cin>>S;int i=1;while(rand()%++i)puts(S.data());}

I saved one byte by using for
#include<iostream>
int main(){std::string S;std::cin>>S;for(int i=1;rand()%++i;)puts(S.data());}

Saved 39 bytes since nobody seems to count the includes
void p(string S){for(int i=1;rand()%++i;)puts(S.data());}

ungolfed
#include <iostream>
int main()
{
  // Create and read string from inputstream
  std::string S;
  std::cin >> S;

  // rand % i: create random int in range [0, i-1]
  // Zero is seen as false and all positive int as true
  int i = 1;
  while (rand() % ++i)
    puts(S.data());
}

You may take the string as an argument from the command line

Includes are counted, unless you find a compiler that includes them by default

@FelipeNardiBatista Which gcc usually does, I think.

braingasm, 22 bytes
edit: Same byte count, but I realized I could sneak in the new tape Limit feature.
,[>,]>L+[+$rzQ>[.>]:>]

Uses 0 as separator.
Works like this:
,[>,]                   Read a byte and move to next cell until end of input.
     >                  After the loop we're in an empty cell;
                          Leave it empty and move to the next.
      L                 Set tape limit here:
                          The tape will then wrap around if we move further.
       +                Increase current cell by one.
                          This cell will be our counter.
        [            ]  Loop until the counter is zero.
                          That won't happen, so it's an infinite loop.
         +              Increase again, so the first time the counter is 2.
          $r            Get a random number, 0 <= r > current cell
            zQ          Quit the program if that random number was 0
              >         Wrap around to the start of the tape.
               [.>]     Print the input stored on the tape
                          The loop will stop at the blank cell.
                   :    Print the blank cell as a number ("0")
                    >   Go to the next (last) cell

C, 41 bytes
n;f(char*s){for(n=1;rand()%++n;puts(s));}

Assumes rand is seeded. Try it online!

"Assumes rand is seeded." -- Is that a valid assumption to make? rand is required by the standard to have a fixed seed value of 1 by default and all implementations I know of do just that. If this function only does what the challenge asks when combined with other code, I think that other code needs to be included in the answer and in the byte count.

Python, 54 bytes
lambda s:int(1/random()-1)*(s+'|')
from random import*

Try it online!
Generated the number of copies as floor(1/p)-1 with p uniformly chosen from the unit interval. The number of copies is n when 1/p-1 falls between n and n+1, which happens when 1/(n+2) < p < 1/(n+1). This happens with probability 1/(n+1)-1/(n+2) or 1/((n+1)*(n+2). This is the desired probability of outputting n copies: 1/2 prob of 0, 1/6 prob of 1, 1/12 prob of 2,...

Why is form random import* at the bottom?

@CalculatorFeline The order doesn't matter. The function definition works either way.

@CalculatorFeline In order to drop to bytes by not writing f= and placing it in the TIO Header

That makes sense.

F#, 161 bytes
Definitely not the best language to golf, but I decided to give it a try (besides, I do not know anything about F#, so any tips on how to improve my answer will be welcome).
let f s=
 let r,z=System.Random(),(<>)0
 let p _=printfn"%s"s
 seq {for i in 2|>Seq.unfold(fun i->Some(i,i+1))do yield r.Next(i)}|>Seq.takeWhile z|>Seq.iter p

Execute with:
[<EntryPoint>]
let main argv =
    "test" |> f
    0

Writes a new line as separator.

Ruby, 29+1 = 30 bytes
Uses the -n flag.
i=1;puts$_ while i>rand(i+=1)

Try it online!

Since you're taking exactly one line of input, you can use the $. special variable instead of i. Arguably you can also replace puts$_ with print but it's not clear the rules support that.

PowerShell, 31 bytes
for($i=2;random($i++)){"$args"}

Get-Random $i outputs an n where 0 <= n < $i, separator is implicit newline.

29 bytes?

Python, 75 bytes
The other Python answer is shorter, but I wanted to try it a different way:
from random import*
f=lambda d=1,s=input():randint(0,d)and s+'!'+f(d+1)or''

Dart - 73 chars
import"dart:math";p(s,{i=2}){while(new Random().nextInt(i++)>0)print(s);}
This function implements the algorithm by taking a string as input and printing it as necessary. The separator is obviously newline.
To run it, you need a main method like main(){p("foo");}.
It's hard to be small when you need to import the math library and instantiate the Random class.
Try it online

APL (Dyalog), 17 bytes
Requires ⎕IO←0 which is default on many systems.
{⎕←⍺⋄×?⍵:⍺∇1+⍵}∘2

This is a monadic function derived from a dyadic function by currying the right argument.
{ anonymous function
 ⎕←⍺ print ⍺ (the string)
  ⋄  then
 ×?⍵: if the signum of a random int in the range [0,⍵-1] is 1, then:
 ⍺ ∇ 1+⍵ recurse with 1+⍵ as new right argument
 (implicit, else: stop)
}∘2 with 2 as bound right argument
Try it online! Sets ⎕RL←0 (Random Link) to avoid TIO's regeneration of the same random number.)

C# 79 bytes
does a divide by 0 error count as terminating?
using System;s=>{for(int i=1;2>1/new Random().Next(++i);Console.Write(s+' '));}

Scala 76 72 71 Bytes
def w[T](s:T)={var x=2;while(Random.nextFloat>1f/x){x+=1;print(s+" ")}

This uses a template because it works fine for strings, and saves a character. Other than that, it's a pretty basic implementation. Scala picks up a couple bytes by not having a proper++ operator. Random.nextFloat returns a random value between 0 and 1, and 1f/x forces float division. This implementation uses a space as a separator, with no trailing newline.

You can use x+=1 to save a byte

Lua, 50 46 bytes
i=2while 1<math.random(i)do i=i+1print(...)end

Assumes that it is already seeded
Try it online!

k, 20 bytes
`0:((*1?2+)(1+)/0)#,

Explanation:
`0:((*1?2+)(1+)/0)#,
                0    /set x to 0
           (1+)      /add 1 to x...
    (*1?2+)    /     /...while randint [0,2+x) is > 0
   (             )#, /make array with that many copies of the string
`0:                  /output array line by line

Probabilities:
 5#{(((#:'=x{(*1?2+)(1+)/0}\0)@!x))%x}2000000      /experimental
0.5001625 0.1667005 0.083024   0.050034 0.0333645
 {(1%x)*-1_1.,*\{(x-1)%x}x}2+!5                    /calculated
0.5       0.1666667 0.08333333 0.05     0.03333333

@ValueInk Oh, I believe I misread! Fixing this now...

@ValueInk Fixed.

JS (ES6), 47 bytes
x=>{for(i=1;Math.random()<i/(i+1);i++)alert(x)}

Unlike the other ES6 answer, this uses a for loop and alert bombs instead of recursion. The seperator that is printed when the program stops is undefined.

Forth (gforth), 71 bytes
include random.fs
: f 1 1 do i 1+ random i = ?leave 2dup type cr loop ;

Try it online!
Technically will end after the [maximum single-cell number]th iteration, but the chance of that happening is at least 2-64 on most systems (and likely 2-32 on others)
Code Explanation
include random.fs  \ load the random library to generate random numbers

: f                \ start a new word definition
  1 1 do           \ loop from 1 to 0 (start at 1 stop when we reach 0 via integer overflow)
    i 1+ random    \ get a random integer from 0 to n
    i =            \ check if the value equals n
    ?leave         \ end the loop if true
    2dup type cr   \ otherwise, print the input string followed by newline
  loop             \ go back to beginning of loop
;                  \ end the word definition

Thunno 2, 7 bytes
(ṅƙɼḅ;£

Attempt This Online!
Explanation
(ṅƙɼḅ;£  # Implicit input
(        # while
 ṅ       # (condition)  0-based iteration index
  ƙ      #              increment twice
   ɼ     #              random item from [1..that]
    ḅ    #              equals one?
     ;£  # (body)  print input string with newline
         # Implicit output

Trilangle, 104 bytes
'0.<_.<.>i.S)#..\_/.L',z$)<.Se(*8'.3....LS:.)~<#+7....@..^.-/...,>j))2<.L,z,<......><#(,.#o.....\",o,../

Try it on the online interpreter!
The random number instruction $ creates a random number along the whole range of integers. This program uses the sign of \$\left|rand\left(\right)\right|+\frac{INT\_MIN}{i+1}\$ to determine whether to terminate.
I don't currently have the ability to create the colorized drawing I normally do, but here's an annotated disassembly. I created this first, then wrote the program, and then tweaked this to match the output of the disassembler.
; Get the string and its length. Pretty standard.
    PSI #0
input_loop: ; 0.2
    GTC
    BNG input_cleanup
    SWP
    INC
    JMP input_loop
input_cleanup: ; 2.0
; Put the iteration number on top of the stack. Rather than popping the -1 to
; push 0, just increment it.
    INC
; These swaps happened to be here, and they don't do anything
    SWP
    SWP
; Increment the iteration number and check whether to terminate
check_term: ; 2.10
    INC
    RND
; RND gives a number in [-0x800000, 0x7fffff].
; Terminate with probability 1/(i+1).
    DP2
    POP
; Get INT_MIN as 2^23. This overflows and becomes a negative number.
    PSI #3
    PSI #8
    MUL
    DEC
    EXP
; then do the division and compare
    SWP
    INC
    DIV
    SWP
    BNG rand_neg
; Stack: [...s, s.length, i, INT_MIN/(i+1), rand]
; Terminate when rand + INT_MIN/(i+1) < 0
    ADD
compare: ; 3.2
; Flip the sign, then end when it's positive instead of negative. It turned out
; to save room to make the positive branch terminate.
    NOT
    BNG print_begin
    JMP end ; disassembler quirk ¯\_(ツ)_/¯
rand_neg: ; 4.0
; Stack: [...s, s.length, i, INT_MIN/(i+1), rand]
; Terminate when INT_MIN/(i+1) - rand < 0
    SUB
    JMP compare
end: ; 5.0
    EXT
print_begin: ; 6.0
    POP
; Print the string.
; DP2 + POP is shorter than PSI #1 + IDX
    DP2
    POP
print_loop: ; 6.6
    BNG print_done
    DUP
; INC + INC is shorter than PSI #2 + ADD
    INC
    INC
    IDX
    PTC
    POP
    DEC
    JMP print_loop
; Print a separator, then loop back.
print_done: ; 8.0
    PSC ','
    PTC
    POP
    POP
    JMP check_term

I have a feeling that this can be shrunk, as there's a significant amount of unused space, but I haven't figured anything out yet.

JavaScript (Node.js), 40 bytes
x=>Array(0|.5/Math.random()).fill(x)+','

Try it online!
Act same

Bash, 71 59 bytes
i=1;while((0<`shuf -i0-$i -n1`));do echo $1;i=$((i++));done

Try it online!
While is a better tool for this job

TI-BASIC, 24 22 bytes
-2 thanks to @lirtosiast
:Prompt Str1           //4 bytes
:While randInt(0,Ans+1 //9 bytes
:Disp Str1             //4 bytes
:Ans+1                 //4 bytes
:End                   //1 byte

Since all non-zero values are truthy, taking a random integer in between 0 and n-1 will give a random boolean with the correct probability.

Why not Ans instead of A?

@lirtosiast Either works, but they have the same byte count and there is no reason to use Ans over A. A takes up less screen space, so I chose it.

I was thinking you could avoid the →A, since you don't use Ans for anything else, and both Ans and A default to 0.

@lirtosiast Ah, OK, thanks.

Runic Enchantments, 20 bytes
i0q11+:'RA0=?;S:$S4?

Try it online!
Note that input is implicitly split on whitespace characters, so they need to be escaped.
Explanation
>                        Implicit entry
 i0q1                    Read input and set up stack
     1+                  Increment counter (value needs to be 2 for first loop)
       :'RA0=            Generate random value (non destructive to stack) and compare with 0
             ?;          If *not* 0, terminate
               S:$S      Otherwise duplicate and print string
                   4?    Skip next 4 instructions (implicit loop)

Newline variant, as printing a whitespace character as a separator costs an extra byte.


text:
Am a I square repdigit?
Your Task
You will write a program or function to return a truthy value if the integer inputted to it is a square repdigit, and a falsy value if it is not.  A repdigit is an integer that contains only one digit (e.g. 2, 44, 9999).  For the purpose of this challenge, a square repdigit is a repdigit that is the square of a different repdigit.
Input
An integer, in base 10.
Output
A truthy/falsy value that reflects whether the input is a square repdigit
Examples
0 --> falsy
1 --> falsy
2 --> falsy
4 --> truthy
9 --> truthy
11 --> falsy

Scoring
This is code-golf, lowest bytes wins.

So, the integer provided and it's square root must be repdigits?

Is this really much different from Is this number a repdigit?

define f(x) = answer from is this number a repdigit; return f(n) & f(root n);

So we are asking if input is 4 or 9?

@Jenny_mathy Or 0 or 1.

@Adám No they must be squares of different repdigits.

@EriktheOutgolfer Oh, I missed that bit.

4 and 9 are indeed the only repdigits that are squares of other repdigits. The last two digits of any repdigit>10 squared contains two different values: 1..1 -> ..21, 2..2 -> ..84, 3..3 -> ..89, 4..4 -> ..36, 5..5 -> ..25, 6..6 -> ..36, 7..7 -> ..29, 9..9 -> ..01. If you square 8..8, the last three digits are 544.

This question is perfectly clear. At least, it is now.

Yes, but I approve of its closing anyway.  I hadn't realized it was just a trivial matter of hard-coding 4 and 9 in.

Neim, 6 3 2 bytes
+

Abuses the way that Neim deals with lists.
+ pushes the numeric literal 49 to the stack.
Then,  attempts to pop a list from the stack, and Neim implicitly converts 49 to [4 9]. It then pops another element, which is the input, provided implicitly. Finally, it checks that the input is in the list.
Try it!

Umm, can't you use one of the constants for 49?

@EriktheOutgolfer Forgot all about them :P

And wait Neim is competing? o_O it even beats Jelly

Why the heck does Neim have a built-in for 49? :P

@ETHproductions It has a built-in for all numbers 1-156. As it's an incomplete language, characters not assigned are automatically assigned as a variable. It used to have numbers up to 180 (also it was Erik's idea to add these :P)

Befunge, 20 17 10 bytes
&4-:5-*!.@

Try it online!
Thanks @ovs for -7 bytes!
How?
&4-:5-*!.@    Initial pointer direction >  (Input: 9   )
&             Get input as integer         (Stack: 9   )
 4-           Subtract 4                   (Stack: 5   )
   :          Duplicate                    (Stack: 5, 5)
    5-        Subtract 5                   (Stack: 5, 0)
      *       Multiply                     (Stack: 0   )
       !      NOT                          (Stack: 1   )
        .     Print as integer             (Stack:     )
         @    End of program

Proof that 4 and 9 are the only valid square repdigits
The last two digits of any repdigit>10 squared are two different values, except 8..8:
 n    n^2 % 100
--------------
1..1     21
2..2     84
3..3     89
4..4     36
5..5     25
6..6     36
7..7     29
8..8     44
9..9     01

88^2 = 7744, and the last three digits of 8..8^2 is 544.

+1 just for the proof.  I really wish I had checked to make sure there were more repdigits before asking this.

@Gryphon You could use the Sandbox to prevent issues like this.

Yes, I should have posted this in the sandbox first.

&4-:5-*!.@ for 10 bytes

@ovs Wow, that's awesome. I couldn't think of using a NOT...

Mathematica, 11 bytes
#==4||#==9&

Jelly, 4 bytes
e4,9

Try it online!
Note: if you disprove me, I'll edit. This returns a truthy result only if the input is 4 or 9.
Junghuan Min ninja'd a proof...

C#, JavaScript, Java, 12 bytes
n=>n==4|n==9

For Java replace => with ->.
Or a version more in the spirit of the challenge, C# only, for 61 bytes:
g=n=>n.Replace(n[0]+"","")==""
n=>g(n)&g(System.Math.Sqrt(n))

The 12 byte solution works for JS too.

@Shaggy I suppose it will work for Java too

Doesn't Java use - instead of = for arrow functions?

@Shaggy Oh yeah... added a comment about it because it is really the same code.

Was about to post a Java answer when I saw this. +1

05AB1E, 5 bytes
49S¹å

Try it online!

APL (Dyalog), 5 bytes
Just tests for membership of {4,9}
∊∘4 9

Try it online!

Braingolf, 19 bytes
.pl3e1:0|>e1:0|<+1-

Try it online!
This is as far as I can tell actually the shortest way to check "is n 4 or 9?"
Will output 1 if input is 4 or 9, otherwise will output 0
Explanation
.pl3e1:0|>e1:0|<+1-  Implicit input from commandline args
.p                   Duplicate, pop duplicate, push prime factors
  l3e                If there are exactly 3 items in stack..
                     (2 prime factors plus original input)
     1               ..Push 1
      :              Else
       0             ..Push 0
        |            Endif
         >           Move last item to start
          e          If 2 prime factors are equal..
           1         ..Push 1
            :        Else
             0       ..Push 0
              |      Endif
               <     Move first item to end
                +    Sum last 2 items
                 1-  Subtract 1
                     Implicit output.

That's not very golfy, considering the language name is Braingolf and it is beaten by Java.

@Okx it's bad at complex conditionals

Batch, 65 58 53 46 bytes
I have code-copying issues.
@if %1 neq 4 if %1 neq 9 echo 0&exit/b
echo 1

Return 1 for truthy value, 0 for falsely value.

Unrolling the loop to @if %1 neq 4 if %1 neq 9 echo 0&exit/b is a few bytes shorter. (FYI my solution is 26 bytes.)

PHP, 22 bytes
<?=$argn==4||$argn==9;

Try it online!

Python, 18 bytes
lambda n:n in[4,9]

Try it online!

Python 3, 39 25 bytes
Solution can be shorter for sure.
old:

n=input();print(n in ['0','1','4','9'])

Try it online!
new:

print(input()in['4','9'])

Try it online!

From this: "a square repdigit is a repdigit that is the square of a different repdigit."
Let z='ζζζζ...' be the square repdigit.
Case 1 z<10:
0² = 0
1² = 1
2² = 4
3² = 9
4² to 9² are not square repdigits.
Case z>10:
Lets assume there is an y∈ℕ with y²=z and y='xxxxx..'
We have just tested all single digits, so if there is an y with y² = z, then it has to be y>10.
So we can write y = x[10°+10¹] + x[10²+10³+...]
Then it is: y² = x²[10°+10¹]² + r  = x² [10° + 2*10¹] + r, with r only containing summands of power >1.
Comparing z='ζζζ..' with y² we get: x²=ζ and 2x²=ζ, hence x=0.
⇒ The only square repdigits are 0,1, 4 and 9.

I don't understand the + r part.

Emphasis: a square repdigit is a repdigit that is the square of a different repdigit.

@JungHwanMin: You are right "r>100" is not clear. Now, as r=r₂10²+r₃10³+..., it should be clear, that r just contains all dezimals >=10².

I think you can write [10⁰+10¹] as simply 11. Also, I can't understand what the r is for.

Welcome on the site! Nice first answer! (as Okx mentioned, 0 and 1 are not square repdigits though)

Also you have unneded whitespace in in [, and you don't need to use n.

Try print(int(input())in[0,1,4,9])

@Okx Umm, you kept 0,1, in. And int(...) isn't of any significance when this is corrected.

@EriktheOutgolfer I just tried to keep it as close to the existing solution as possible. But yes, 0 and 1 should be removed.

@Okx Can? They must be removed otherwise this doesn't follow the still current rules...

I edited the answer, so that it should be more obvious what 'r' means.

Updated according to your comments. Thx.

Javascript, 17 bytes
a=>!((a-4)*(a-9))

f=
a=>!((a-4)*(a-9))

for (i=0;i<12;i++) console.log(''+i+' -> '+f(i))


text:
Wind me a number snake!
Given an input integer n, draw a number snake, that is, a grid measuring n x n consisting of the numbers 1 through n^2 that are wound around each other in the following fashion:
Input n = 3:
7 8 9
6 1 2
5 4 3

Input n = 4:
 7  8  9 10
 6  1  2 11
 5  4  3 12
16 15 14 13

Input n = 5:
21 22 23 24 25
20  7  8  9 10
19  6  1  2 11
18  5  4  3 12
17 16 15 14 13

(Inspired by this problem from Project Euler.)
This is code-golf, the shortest answer in bytes wins!

Example: 4? Or any even number.

May we output an array of arrays of ints?

May we assume the input is odd?

Related

Related Project Euler problem

@Okx I was inspired by that.

@TheLethalCoder I added an example for n = 4.

Possible dupe?

Can the lines be outputted as an array or a sequence of cells? (asking for brainfuck)

@Uriel No, please print the output in a grid.

See also http://www.perlmonks.com/?node_id=487200 with many solutions and links in replies.

Related: Determine the position of a non-negative number in the infinite spiral.

MATL, 3 bytes
1YL

Try it online!
Explanation
Built-in... ¯\_(ツ)_/¯

Why... why is this a built in?

I'm guessing this is something to do with the "Magic Square" stuff?

@TheLethalCoder Because Matlab had it and I thought it would be useful (which it is indeed)

C#, 203 202 196 193 178 bytes
n=>{var r=new int[n,n];for(int o=n-2+n%2>>1,i=r[o,o]=1,c=2,w=o,h=o,b=1-2*(i%2),j;n>i++;){r[h,w+=b]=c++;for(j=0;j<i-1;++j)r[h+=b,w]=c++;for(j=0;j<i-1;++j)r[h,w-=b]=c++;}return r;}

Saved a byte thanks to @StefanDelport.
Saved 22 bytes thanks to @FelipeNardiBatista.
This works by the following observation of how the squares are built up:

As you can see each bit is added on to the previous square. For even numbers we go right of where we were, down till were one lower than where the square was and then left to the end. Odd numbers are essentially the opposite, we go left one, up till were one above the current height and then right to the end.
Full/Formatted version:
using System;
using System.Linq;

class P
{
    static void Main()
    {
        Func<int, int[,]> f = n =>
        {
            var r = new int[n, n];
            for (int o = n - 2 + n % 2 >> 1, i = r[o, o] = 1, c = 2, w = o, h = o, b = 1 - 2 * (i % 2), j; n > i++;)
            {
                r[h, w += b] = c++;

                for (j = 0; j < i - 1; ++j)
                    r[h += b, w] = c++;

                for (j = 0; j < i - 1; ++j)
                    r[h, w -= b] = c++;
            }

            return r;
        };

        Console.WriteLine(String.Join("\n", f(3).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
        Console.WriteLine(String.Join("\n", f(4).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");
        Console.WriteLine(String.Join("\n", f(5).ToJagged().Select(line => String.Join(" ", line.Select(l => (l + "").PadLeft(2))))) + "\n");

        Console.ReadLine();
    }
}

public static class ArrayExtensions
{
    public static T[][] ToJagged<T>(this T[,] value)
    {
        T[][] result = new T[value.GetLength(0)][];

        for (int i = 0; i < value.GetLength(0); ++i)
            result[i] = new T[value.GetLength(1)];

        for (int i = 0; i < value.GetLength(0); ++i)
            for (int j = 0; j < value.GetLength(1); ++j)
                result[i][j] = value[i, j];

        return result;
    }
}

++i<=n; can become n>++i, nothing else I can see, +1.

n%2<1?2:1 to 2-x%2 ? I haven't tested it in C#, but in C and Python it worked.

for(int o=n-2+n%2>>1,i=r[o,o]=1,c=2,w=o,h=o,j;n>i++;){var b=i%2<1; .... golfed a bit

@FelipeNardiBatista Awesome would never have thought of those two! Thanks.

var b=1-2*(i%2);r[h,w+=b]=c++;for(j=0;j<i-1;++j)r[h+=b,w]=c++;for(j=0;j<i-1;++j)r[h,w-=b]=c++;

Dyalog APL, 70 56 45 41 bytes
,⍨⍴∘(⍋+\)×⍨↑(⌈2÷⍨×⍨),(+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳

Try it online!
How?
(+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳

calculates the differences between the indices; 1 and ¯1 for right and left, ¯⍵ and ⍵ for up and down.
1,⊢,¯1,- comes as 1 ⍵ ¯1 ¯⍵, +⍨⍴ stretches this array to the length of ⍵×2, so the final 2/⍳ can repeat each of them, with a repetition count increasing every second element:
      (1,⊢,¯1,-) 4
1 4 ¯1 ¯4
      (+⍨⍴1,⊢,¯1,-) 4
1 4 ¯1 ¯4 1 4 ¯1 ¯4
      (2/⍳) 4
1 1 2 2 3 3 4 4
      ((+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳) 4
1 4 ¯1 ¯1 ¯4 ¯4 1 1 1 4 4 4 ¯1 ¯1 ¯1 ¯1 ¯4 ¯4 ¯4 ¯4

then,
(⌈2÷⍨×⍨),

prepends the top-left element of the spiral,
×⍨↑

limit the first ⍵2 elements of this distances list,
+\

performs cumulative sum,
⍋

grades up the indices (⍵[i] = ⍵[⍵[i]]), to translate the original matrix with the indices of every element, and finally
,⍨⍴

shapes as a ⍵×⍵ matrix.

For those interested, this technique is discussed at length in this excellent article.

C, 321 307 295 284 283 282 bytes
Thanks to both @Zachary T and @Jonathan Frech for golfing a byte!
#define F for(b=a;b--;)l
i,j,k,a,b,m;**l;f(n){n*=n;l=calloc(a=m=3*n,4);F[b]=calloc(m,4);for(l[i=j=n][j]=a=k=1;n>k;++a){F[i][++j]=++k;F[++i][j]=++k;++a;F[i][--j]=++k;F[--i][j]=++k;}for(i=0;i<m;++i,k&&puts(""))for(j=k=0;j<m;)(a=l[i][j++])>0&&a<=n&&printf("%*d ",(int)log10(n)+1,k=a);}

Allocates a two-dimensional array of zeroes, then starts filling it from somewhere in the middle. Lastly the values that are larger than zero but smaller than or equal to the square of the input are printed.
Try it online!
Formatted:
#define F for(b=a; b--;)l
i, j, k, a, b, m; **l;
f(n)
{
    n *= n;
    l = calloc(a=m=3*n, 4);

    F[b] = calloc(m, 4);

    for(l[i=j=n][j]=a=k=1; n>k; ++a)
    {
        F[i][++j] = ++k;
        F[++i][j] = ++k;
        ++a;

        F[i][--j] = ++k;
        F[--i][j] = ++k;
    }

    for(i=0; i<m; ++i, k&&puts(""))
        for(j=k=0; j<m;)
            (a=l[i][j++])>0 && a<=n && printf("%*d ", (int)log10(n)+1, k=a);
}

Is it possible to replace i,j,k,a,b,m;f(n){n*=n;int**l=calloc(a=m=3*n,4); with i,j,k,a,b,m,**l;f(n){n*=n;l=calloc(a=m=3*n,4); to save a byte?

You may be able to replace k<=n; with n>k; to save a byte.

APL (Dyalog Classic), 32 29 bytes
1+×⍨-{⊖∘⌽⍣⍵⌽{⌽⍉,⌸⍵+≢⍵}⍣2⍣⍵⍪⍬}

Try it online!
Uses ⎕io←1. Starts with a 0-by-1 matrix (⍪⍬). 2N times (⍣2⍣⍵) adds the height of the matrix (≢⍵) to each of its elements, puts 1 2...height on its right (,⌸), and rotates (⌽⍉). When that's finished, corrects the orientation of the result (⊖∘⌽⍣⍵⌽) and reverses the numbers by subtracting them from N2+1 (1+×⍨-).

PHP, 192 bytes
for($l=strlen($q=($a=$argn)**2)+$d=1,$x=$y=$a/2^$w=0;$i++<$q;${yx[$w%2]}+=$d&1?:-1,$i%$d?:$d+=$w++&1)$e[$x-!($a&1)][$y]=sprintf("%$l".d,$i);for(;$k<$a;print join($o)."\n")ksort($o=&$e[+$k++]);

Try it online!
Same way build a string instead of an array
PHP, 217 bytes
for($l=strlen($q=($a=$argn)**2)+$d=1,$x=$y=($a/2^$w=0)-!($a&1),$s=str_pad(_,$q*$l);$i++<$q;${yx[$w%2]}+=$d&1?:-1,$i%$d?:$d+=$w++&1)$s=substr_replace($s,sprintf("%$l".d,$i),($x*$a+$y)*$l,$l);echo chunk_split($s,$a*$l);

Try it online!

[-1,1][$d&1] --> $d&1?:-1

@Titus Thank You I have not see it

Here is one more byte: for(;$k<$a;print join($o)."\n")ksort($o=&$e[+$k++]);. And another one: "%$l".d. And one more: $x*$l*$a+$y*$l --> ($x*$a+$y)*$l.

And I think that in the second version You can initialize $s to a padded underscore (or letter or digit); that character will be overwritten.

@Titus Thank You and you can use the .d in your own approach to save 2 bytes

PHP, 185 176 174 bytes
for(;$n++<$argn**2;${xy[$m&1]}+=$m&2?-1:1,$k++<$p?:$p+=$m++%2+$k=0)$r[+$y][+$x]=$n;ksort($r);foreach($r as$o){ksort($o);foreach($o as$i)printf(" %".strlen($n).d,$i);echo"
";}

Run as pipe with -nR or test it online.
breakdown
for(;$n++<$argn**2;     # loop $n from 1 to N squared
    ${xy[$m&1]}+=$m&2?-1:1, # 2. move cursor
    $k++<$p?:               # 3. if $p+1 numbers have been printed in that direction:
        $p+=$m++%2+             # increment direction $m, every two directions increment $p
        $k=0                    # reset $k
)$r[+$y][+$x]=$n;           # 1. paint current number at current coordinates

ksort($r);              # sort grid by indexes
foreach($r as$o){       # and loop through it
    ksort($o);              # sort row by indexes
    foreach($o as$i)        # and loop through it
        printf(" %".strlen($n).d,$i);   # print formatted number
    echo"\n";               # print newline
}

Mathematica, 177 bytes
(n=#;i=j=Floor[(n+1)/2];c=1;d=0;v={{1,0},{0,-1},{-1,0},{0,1}};a=Table[j+n(i-1),{i,n},{j,n}];Do[Do[Do[a[[j,i]]=c++;{i,j}+=v[[d+1]], {k,l}];d=Mod[d+1,4],{p,0,1}],{l,n-1}];Grid@a)&

Waaait, no built-in for this in Mathematica?

Python 3, 249 247 bytes
I initialize an 2D array and find the starting point, which is the center for odd n or offset (-1,-1) for even n, then scale the fill/cursor pattern with the current 'ring' number.  I feel like I'm missing a trick for interpreting the directions but I haven't come up with anything cheaper.
def f(n):
 M=[n*[0]for a in range(n)]
 x=y=n//2-1+n%2
 M[x][y]=i=s=1
 while 1:
  t=s*2
  for d in'R'+'D'*(t-1)+'L'*t+'U'*t+'R'*t:
   if i==n*n:print(*M,sep='\n');return
   v=[1,-1][d in'LU']
   if d in'UD':x+=v
   else:y+=v
   M[x][y]=i=i+1
  s+=1

Try it online!
-2 thanks to Zachary T!

how did you count your bytes? tabs, spaces and newlines counts as well

I replaced every \n and \t with " " and took a len().  I just copied the above and redid it to make sure I didn't change anything and forget to recount but I got the same number. Did I miss something?

i'm counting \t and \n as 1 byte and still getting 249 bytes

e:^^^is there a better/easier method I should use? they always appeared to be used interchangeably to me.^^^ Strange, this is what I get in IDLE: len("def f(n): M=[n*[0]for a in range(n)] x=y=n//2-(n%2<1) M[x][y]=i=s=1 while 1: t=s*2 for d in'R'+'D'*(t-1)+'L'*t+'U'*t+'R'*t: if i==n*n:print(*M,sep='\n');return v=[1,-1][d in'LU'] if d in'UD':x+=v else:y+=v M[x][y]=i=i+1 s+=1") 223

usually text editors tell you how many characters are selected, so CTRL+A and read what it says

I think you can change x=y=n//2-(n%2<1) to x=y=n//2-1+n%2 to save two bytes.

C++, 245 228 bytes
void f(){for(int i=0,j=-1,v,x,y,a,b;i<n;i++,j=-1,cout<<endl)while(++j<n){x=(a=n%2)?j:n-j-1;y=a?i:n-i-1;v=(b=y<n-x)?n-1-2*(x<y?x:y):2*(x>y?x:y)-n;v=v*v+(b?n-y-(y>x?x:y*2-x):y+1-n+(x>y?x:2*y-x));cout<<setw(log10(n*n)+1)<<v<<' ';}}

Try it online!
The function calculates and prints the value of each number of the matrix depending on its x, y position by applying this logic:

Formatted version:
#include <iostream>
#include <iomanip>
#include <math.h>

using namespace std;

void f(int n)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            int value = 0;

            // Invert x and y when n is even
            int x = n % 2 == 0 ? n - j - 1 : j;
            int y = n % 2 == 0 ? n - i - 1 : i;
            if (y < (n - x))
            {
                // Left-top part of the matrix
                int padding = x < y ? x : y;
                value = n - 1 - padding * 2;
                value *= value;
                value += y >= x ? n - x - y : n + x - y - (y * 2);
            }
            else
            {
                // Right-bottom part of the matrix
                int padding = x > y ? n - x : n - y;
                value = n - padding * 2;
                value *= value;
                value += x > y ? y - padding + 1 : n + y - x - (padding * 2) + 1;
            }

            cout << setw(log10(n * n) + 1);
            cout << value << ' ';
        }

        cout << endl;
    }
}

int main()
{
    int n;
    while (cin >> n && n > 0)
    {
        f(n);
        cout << endl;
    }
}

Wolfram Language (Mathematica), (...) 83 bytes
Byte measured in UTF8, \[LeftFloor] (⌊) and \[RightFloor] (⌋) cost 3 bytes each. Mathematica doesn't have any special byte character set.
Table[Max[4x^2-Max[x+y,3x-y],4y
y-{x+y,3y-x}]+1,{y,b+1-#,b=⌊#/2⌋},{x,b+1-#,b}]&

Try it online!

Uses the closed form for each of the 4 cases, then takes the maximum carefully to get the desired result.
Returns a 2D array of integers. I'm not sure if this is allowed, and although it has been asked in the comments, the OP didn't reply.

Clojure, 206 bytes
(defmacro F[s]`(if(~'r(+ ~'p ~'v ~s))~'v ~s))
#(loop[i 1 p(*(quot(dec %)2)(inc %))v 1 r{}](if(<(* % %)i)(partition %(map r(range i)))(recur(inc i)(+ p v)({1(F %)-1(F(- %))%(F -1)(- %)(F 1)}v)(assoc r p i))))

I guess this is a decent start, builds the board in sequence to a hash-map and then partitions it into n x n lists. That defmacro ended up being quite long, but the code is still shorter with it than without. Is there a more succint syntax to describe it?
Bulk of bytes calculate the starting point, and build the look-up logic of the next velocity v. Perhaps a nested vec would be better, but then you've got two indexes and velocities to keep track of.

J, 41 bytes
(]|.@|:@[&0](|.@|:@,.*/@$+#\)@]^:[1:)2*<:

Try it online!
Does the same thing as ngn’s APL submission but starts with a 1-by-1 matrix and repeats 2×N−2 times.

Can you improve my alternative approach (now tied at 41) to beat yourself?  I've given it my best golf so far, but I suspect at least a few more bytes could be shaved off.

Python 165 (or 144)
from pylab import *
def S(n):
 a=r_[[[1]]];r=rot90;i=2
 while any(array(a.shape)<n):
  q=a.shape[0];a=vstack([range(i,i+q),r(a)]);i+=q
 if n%2==0:a=r(r(a))
 print(a)

This creates a numpy array, then rotates it and adds a side until the correct size is reached.  The question didn't specify if the same start point needs to be used for even and odd numbers, if that's not the case the line if n%2==0:a=r(r(a)) can be removed, saving 21 bytes.

this isn't Python, it's Python + numpy

@ASCII-only Is there a master list of acceptable language names somewhere?  This is perfectly valid python.

It uses a library, so you need to include the library's name as well... as for allowed languages, any language with a publicly available implementation you can get to run is allowed

@ASCII-only  where's that written out?  I haven't seen it done with most python answers.

Yes, because most of them don't use numpy... and the stdlib doesn't count as an external library

J, 41 bytes
,~$[:/:[:+/\_1|.1&,(]##@]$[,-@[)2}:@#1+i.

standard formatting
,~ $ [: /: [: +/\ _1 |. 1&, (] # #@] $ [ , -@[) 2 }:@# 1 + i.

This approach is based off At Play With J Volutes (Uriel's APL uses a similar technique).
It's unexpected and elegant enough to justify a 2nd J answer, I thought.
Essentially, we don't do anything procedural or even geometric.  Instead, we arithmetically create a simple sequence that, when scan summed and graded up, gives the correct order of the spiraled number from left to right, top to bottom.  We then shape that into a matrix and are done.
I'll add a more detailed explanation when time permits, but the linked article explains it in depth.
Try it online!

K (ngn/k), 38 bytes
{(x,x)#<0,+\(,/-:\1,x)4!-1_&1+-1_&x#2}

Attempt This Online!

Python 3 (Stackless), 192 188 179 150 bytes
lambda n:[list(map(v,list(range(t-n,t)),[y]*n))for t in[1+n//2]for y in range(n-t,-t,-1)]
v=lambda x,y,r=0:y>=abs(x)and(3-2*r+4*y)*y+x+1or v(y,-x,r+1)

Try it online!
The algorithm here is to form a phasor for each coordinate in the grid, and then rotate it 90-degrees clockwise until the phasor lies between the upper diagonals.  A simple formula can be used to calculate the value based on the coordinates and the number of clockwise rotations:
$$
(2y+1)^2-(y-x)-2yr
$$
Saved 4-bytes since 90-degree phasor rotation is easily done without complex numbers

R, 183 bytes
x=scan()
b=t(d<-1)
while(2*x-1-d){m=max(b)
y=(m+1):(m+sum(1:dim(b)[2]|1))
z=d%%4
if(z==1)b=cbind(b,y)
if(z==2)b=rbind(b,rev(y))
if(z==3)b=cbind(rev(y),b)
if(z==0)b=rbind(y,b)
d=d+1}
b

Try it online!
Output is a matrix snake (or snake matrix, whatever). It's probably not the most efficient method, and it could likely be golfed, but I thought it was worth showing. I'm rather proud of this actually!
The method builds the matrix from the inside out, always appending an additional number of integers equal to the number of columns in the matrix before appending.
The pattern that follows is either binding by columns or by rows, while also reversing some values so they are appended in the correct order.
193 bytes
Exact same as above, but final b is
matrix(b,x)

Try it online!
which gives slightly cleaner output, but I didn't see any special criteria for output, so the first answer should work if I'm not mistaken.


text:
Output the Wikipedia article for Kolmogorov Complexity
Your job is to output the html of the current version (at the time of this writing) of the Wikipedia page for Kolmogorov complexity: https://en.wikipedia.org/w/index.php?title=Kolmogorov_complexity&oldid=781950121&action=raw (backup)
This is code-golf, so the shortest code wins.

I downvoted because I don't think this is an interesting challenge; there isn't much room for compression in my opinion. Other than maybe tags, not much can be done to compress it.

@HyperNeutrino Well, you could encode the abstract concept of kolmogorov complexity, and then train a neural net on generating wikipedia articles, and then feed in the kolmogorov complexity concept.

I feel like that would be longer than just printing the text itself.

related

You made a typo right in the title

7zip file manager: 12,156 bytes
hex dump: here
how to use:
7zip e [savedfileName]
I'm posting this because it's about as small as you can get it without using HTTP calls.

Is this valid seeing as it requires the use of an external file?

@Shaggy source code files aren't considered external.

Bubblegum, 12,290 bytes
Hexdump of solution.
Try it online! (you have to paste the hexdump yourself, it's too long to fit in 30k chars)


text:
Reversed language name
You should code a piece of code that looks like it outputs the language name but actually outputs the name reversed.
E.g. a Python program should look like it outputs Python but should actually output nohtyP.
The winner is the answer with the most upvotes in a week!

Flagged to close as underhanded questions are no longer welcome.

I'm voting to close this question as off-topic because underhand questions are no longer welcome in this site

It is such a pity that [tag:underhanded] was made off-topic. The community loves them.

Could've been interesting if it had said "The characters in the language-name cannot be hard-coded".

@Adám: Looking at the quality of the answers to this challenge, I can see why we don't like challenges like this on the site any more. Most of the answers are terrible (not even obfuscated at all), and most of the rest are exploiting a loophole in the wording of the question.

@ais523 I suppose you mean allow, not like. Well, apart from the loophole (which the OP could address) upvotes (since this is a popularity contest) are supposed to promote the actually clever answers.

May I suggest adding a rule that prohibits palindromically named languages from participating, or alternatively requires them to add some kind of identifier like a dialect name or a version number?

I also think you should forbade palindromic languages! @Adám

From reopen review: this challenge is still off-topic, and although the offtopic subreason given isn't correct (it should be "this challenge is offtopic because it asks for underhanded code"), only a moderator can change the offtopic subreason. So voting to leave as closed.

Since this is closed: Keg, 4 bytes

PHP, 3 bytes
PHP

Try it online!
It looks like it outputs the language name, but it's actually the letters in reversed order.

I normally hate underhand questions but this one is brilliant

Wait, it's reversed? How sure are you...

The challenge PHP was created for.

Cannot believe this... I hate Palindromes!

@KritixiLithos 100%. I pasted the output into a script where I compared it to 'PHP'[::-1] and it returned true.

OK, so this was funny because it exploited a loophole that OP (a newcomer to PPCG) probably didn't think of, but you shouldn't upvote answer that do not answer the challenge. The answer was supposed to be underhanded. This isn't.

I don't like that this seems to be considered the standard way to program with PHP. it is more like pure HTML markup. If I type PHP; inside the php cli, that is php -a, it doesn't print anything but says PHP Notice:  Use of undefined constant PHP - assumed 'PHP' in php shell code on line 1. I think, this answer should be more like echo PHP;.

Cubix
Because Cubix doesn't always need to be indecipherable
begin;
print "Cubix" > output;
end@?;

Try it online!
Watch it running

This is great!!

R, 8 bytes
Took me a while to figure this one out, but I think I've solved it!
cat("R")

HTML, 11 Bytes
HTML

-4 Bytes hardcoding the unicode character in a html file
HTML, 12 Bytes
HTML

The browser do the rest in a html file

HTML

Might want to check the underhanded tag

@Mayube now better?

Yeah that's much better

C++
#include <iostream>
int main()
{
    char C = 1;
    std::string CPP;
    for(C++; C++ < 42; C++)
        CPP += "C++";
    std::cout << CPP[C++];
    std::cout << CPP[C++];
    std::cout << CPP[C++];
    return 0;
}

Try it online!

Braingolf, 20 bytes
"Braingolf"@@@@@@@@@

Try it online!
@ Prints a character as ASCII, however because "Braingolf" pushes the string in order, the last item on the stack is f, so the first @ prints f, and so on.
Because of this quirk, the first Hello, World! program in Braingolf was actually:
"!dlroW ,olleH"@@@@@@@@@@@@@

Sidenote: Braingolf backwards is Flogniarb, which might actually be a better language name than Braingolf!

><>, 8 bytes
"><>">o<

Try it online!
Fun fact, this actually reverses the name of the language. The name, however, is a palindrome. Which is extra funny to me, because 'paling' (which almost spells the start of 'palindrome') is a kind of eel in Dutch.

Wait ><> isn't a palindrome, it's <>< backwards

@Mayube instinctively I thought that too and was "Huh, ><> outputs the stack reversed, why am I getting ><>".  Then I counted the GT's and LT's...

but this doesn't work, because it outputs ><> not <><, the goal is to output the language name reversed

@Mayube ><> reversed is still ><> ;)

Oh right yeah I see it now, I had to literally replace ><> with 121 in the code to understand what you were saying :P

I am wondering how this got a downvote...

@steenbergh I countered it. ;)

Huh... it's funny how it looks like the reverse should be <><, but it's ><>. Geometry!

C (gcc), 20 18 bytes
-2 bytes thanks to cleblanc.
Specification says nothing about any output on STDERR so...
main(){puts("C");}

Try it online!

Why not use puts("C") to save a couple of bytes.

First time using C lol. Thanks!

@Downvoter, please explain.

Jelly, 8 bytes
“Jelly”U

Try it online!
"U" is a meaningless enough atom for "reverse an array" that 99% of programmers will likely assume that this program will output "Jelly". Maybe not so much code-golfers, though.

This is fairly obvious for even beginner Jelly programs like myself a few weeks ago. (I didn't downvote though).

@HyperNeutrino Wow, I didn't realize you were a beginner Jelly program! :P

@Challenger5 Well I'm sorry that I can't engrish :p

APL (Dyalog), 24 bytes
Outputs on STDERR. This is a simple identity reduction, but APL goes right-to-left!
{⍺⊣⍞←⍵}/' APL'

Try it online!

Alternate, tacit, self-documenting version:
Print←⍞∘←
Identity←⊣
All←/
Identity∘Print All' APL'

Try it online!

A.P.L.: An Interactive Approach (pun intended). Let's ask for the three letters and input them in proper order:
⎕⎕⎕
'A'
'P'
'L'

Works because APL evaluates from right to left and thus asks for the rightmost letter first, but we enter the "A" first, etc.
Try it online!

J, 3 bytes
Jumping on the language-is-palindrome bandwagon:
'J'

Hm… |.'J' would be more fitting.

q, 5 bytes
a one letter language name makes this problem trivial
1"q";

Output:
q

Bash, 10 bytes
rev<<<Bash

Try it online!

If you use sh instead of bash you can save two bytes. Never have I ever suggested switching languages for a program to save two bytes lol

@Sirens: sh doesn't support the <<< redirection. bash is sometimes renamed to sh, but that doesn't change the fact that the language is still Bash.

I stand corrected: sh --version: GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16). Kind of nasty that they do that given that sh and bash behave differently.


text:
Output this sequence of numbers
Your challenge is to write a program or function to output this sequence of numbers.
Output requirements:

Must contain numbers specified above
Must be in order as specified
Numbers must be delimited by whitespace

Shortest code in bytes wins.

Ah, feck, I've figured out 2 formulas for this but it's too fiddly to write them up, test them & golf them down on my phone.

OEIS Sequence

A033312

Guessing how you've generated a sequence is a poor fit for code golf. Once one person has solved the "puzzle", everyone can copy the idea.

@xnor Alright, I'll add modified version

That edit makes it [tag:restricted-source] instead of [tag:code-golf]

You've just made the winning criterion the language used for a solution. That's not a winning criterion.

Is this meant to be a [tag:kolmogorov-complexity]? Or do you take the number of numbers to output as input / output forever / output the number at a specific index? In any case, the specification of the challenge shouldn't be hosted on an external site. You should place the rule used for generating the numbers into the question.

@ais523 I don't know if it was KC at the time you read it, but it was originally KC but I removed that because the output requirements imply that there can be multiple valid outputs; thus, I don't believe that makes it KC (so I removed that along with [tag:arithmetic]).

Python, 76 bytes
from math import*
s=2**32-5
for i in range(6499):print((s-factorial(i+1))%s)

A033312.
Python, 84 bytes
from math import*
k=s=2**32-6
for i in range(6499):s-=i*factorial(i);s%=k+1;print(s)

A001563.

Do you really need k=? As far as I can tell, k=s=... and s never changes so why not remove the k= and make %k into %s?

@cairdcoinheringaahing thanks

You can save 1 cheap byte by not importing *; Try it online!

Python 3, 148 bytes
a=[1]
n=6499
N=2**32-5
exec("a+=[a[-1]*len(a)%N];"*n)
a=[i*a[i]for i in range(n)]
for i in range(1,n):a[i]=(a[i]+a[i-1])%N
print([N-i-1 for i in a])

Try it online!
Surely this can be golfed.

Took you literally 10 minutes :)

@Mr.Xcoder I only checked the beginning and the end though.

Charcoal, 39 bytes
Ａ⁻Ｘ²¦³²¦⁵σＡ¹φＡ¹κＦ⁶⁴⁹⁹«⁺﹪⁻σφσ¶Ａ⁺κ¹κＡ×φκφ

Try it online!
Explanation
Ａ         σ                                    Assign to s
  ⁻Ｘ²¦³²¦⁵                                     2 ** 32 - 5
            Ａ¹φ                                Assign 1 to f (factorial)
                Ａ¹κ                            Assign 1 to k
                    Ｆ⁶⁴⁹⁹«                     For i from 0 to 6498
                           ⁺﹪⁻σφσ¶             (s - f) % s + "\n" (implicitly printed)
                                   Ａ⁺κ¹κ       k = k + 1
                                         Ａ×φκφ Assign f * k to f

05AB1E, 19 bytes
žJ5-6499FDN>!-sDŠ%,

Try it online!
Only checked first and last numbers. If you run it TIO will probably take a while to print them all

Explanation
žJ5-                # (2 ** 32) - 5; call this x
    6499F           # for N in 0 .. 6498. Stack entering loop: [x]
         D          # duplicate. Stack: [x, x]
          N>        # N + 1. Stack: [x, x, N + 1]
            !       # factorial. Stack: [x, x, (N + 1)!]
             -      # subtract. Stack: [x, x - (N + 1)!]
              s     # swap. Stack: [x - (N + 1)!, x]
               D    # duplicate. Stack: [x - (N + 1)!, x, x]
                Š   # cycle last three items. Stack: [x, x - (N + 1)!, x]
                 %  # modulus. Stack [x, (x - (N + 1)!) % x)]
                  , # pop and print. Stack: [x]


text:
Create a BijectiveBrain
Create a bijective function between the syntactically valid BF programs and the natural numbers
This means that you will assign each BF program a nonnegative integer (0,1,2,...) in such a way that each number gets a BF program without syntax errors (and without whitespace or comments).
Note that something like Binaryf***, for two reasons. Both +> and > map to 2, and no valid program maps to 6 (since [ is not a valid BF program).
You may either create two programs, one to map BF programs to numbers, one to map numbers to valid BF programs (which will be inverses) (in which case your score is the sum of their lengths), or you can create one program which does both tasks (in which case your score is just length of that one program).
Note: The program(s) must run in polynomial time (in terms of the length of the input). (This rule is to prevent boring brute force approaches.)
This is code-golf, so the shortest program(s) wins!

Haskell, 215+242=457
I haven't significantly golfed this. Its more of a example.
From BF to number
c '>'=1
c '<'=2
c '+'=3
c '-'=4
c '.'=5
c ','=6

i 0 ""=0
i 0 ('[':t)=7+7*(i 1 t)
i 0 (h:t)=(c h)+7*(i 0 t)

i b (']':t)=0+8*(i (b-1) t)
i b ('[':t)=7+8*(i (b+1) t)
i b (h:t)=(c h)+8*(i b t)

main=interact(show.i 0)

From number to BF
c 1='>'
c 2='<'
c 3='+'
c 4='-'
c 5='.'
c 6=','

i 0 0=""
i 0 n = case divMod n 7 of
    (m,0)->'[':i 1 (m-1)
    (m,x)->(c x):i 0 m
i b n = case divMod n 8 of
    (m,0)->']':i (b-1) m
    (m,7)->'[':i (b+1) m
    (m,x)->(c x):i b m

main=interact(i 0.read)

It works through a combination of Bijective numeration and Mixed radix.
The encoder has two modes: no unmatched brackets mode and unmatched brackets mode.
If there are no unmatched brackets, 0 maps to the empty program, and each of the characters ><+-.,[ is mapped to a number from 1 to 7. ] is not included since a BF program can not have ] until it an unmatched bracket. This digit becomes the least significant digit, and is in base 7.
Once there are unmatched brackets, the digits are in base 8, with ] assigned to 0. In particular, there is no number assigned to the ending the program (since you can not end the program while there are unmatched brackets). Once all brackets are matched, it returns to no unmatched brackets mode. To output 0 exactly while in this mode, you must match all brackets, and then end.
Example: .-,.><++.,[>] -> 4228460766 -> .-,.><++.,[>]