text:
File Permissions
Adapted from the UIL - Computer Science Programming free response question "Carla" for 2018 District.
Introduction
In UNIX-like operating systems, each file, directory, or link is "owned" by a "user", who is a member of a "group", and has certain "permissions" represented by a ten-character string such as "drwxrwxrwx". The first character is 'd', '-', or 'l' (directory, file, or link), followed by three sets of "rwx" values, indicating "read, write, execute" permissions. The first set is the user's rights, the middle set the group's rights, and the third everyone else's rights to that object.
Permission denied for any of these rights is represented by a '-' in place of the 'r', 'w', or 'x'. For example, a sample directory permission string would be "drwxr--r--", indicating full directory rights for the user, but "read-only" rights for the group member and all others.
Each "rwx" combination can also be represented by an octal value (0-7) with the most significant bit representing read permission, the next most significant bit representing write permission, and the least significant bit representing execute permission.
Challenge
Given a four-character code string made up of a character: 'D', 'F', or 'L', followed by a three-digit octal integer value, like 664, output the resulting 10 character string that represents the permission value indicated.
Input
Your program or function may either read the input from standard in (four characters will be entered, optionally followed by a newline) or be passed the input as an argument.
Your program may accept uppercase or lowercase inputs but must be consistent (either all inputs are uppercase or all inputs are lowercase).
Output
Your program must print the resulting ten-character string that represents the permission value indicated in the exact format specified above. Tailing white space is allowed.
Test Cases
In: F664 Out: -rw-rw-r--
In: D775 Out: drwxrwxr-x
In: L334 Out: l-wx-wxr--
In: F530 Out: -r-x-wx---
In: D127 Out: d--x-w-rwx
Scoring and Rules

Standard loop-holes are forbidden.
Standard rules apply.
Please provide a link to test your code as well as an explanation.
This is code-golf, so the shortest answer in bytes wins!

Wait what, asked yesterday and answer accepted already? Does this mean no more answers are expected or what?

@Nit More answers are always welcome, regardless of whether an answer is accepted.

@Nit I was on mobile and trying to downvote an unrelated answer (which has been removed since). I accidentally hit the accept answer button with my fat finger. I couldn't figure out how to unaccept so I just changed the accepted answer to the shortest one as of now.

@Nit I mean... he did accept a Dennis answer, so he honestly may be correct.

Jelly, 19 bytes
“rwx“-”Œp⁺;Ṁ⁾f-yị@~

Try it online!
How it works
“rwx“-”Œp⁺;Ṁ⁾f-yị@~  Main link. Argument: s (string)

“rwx“-”              Set the return value to ["rwx, "-"].
       Œp            Take the Cartesian product, yielding ["r-", "w-", "x-"].
         ⁺           Take the Cartesian product, yielding
                     ["rwx", "rw-", "r-x", "r--", "-wx", "-w-", "--x", "---"].
          ;Ṁ         Append the maximum of s (the letter).
            ⁾f-y     Translate 'f' to '-'.
                  ~  Map bitwise NOT over s.
                     This maps the letter to 0, because it cannot be cast to int,
                     and each digit d to ~d = -(d+1).
                ị@   Retrieve the results from the array to the left at the indices
                     calculated to the right.
                     Indexing is modular and 1-based, so the letter from s is at
                     index 0, "---" at index -1, ..., and "rwx" at index -8.

bash, 59 53 bytes
chmod ${1:1} a>a;stat -c%A a|sed s/./${1:0:1}/|tr f -

Right tool for the job?
Thanks to Dennis for saving 5 bytes and HTNW for saving one.
Try it online!
chmod ${1:1} a>a;  # call chmod with the input with its first character removed
                   # note that the redirection creates the file a *before* the
                   #   chmod is run, because of the way bash works
stat -c%A a|       # get the human readable access rights
sed s/./${1:0:1}/  # replace the first character with the first char of input
|tr f -            # transliterate, replacing f with -

Well that was fast. Certainly the right tool for the job.

chmod ${1:1} a>a;stat -c%A a|sed "s/-/\L${1:0:1}/;s/f/-/" saves two bytes.

Going off @Dennis, I think you can shave off one more with tr instead of y: chmod ${1:1} a>a;stat -c%A a|sed s/./\\L${1:0:1}/|tr f -

And \\L doesn't seem to be required. The OP said we can use lowercase input.

Is it legit to assume there is no file a and the user has permission to make it or there is the file a and it is writable by the user? Because if there is a file a owned by root with permissions 700, this shouldn't work.

@NoOneIsHere While permissions in particular never came up in the discussion, the community decided that creating temporary files in the current directory is allowed by default. By extension, we can assume that it's possible.

Python 2, 78 bytes
lambda a,*b:[a,'-'][a=='f']+''.join('-r'[x/4]+'-w-w'[x/2]+'-x'[x%2]for x in b)

Takes input as a character and three ints.
Try it online!
Explanation
[a,'-'][a=='f'] takes either the input character or -, if the character is f.
'-r'[x/4]+'-w-w'[x/2]+'-x'[x%2] is essentially an octal conversion to get the rwx string.

Perl 5 + -p, 37 bytes
s/\d/(<{-,r}{-,w}{-,x}>)[$&]/ge;y;f;-
Try it online!
Explanation
s///ubstitutes each \digit in the string ($_, implicit from the implicit -n provided by -p) with the result of the glob (<...>) of {-,r}{-,w}{-,x} (which is treated as a list) at index $& (the matched \digit).
The glob computes this list:
(
"---", # 0
"--x", # 1
"-w-", # 2
"-wx", # 3
"r--", # 4
"r-x", # 5
"rw-", # 6
"rwx", # 7
)

I'd love to read an explanation of this. Not knowing Perl the (<{-,r}{-,w}{-,x}>)[$&] syntax is mysterious to me.

@Jordan I've added an explanation! But it's essentially a "BSD style glob", treated as a list and indexed using the replaced \digit.

Ah, that makes perfect sense. Thanks!

Retina, 51 bytes
f
-
0
---
1
--x
2
-w-
3
-wx
4
r--
5
r-x
6
rw-
7
rwx

Try it online!
No idea how to use Retina, so please let me know how to do this better. I just figured I'd try to learn at least one language that isn't Pyth.
Explanation:
Replace f with - (leaving d and l unchanged), then replace each digit with the appropriate rwx.

:/ I can get as far as this but no further. and the smart way is super ungolfy

It would be so much golfier with some kind of ternary/logical or/add and trim operators

@ASCII-only Your idea was quite nice, I've used it for this answer :)

Retina 0.8.2, 43 bytes
\d
$&r$&w$&x
f|[0-3]r|[0145]w|[0246]x
-
\d

Try it online! Link includes test cases. Takes input in lower case. Explanation:
\d
$&r$&w$&x

Triplicate each digit, suffixing with r, w and x.
f|[0-3]r|[0145]w|[0246]x
-

Change all the incorrect letters to -s.
\d

Delete any remaining digits.

JavaScript (ES6), 63 bytes
Expects the input string in lowercase.
s=>s.replace(/\d|f/g,c=>1/c?s[c&4]+s[c&2]+s[c&1]:'-',s='-xw-r')

Try it online!
Commented
s => s.replace(   // replace in the input string s
  /\d|f/g, c =>   //   each character c which is either a digit or the letter 'f'
    1 / c ?       //   if c is a digit:
      s[c & 4] +  //     append '-' or 'r'
      s[c & 2] +  //     append '-' or 'w'
      s[c & 1]    //     append '-' or 'x'
    :             //   else:
      '-',        //     just replace 'f' with '-'
  s = '-xw-r'     //   s holds the permission characters
)                 // end of replace()

Charcoal, 27 bytes
ＦＳ≡ιdιlιf¦-⭆rwx⎇§↨⁺⁸Ｉι²⊕λκ-

Try it online! Link is to verbose version of code. Explanation:
 Ｓ                          Input string
Ｆ                           Loop over characters
   ι                        Current character
  ≡                         Switch
    d                       Literal `d`
     ι                      Implicitly print current character
      l                     Literal `l`
       ι                    Implicitly print current character
        f                   Literal `f`
         ¦                  (Separator between string literals)
          -                 Implicitly print literal `-`
                            Implicit default case
            rwx             Literal `rwx`
           ⭆                Map over characters
                     ι      Input character
                    Ｉ       Cast to integer
                   ⁸        Literal 8
                  ⁺         Sum
                      ²     Literal 2
                 ↨          Base conversion
                        λ   Inner index
                       ⊕    Incremented
                §           Index into base conversion
                         κ  Inner character
                          - Literal `-`
               ⎇            Ternary
                            Implicitly print

Haskell, 84 83 81 bytes
f 'f'='-'
f y=y
t#n=f t:((\x->["-r"!!div x 4,"-w-w"!!div x 2,"-x"!!mod x 2])=<<n)

Try it online!
Ended up being pretty similar in concept to Mnemonic's Python 2 answer. f creates the file type, the rest is the gets permissions from the octal number. This one really made me wish & was a bitwise and operator included in prelude.

You can use div instead of quot.

Java 8, 100 bytes
s->s.replaceAll("(\\d)","$1r$1w$1x").replaceAll("f|[0-3]r|[0145]w|[0246]x","-").replaceAll("\\d","")

Try it online.
Port of @Neil's Retina answer.
Explanation:
s->                                 // Method with String as both parameter and return-type
  s.replaceAll("(\\d)","$1r$1w$1x") //  Replace every digit `d` with 'drdwdx'
   .replaceAll("f                   //  Replace every "f",
                |[0-3]r             //  every "0r", "1r", "2r", "3r",
                |[0145]w            //  every "0w", "1w", "4w", "5w",
                |[0246]x",          //  and every "0x", "2x", "4x", "6x"
               "-")                 //  with a "-"
   .replaceAll("\\d","")            //  Remove any remaining digits

This is smart! ;)

@OlivierGrégoire Well, mainly because it saves on the return statement and loops. Too bad three individual .replaceAll is still less bytes than a loop with .replaceAll and added return and String-array.. But credit of course goes to Neil, who's Retina answer I used as base to port from.

Jelly, 21 bytes
Ḣ⁾f-yɓOBṫ€4a“rwx”o”-ṭ

A full program printing to STDOUT. (As a monadic link the return value is a list containing a character and a list of three lists of characters.)
Try it online! Or see the test-suite.
How?
Ḣ⁾f-yɓOBṫ€4a“rwx”o”-ṭ | Main Link: list of characters
Ḣ                     | head & pop (get the 1st character and modify the list)
 ⁾f-                  | list of characters = ['f', '-']
    y                 | translate (replacing 'f' with '-'; leaving 'd' and 'l' unaffected)
     ɓ                | (call that X) new dyadic chain: f(modified input; X)
      O               | ordinals ('0'->48, '1'->59, ..., '7'->55 -- notably 32+16+value)
       B              | convert to binary (vectorises) (getting three lists of six 1s and 0s)
        ṫ€4           | tail €ach from index 4 (getting the three least significant bits)
           “rwx”      | list of characters ['r', 'w', 'x']
          a           | logical AND (vectorises) (1s become 'r', 'w', or 'x'; 0s unaffected)
                 ”-   | character '-'
                o     | logical OR (vectorises) (replacing any 0s with '-'s)
                   ṭ  | tack (prepend the character X)
                      | implicit print (smashes everything together)

Perl 6 -p, 37 bytes
s:g[\d]=[X~]('-'X <r w x>)[$/];s/f/-/

Try it online!
Port of Dom Hastings' Perl 5 solution.

Retina, 38 bytes
Inspired by a comment from ASCII-only.
\d
---$&*
---____
r--
--__
w-
-_
x
f
-

Try it online!
The idea is converting each digit to unary (the default unary digit in Retina is _) with three leading -, and then converting binary digits from the most to the least significant.

Python 3, 71 bytes
lambda s:("-"+s)[s[0]!="f"]+stat.filemode(int(s[1:],8))[1:]
import stat

Try it online!
Python 3.3+ has a built-in for that, although due to the need for an import, and differences in expected input format, it is not very golf-friendly.

05AB1E, 34 27 bytes
ćls8βbvyi…rwx3*Nèë'-}J'f'-:

Try it online!
Golfed down 7 bytes by @MagicOctopusUrn

ć                           # Remove head from string.
 ls                         # Lowercase swap.
   8βb                      # Octal convert to binary.
      vy                    # For each...
        i        ë  }
         …rwx3*Nè           # If true, push the correct index of rwx.
                  '-        # Else push '-'.
                     J      # Repeatedly join stack inside the loop.
                      'f'-: # Repeatedly replace 'f' with '-' inside the loop.

ćls8βbvyi…rwx3*Nèë'-}J'f'-: for 7 less...

Basically just a different ordering using if statements, and instead of removing the f I'm just replacing all f's in the final string with -.

i <CODE FOR TRUE> ë <CODE FOR FALSE> }

@MagicOctopusUrn Nice!

Tcl, 139 bytes
proc P s {join [lmap c [split $s ""] {expr {[regexp \\d $c]?"[expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]":$c==f?"-":$c}}] ""}

Try it online!

Tcl, 144 bytes
proc P s {join [lmap c [split $s ""] {expr {[regexp \\d $c]?[list [expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]]:$c==f?"-":$c}}] ""}

Try it online!

Tcl, 149 bytes
proc P s {join [lmap c [split $s ""] {if [regexp \\d $c] {list [expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]} {expr {$c==f?"-":$c}}}] ""}

Try it online!

Tcl, 150 bytes
proc P s {join [lmap c [split $s ""] {if [regexp \\d $c] {set v [expr $c&4?"r":"-"][expr $c&2?"w":"-"][expr $c&1?"x":"-"]} {expr {$c==f?"-":$c}}}] ""}

Try it online!

Tcl, 180 bytes
proc P s {join [lmap c [split $s ""] {if [regexp \\d $c] {[set R regsub] (..)1 [$R (.)1(.) [$R 1(..) [$R -all 0 [format %03b $c] -] r\\1] \\1w\\2] \\1x} {expr {$c==f?"-":$c}}}] ""}

Try it online!

Still very ungolfed!

Java (JDK 10), 118 bytes
s->{var r=s[0]=='f'?"-":""+s[0];var z="-xw r".split("");for(int i=0;++i<4;)r+=z[s[i]&4]+z[s[i]&2]+z[s[i]&1];return r;}

Try it online!
Credits

13 bytes saved thanks to Kevin Cruijssen

When you take the input as lowercase fdl, you can change the var r=s[0]<70?"d":s[0]<72?"-":"l"; to var r=s[0]=='f'?"-":s[0]+""; to save 6 bytes. Also, .toCharArray() can be .split("") to save an additional 4 bytes.

@KevinCruijssen Your idea made me save 13 bytes, not 10 (since I could remove the ""+ later on to "cast" a char into a String) ;) Thanks!

Excel, 224 bytes
=IF(LEFT(A1,1)="f","-",LEFT(A1,1))&CHOOSE(MID(A1,2,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx")&CHOOSE(MID(A1,3,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx")&CHOOSE(MID(A1,4,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx")

Done in 4 stages:
IF(LEFT(A1,1)="f","-",LEFT(A1,1))    Replace "f" with "-".

And 3 times:
CHOOSE(MID(A1,2,1)+1,"---","--x","-w-","-wx","r--","r-x","rw-","rwx")

Trying to be smarter, adds 25 bytes per set of rights, 75 in total:
IF(INT(MID(A1,2,1))>3,"r","-")&IF(MOD(MID(A1,2,1),4)>1,"w","-")&IF(ISODD(MID(A1,2,1)),"x","-")

Python 2, 238 bytes
lambda m,r=str.replace,s=str.split,j="".join,b=bin,i=int,z=str.zfill,g=lambda h,y:y if int(h)else "-":r(m[0],"f","-")+j(j([g(z(s(b(i(x)),"b")[1],3)[0],"r"),g(z(s(b(i(x)),"b")[1],3)[1],"w"),g(z(s(b(i(x)),"b")[1],3)[2],"x")])for x in m[1:])

Try it online!
I had assumed this would be a drop in the bucket, but I was wrong indeed. Probably should have realized that a lambda wasn't the best idea at some point.

:| too many builtins = too long

APL+WIN, 55 bytes
Prompts for input string with leading character lower case:
('dl-'['dlf'⍳↑t]),⎕av[46+(,⍉(3⍴2)⊤⍎¨⍕1↓t←⎕)×9⍴69 74 75]

Explanation:
9⍴69 74 75 create a vector of ascii character codes for rwx -46, index origin 1

1↓t←⎕ prompt for input and drop first character

,⍉(3⍴2)⊤⍎¨⍕ create a 9 element vector by concatenating the binary representation for each digit

46+(,⍉(3⍴2)⊤⍎¨⍕1↓t←⎕)×9⍴69 74 75 multiply the two vectors and add 46

⎕av[.....] convert back from ascii code to characters, 46 being '-'

('dl-'['dlf'⍳↑t]), append first character from input swapping '-' for 'f'

J,  57  52 bytes
5 bytes saved thanks to FrownyFrog!
-&.('-DLld'i.{.),[:,('-',:'rwx'){"0 1&.|:~1#:@}."."0

Try it online!
Yet another long solution... I don't know how to make } work in tacit verbs and that's why I used the much longer {"0 1&.|: for selection.
Explanation:
@}. Drop the first symbol and
,.&.": convert the rest to a list of desimal digits
]:#:  convert each digit to a list of binary digits (and cap the fork)
('-',:'rwx') creates a 2-row table and use 0 to select from its first row / 1 - from its second one
   '-',:'rwx'
---
rwx

{"0 1&.|:~ uses the binary digits to select from the table above
[:,  flattens the result
('d-l'{~'DFL'i.{.) formats the first symbol
, appends the fisrt symbol to the list of permissions

The input is already a string, you need 1#:@}."."0

This seems to work: ('d-l'{~'DFL'i.{.) → -&.('-DLld'i.{.)

@FrownyFrog Very nice use of i. and &. Thanks a lot!
By the way, can you explain to me how to use select } in tacit verbs?

2 2 2&#:`('-',:'rwx'"_)}@"."0@}. is exactly the same length

However it doesn’t break on 333 :)

Python 3, 77 bytes
lambda a,*b,k='-xw-r':f'{a}-'[a=='f']+''.join(k[x&4]+k[x&2]+k[x&1]for x in b)

Try it online!

C (gcc), 109 104 bytes
At least C can convert octal input.... :-)
Edit: I realized that the size modifier wasn't strictly required, and that putchar() is shorter than printf() in this case!
f(a,b){char*s="-xwr";scanf("%c%o",&a,&b);putchar(a-70?a:*s);for(a=9;~--a;putchar(s[(1&b>>a)*(a%3+1)]));}

Try it online!
Original:
f(a,b){char*s="-xwr";scanf("%c%3o",&a,&b);putchar(a-70?a:*s);for(a=9;~--a;printf("%c",s[(1&b>>a)*(a%3+1)]));}

Try it online!

PHP, 68 bytes
<?=strtr(strtr($argn,[f=>_,___,__x,_w_,_wx,r__,r_x,rw_,rwx]),_,"-");

translates f in lowercase input to underscore and every octal number to its rwx equivalent, using underscores instead of dashes (to save the need for quotes), then replaces the _ with -.
Run as pipe with -nF or try it online.

Ruby, 80 76 bytes
->a,*b{a.tr(?f,?-)+b.map{("%03b"%_1).gsub(/./){$&>?0?"rwx"[$`.size]:?-}}*""}

Attempt This Online!
Ruby, 64 bytes
A port of user48543's Python 2 solution.
->a,*b{a.tr(?f,?-)+b.map{"-r"[_1/4]+"-w-w"[_1/2]+"-x"[_1%2]}*""}

Attempt This Online!

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


text:
Interpret TwoMega
In this challenge, you will write an interpreter for 2Ω (transcribed as TwoMega), a language based loosely on brainfuck with an infinite-dimensional storage space.
The Language
2Ω contains three pieces of state:

The Tape, which is an infinite list of bits, all initialized to 0. It has a leftmost element, but no rightmost element.
The Memory Pointer, which is a nonnegative integer that is an index of an element in the tape. A higher memory pointer refers to a tape cell further to the right; a memory pointer of 0 refers to the leftmost element. The memory pointer is initialized to 0.
The Hypercube, which is a conceptually ∞-dimensional "box" of cells, each of which contains a bit initialized to 0. The width of the Hypercube is bound in every dimension to only 2 cells, but the infinity of dimensions means the number of cells is uncountable.

An index into the hypercube is an infinite list of bits that refers to a cell in the hypercube (in the same way that a finite list of bits could be used to refer to a hypercube of finite dimension). Because the tape is an infinite list of bits, the entire tape always refers to an element of the Hypercube; this element is called the referent.
2Ω gives meaning to 7 different characters:

< decrements the memory pointer by 1. Decrementing it below 0 is undefined behavior, so you do not need to handle it.
> increments the memory pointer by 1.
! flips the bit at the referent.
. outputs the bit at the referent.
^ replaces the bit at the cell pointed to by the memory pointer on the tape with the inverse of the bit at the referent.
[x] runs the code x as long as the bit at the referent is 1.

The Challenge
Your task is to write a program that takes a string as input and executes that input as a 2Ω program.
This is code-golf, so the shortest valid answer (measured in bytes) wins.
Notes

You can assume that the program will consist solely of the characters <>!.^[] and that [] will be properly nested.
Your interpreter should only be limited by available memory on the system. It should be able to run the sample programs in a reasonable amount of time.

Sample Programs
Print 1:
!.

Print 010:
.!.!.

Print 0 forever:
![!.!]

Print 0 forever, or 1 forever if ! is prepended:
[.]![!.!]

A small note: the number of storage cells is not actually uncountable, as the number of 1s on the tape is always finite. In fact, there is a fairly simple bijection between the natural numbers and the tape states (interpret the tape contents as a backwards binary number), which shows that the Hypercube is basically an infinite 1D array, accessed by flipping bits in an integer pointer value, instead of in/decrementing as in brainfuck.

Also, re: your invitation to write a cat program: there doesn't seem to be an instruction for taking input.

I think there should be sample programs using more of the instruction set.Two simple ones:  . - prints a single zero and then exists; !^!. - prints a single one then exits. More would be good though. At the moment one must understand submissions in order to verify them (and hence upvote them!)

@Lynn The input would be given by having either a 1 or a 0 on cell [0,0,0,0,0,0,0...] (i.e. the presence of a ! at the start of the program).

Then you could do [.]![!.!] to print the value of that cell forever

But the set of reachable cells are countable.

inb4 a 2000 byte BF program

JavaScript (Node.js), 148 bytes
x=>eval(x.replace(e=/./g,c=>({'<':'u/=2','>':'u*=2','!':'e[v]^=1','.':'alert(+!!e[v])','^':'v=(v|u)^u*e[v]','[':'while(e[v]){'}[c]||'}')+';',v=u=1))

Try it online!
It's turing complete
BoolFuck TwoMega
< >^>^>[!]^<<<<[!]^>>[!]!^>[!]!^>[!]!^<<<<(>^>^>1<<<<1>>0>0>0<<<<)
> ^<^<[!]^>>>>[!]^<<[!]!^<[!]!^<[!]!^>>>(^<^<1>>>>1<<0<0<0>>>)

Need init as moving right few places and init the current and right one bit of the address as 1 (>>>>>>>>^>^<)
Try it online!
Place n in BoolFuck is written as (0, 0, ..., 0(n*0), [1], 1, 0, 0, ...).
For >, it does n => n+1
     0 0 0 0 0[1]1 0 0 0 0
^    0 0 0 0 0[x]1 0 0 0 0
<    0 0 0 0[0]x 1 0 0 0 0
^    0 0 0 0[y]x 1 0 0 0 0, yx != 01
<    0 0 0[0]y x 1 0 0 0 0
[!]^ 0 0 0[1]y x 1 0 0 0 0, (0yx10) = 0
>>>> 0 0 0 1 y x 1[0]0 0 0
[!]^ 0 0 0 1 y x 1[1]0 0 0, (1yx10) = 0
<<   0 0 0 1 y[x]1 1 0 0 0
[!]! 0 0 0 1 y[x]1 1 0 0 0, (1yx11) = 1
^    0 0 0 1 y[0]1 1 0 0 0
<    0 0 0 1[y]0 1 1 0 0 0
[!]! 0 0 0 1[y]0 1 1 0 0 0, (1y011) = 1
^    0 0 0 1[0]0 1 1 0 0 0
<    0 0 0[1]0 0 1 1 0 0 0
[!]! 0 0 0[1]0 0 1 1 0 0 0, (10011) = 1
^    0 0 0[0]0 0 1 1 0 0 0
>>>  0 0 0 0 0 0[1]1 0 0 0

Same to how < work

Are you sure this translation is valid? !>. prints 1 in boolfuck but translates to !>^. which prints 1 in TwoMega (> does not affect the tape; ^ does not affect the tape since the referent is 1)

@EsolangingFruit +>; do [1]00... 1[0]0... (output 0), !>^. do (0,0,...)=1, ptr=([0],0,...) (0,0,...)=1, ptr=(0,[0],...) (0,0,...)=1, ptr=(0,[1],...) (output 0), what's wrong?

@EsolangingFruit for !>., only > is a valid command in boolfuck...

@l4m2 In TwoMega, ! inverts the referent, not the tape cell.

@EsolangingFruit so what's wrong here?

I think your code for ^ is wrong, it should be something like e[v]?v&=~u:v|=u.

seems i misunderstood the problem

@l4m2 Looks like your translation contains a few 1 and 0. What are those supposed to mean?

@EsolangingFruit the string before ( has no 1 and 0. Number mean set the current place to 1 or 0, possibly destroy the current placeinfo

I'd appreciate if you were to put an explanation of how the translation works.

This site is for programming contests and challenges. General programming questions are off-topic here. You may be able to get help on Stack Overflow.

Python 2, 167 bytes
t=h=I=0
m=1
E=''
for c in input():i='[<>!.^]'.find(c);E+=' '*I+'while+2**t&h: m/=2 m*=2 h^=2**t print+(2**t&h>0) t=t&~m|m*(2**t&h<1) #'.split()[i]+'\n';I-=~-i/5
exec E

Try it online!
t is the tape. t = 6 means the tape is [0 1 1 0 0 0 …]
m is 2 to the power of the memory pointer. So m = 8 means we're pointing at tape bit 3.
h is the hypercube. h = 80 (bits 4 and 6 set) means the bits at [0 0 1 0 …] and [0 1 1 0 …] are set.
To read the bit at the referent, we check 2t & h. To flip it, we perform h ^= 2t.
We translate the instructions to Python code and execute the result. I stores the indentation level of the while loops.

Either your program or the second test case is wrong

@wastl The second test case was wrong. ;)

Some rearrangements, extra variable for 2**t (-6 bytes).

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

Try it online!
This code was written just so I'd have a place to write a proof of Turing-completeness.
Proof of Turing-completeness
We show a reduction from Boolfuck to TwoMega:
Boolfuck   TwoMega
>          >>
<          <<
.          !^!.!^!
[          !^![!^!
]          !^!]!^!
+          !^[!]^[>!^<[!]!^>[!]!^<]

This translation stores the Boolfuck state in the even-numbered tape cells in TwoMega.  All of the translated commands will preserve the following invariants:

The memory pointer is at an even-numbered cell.
All odd-numbered tape cells are zero.
For any possible tape with all odd-numbered cells zero, the corresponding value on the hypercube is zero.

The snippet !^! will keep [0]0 constant and swap between 0[0] and [1]1 (where attention is limited to the line on the hypercube reachable without moving the memory pointer).  As such, it is used to temporarily put the current tape value into the referent for the Boolfuck commands which care about it.
If TwoMega were given an input command , with the expected semantics, the Boolfuck command , would translate to >^<,!^>[!]!^<.  Since , is not necessary to prove that Boolfuck is Turing-complete, the lack of an input command does not affect this proof.

It mainly stores info in the position in the hypercube rather than the cube itself?

@l4m2 My reduction from BoolFuck does not store any data in the cube itself.  Any 1s I make on the hypercube are only there to set tape cells to 0.

Python 3, 297 284 274 bytes
-10 bytes thanks to ovs and Jonathan Allan
C=input()
h={}
t=set()
def f(C,p):
 c=C[0];r=hash(frozenset(t));v=h.get(r,0)
 p={"<":p-1,">":p+1}.get(c,p)
 if'"'>c:h[r]=not v
 if"."==c:print(int(v))
 if"]"<c:t.discard(p)if v else t.add(p)
 if"["==c:
  while f(C[1:],p):1
 else:return c=="]"and v or C and f(C[1:],p)
f(C,0)

Try it online!

t.discard(p) -> t-={p}

@shooqie That doesn't work unless t is global.

@fergusq Though I'm pretty sure it works if you declare f as f(C,p,t=set())

Pip, 75 71 bytes
lPB0aR:^"!><[].^_""!:_
--viPU0
++v
W_{
}
O_
i@v:!_LFBilPB0
l@FBi"^n;Vau

Try it online!
Translates the 2Ω code into equivalent Pip code and evaluates it.
We use i to represent the tape, v for the tape pointer*, and l for the hypercube. The first two come preinitialized to useful values; l starts as [], to which we push a 0 (lPU0) to avoid indexing-empty-list problems.
* Actually, it's the bitwise negation of the tape pointer, because we're storing the tape backwards for easier conversion to decimal.
The rest of the code is:
aR:...;     Do a bunch of replacements in a, translating it into Pip code
       Va   Evaluate a
         u  Suppress output of the final expression that was evaluated

The translation table:
!  !:_
>  --viPU0
<  ++v
[  W_{
]  }
.  O_
^  i@v:!_LFBilPB0
_  l@FBi

l@FBi is the referent: element of hypercube l at the index (convert i from binary). It appears often, so we call it _ and replace _ with the real code at the end.

!:_ logically negates the referent in place.
--viPU0 decrements v (moving the tape pointer to the right); it then pushes another 0 to the left side of i, to make sure that the tape pointer stays in bounds.
++v increments v (no need for bounds-checking, per OP).
W_{ runs a loop while the referent is truthy (i.e. nonzero, i.e. 1).
} closes the loop.
O_ outputs the referent without newline.

Finally, for ^:
i@v:            Set the current tape cell to
    !_          The logical negation of the referent
                Now, make sure the list representing the hypercube is long enough:
      LFBi      Loop frombinary(i) times:
          lPB0  Push another 0 to the end of l
                This ensures that FBi will always be a valid index into l

source: Stack Exchange

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

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

sort: votes


text:
Triangular Lattice Points close to the Origin
Background
A triangular grid is a grid formed by tiling the plane regularly with equilateral triangles of side length 1. The picture below is an example of a triangular grid.

A triangular lattice point is a vertex of a triangle forming the triangular grid.
The origin is a fixed point on the plane, which is one of the triangular lattice points.
Challenge
Given a non-negative integer n, find the number of triangular lattice points whose Euclidean distance from the origin is less than or equal to n.
Example
The following figure is an example for n = 7 (showing only 60-degree area for convenience, with point A being the origin):

Test Cases
Input | Output
---------------
    0 |       1
    1 |       7
    2 |      19
    3 |      37
    4 |      61
    5 |      91
    6 |     127
    7 |     187
    8 |     241
    9 |     301
   10 |     367
   11 |     439
   12 |     517
   13 |     613
   14 |     721
   15 |     823
   16 |     931
   17 |    1045
   18 |    1165
   19 |    1303
   20 |    1459
   40 |    5815
   60 |   13057
   80 |   23233
  100 |   36295
  200 |  145051
  500 |  906901
 1000 | 3627559

Hint: This sequence is not OEIS A003215.
Rules
Standard rules for code-golf apply. The shortest submission wins.
Please include how you solved the challenge in your submission.

OEIS A053416 is the sequence of the number of points contained in a circle of diameter rather than radius n, so has twice as many terms as you want.

Relevant Wikipedia and Mathworld. Contains xnor's formula and not proof.

It is the sum of the first n^2+1 terms of OEIS A004016.

Python 2, 43 bytes
f=lambda n,a=1:n*n<a/3or n*n/a*6-f(n,a+a%3)

Try it online!
This is black magic.
Offering 250 rep for a written-up proof. See Lynn's answer for a proof and explanation.

How does this work? I've been wondering for a good 30 minutes... It looks so simple but I can't find a relationship between that recursion and circles...

@xnor you should hold off on the explanation and see if anyone guesses at this point hah.

@JungHwanMin My proof is an epic journey through plane geometry, Eisenstein integers, factorization over number fields, quadratic reciprocity, arithmetic progressions, and interchanging summations -- all for such a simple expression. Writing it all would be a major undertaking that I don't have time for now, so I'm hoping someone else will give a proof, likely a simpler one that mine that makes the connection clearer.

Hmm. Why doesn't n*n<a work as upper bound

Proof. This is longer than Lynn's but more self-contained: it makes no use of unproven assertions about factorisation over the Eisenstein integers.

@PeterTaylor Cheddar Monk? As in Darths & Droids?

@Neil, congratulations on being the first person ever to ask! I registered the domain to use it as a bargaining chip for Negotiation, Level 1 in the Academy.

@PeterTaylor I've seen Piet answers here, so I guess I shouldn't have been so surprised...

ditto

Haskell, 48 bytes
f n=1+6*sum[(mod(i+1)3-1)*div(n^2)i|i<-[1..n^2]]

Try it online!
Uses xnor's "black magic" formula:
$$f(n)=1+6\sum_{a=0}^\infty \left\lfloor \frac{n^2}{3a+1}\right\rfloor -  \left\lfloor \frac{n^2}{3a+2}\right\rfloor$$
A proof of its correctness, and an explanation of how xnor managed to express it in 43 bytes of Python, can be found here.

Long story short: we count Eisenstein integers of norm \$1 \le N \le n^2\$, by factoring \$N = (x+y\omega)(x+y\omega^*)\$ into Eisenstein primes and counting how many solutions for \$(x,y)\$ come out of the factorization. We recognize the number of solutions as being equal to
$$6 \times ((\text{# of divisors of }N \equiv 1\space(\text{mod }3)) - (\text{# of divisors of }N \equiv 2\space(\text{mod }3)))$$
and apply a clever trick to make that really easy to compute for all integers between \$1\$ and \$n^2\$ at once. This yields the formula above. Finally, we apply some Python golf magic to end up with the really tiny solution xnor found.

I certainly didn't expect this when xnor said "there's some deep mathematical insights behind golfing the problem".

In this question I've just said "But if you find yourself considering computations like matrix division or using Eisenstein integers or Euclid's algorithm in the complex plane please save that for the follow-up code-challenge question"

Wolfram Language (Mathematica), 53 51 50 bytes
-1 byte thanks to @miles
Sum[Boole[x(x+y)+y^2<=#^2],{x,-2#,2#},{y,-2#,2#}]&

Try it online!
How?
Instead of thinking in this:

Think of it like this:

So we apply the tranformation matrix [[sqrt(3)/2, 0], [1/2, 1]] to transform the second figure to the first one.
Then, we must find the circle in the triangular grid in terms of Cartesian coordinates.
(sqrt(3)/2 x)^2 + (1/2 x + y)^2 = x^2 + x y + y^2

So we find lattice points x, y such that x^2 + x y + y^2 <= r^2
For example, with r = 3:

FYI, the formula x^2+x y+y^2 can also be derived from the Law of Cosines with 120 degrees.

x^2+x y+y^2 -> x(x+y)+y^2 saves a byte

The formula x^2 + xy + y^2 can also be derived from the norm of an Eistenstein integer, which is a^2 - ab + b^2. Note that the sign of a and b is irrelevant except in the term ab so it has the same amount of solutions.

Wolfram Language (Mathematica), 48 bytes
Based on OEIS A004016.
1+6Sum[DivisorSum[i,#~JacobiSymbol~3&],{i,#^2}]&

Try it online!

CJam (24 bytes)
{_*_,f{)_)3%(@@/*}1b6*)}

This is an anonymous block (function) which takes one argument on the stack and leaves the result on the stack. Online test suite. Note that the two largest cases are too slow.
Explanation
alephalpha noted in a comment on the question that

It is the sum of the first n^2+1 terms of OEIS A004016

and xnor's answer implements this sum (although I'm not sure whether their unposted proof uses it explicitly) as $$f(n) = 1 + 6 \sum_{a=0}^\infty \left\lfloor\frac{n^2}{3a+1}\right\rfloor - \left\lfloor\frac{n^2}{3a+2}\right\rfloor$$
My proof of correctness of that formula is based on some information gleaned from alephalpha's OEIS link:

G.f.: 1 + 6*Sum_{n>=1} x^(3*n-2)/(1-x^(3*n-2)) - x^(3*n-1)/(1-x^(3*n-1)). - Paul D. Hanna, Jul 03 2011

for which the relevant reference is the paper by Hirschhorn. An elementary proof is possible using nothing more than a basic understanding of complex numbers (cube roots of unity, magnitude), the concept of generating functions, the derivative of \$x^a\$, and the chain rule of differentiation. In summary, we first prove from first principles the Jacobi triple-product identity $$\prod_{k=0}^\infty (1-q^{k+1})(1 + xq^{k+1})(1 + x^{-1}q^k) = \sum_{k\in \mathbb{Z}} q^{k(k+1)/2}x^k$$
That then bootstraps a proof that $$\sum_{m,n \in \mathbb{Z}} \omega^{m-n} q^{m^2+mn+n^2} = \prod_{k=1}^\infty \frac{(1-q^k)^3}{1-q^{3k}}$$ where \$\omega\$ is a primitive cube root of unity. The final big step is to use this to show that $$\sum_{m,n \in \mathbb{Z}} q^{m^2+mn+n^2} = 1 + 6 \sum_{k \ge 0} \left(\frac{q^{3k+1}}{1-q^{3k+1}} - \frac{q^{3k+2}}{1-q^{3k+2}} \right)$$
Code dissection
{          e# Define a block. Stack: ... r
  _*       e#   Square it
  _,f{     e#   Map with parameter: invokes block for (r^2, 0), (r^2, 1), ... (r^2, r^2-1)
    )      e#     Increment second parameter. Stack: ... r^2 x with 1 <= x <= r^2
    _)3%(  e#     Duplicate x and map to whichever of 0, 1, -1 is equal to it (mod 3)
    @@/*   e#     Evaluate (r^2 / x) * (x mod 3)
  }
  1b6*     e#   Sum and multiply by 6
  )        e#   Increment to count the point at the origin
}

APL (Dyalog Classic), 23 bytes
{1+6×+/-/⌊⍵÷1+3⊥¨⍳⍵2}×⍨

Try it online!
tribute to xnor's and lynn's answers
the last test is commented because it needs more memory, e.g. MAXWS=200M in the env

J, 27 bytes
[:+/@,*:>:(*++&*:)"{~@i:@+:

Try it online!
Based on JungHwan Min's method.
Explanation
[:+/@,*:>:(*++&*:)"{~@i:@+:  Input: n
                         +:  Double
                      i:     Range [-2n .. 2n]
                  "{~        For each pair (x, y)
                *:             Square both x and y
              +                Add x^2 and y^2
             +                 Plus
            *                  Product of x and y
        >:                   Less than or equal to
      *:                     Square of n
     ,                       Flatten
  +/                         Reduce by addition

Jelly,  15  13 bytes
-2 thanks to Dennis (just increment the square to avoid concatenation of a zero; avoid head by using a post-difference modulo-slice rather than a pre-difference slice)
Uses the "black magic" method of honing in on the answer that was exposed by xnor in their Python answer, but uses iteration rather than recursion (and a little less calculation)
²:Ð€‘$Im3S×6C

A monadic link accepting a non-negative integer and returning a positive integer.
Try it online! Or see the test-suite.
How?
²:Ð€‘$Im3S×6C - Main Link: non-negative integer, n     e.g. 7
²             - square                                     49
     $        - last two links as a monad:
    ‘         -   increment                                50
  Ð€          -   map across (implicit range of) right with:
 :            -     integer division                       [49,24,16,12,9,8,7,6,5,4,4,4,3,3,3,3,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0]
      I       - incremental differences                    [-25,-8,-4,-3,-1,-1,-1,-1,-1,0,0,-1,0,0,0,-1,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1]
       m3     - every third element                        [-25,-3,-1,0,0,-1,0,0,0,0,0,0,0,0,0,0,-1]
         S    - sum (vectorises)                           -31
          ×6  - multiply by six                           -186
            C - complement (1-X)                           187

Jelly, 14 bytes
ḤŒR+²_×ʋþ`F½»ċ

Uses @JungHwanMin's method.
Try it online!

05AB1E, 15 14 bytes
nD>L÷¥3ιнO6*±Ì

Port of @JonathanAllans Jelly answer, which in turn is a derivative from @xnor's 'black magic' formula.
Try it online or verify all test cases.
Explanation:
n               # Square the (implicit) input-integer
 D>             # Duplicate it, and increase the copy by 1
   L            # Create a list in the range [1, input²+1]
    ÷           # Integer divide input² by each of these integers
     ¥          # Take the deltas / forward differences
      3ι        # Uninterleave this list into 3 parts
                #  i.e. [a,b,c,d,e] → [[a,d],[b,e],[c]]
        н       # Pop and leave the first inner list
         O      # Take the sum of this list
          6*    # Multiply it by 6
            ±   # Take the bitwise NOT (-n-1)
             Ì  # And increase it by 2
                # (after which the result is output implicitly)

JavaScript (ES6), 65 bytes
This is a port of @JungHwanMin's solution.
f=(n,y=x=w=n*2)=>y-~w&&(x*x+x*y+y*y<=n*n)+f(n,y-=--x<-w&&(x=w,1))

Try it online!

Original answer (ES7), 70 bytes
Simply walks through the grid and counts the matching points.
f=(n,y=x=n*=2)=>y+n+2&&(x*x*3+(y-x%2)**2<=n*n)+f(n,y-=--x<-n&&(x=n,2))

Try it online!

Porting xnor's answer is shorter: 42 bytes (outputs true instead of 1; 46 if we also integer-divide it). And I don't know JavaScript well enough to golf the integer-divisions ~~(a/b), but I'm sure there is a shorter way for those as well..

Wolfram Language (Mathematica), 39 bytes
Length@Solve[x(x+y)+y^2<=#^2,Integers]&

Try it online!
Using JungHwan Min's coordinate transformation and simply counting the solutions over the integers.

Pari/GP, 42 bytes
Using the built-in qfrep.
n->1+2*vecsum(Vec(qfrep([2,1;1,2],n^2,1)))

qfrep(q,B,{flag=0}): vector of (half) the number of vectors of norms from 1 to
  B for the integral and definite quadratic form q. If flag is 1, count vectors
  of even norm from 1 to 2B.

Try it online!

Java 8, 65 bytes
n->f(n,1)int f(int n,int a){return n*n<a/3?1:n*n/a*6-f(n,a+a%3);}

Port of @xnor's Python 2 answer.
Try it online.

C# (Visual C# Interactive Compiler), 68 bytes
n=>{int g(int x,int y)=>x*x<y/3?1:x*x/y*6-g(x,y+y%3);return g(n,1);}

Try it online!
Same as everyone else, unfortunately. I know there's probably a better way of writing this, but declaring and calling a lambda at the same time in c# is not exactly something I do, well, ever. Though in my defense, I can't think of a good reason (outside code golf, of course) to do so. Still, if someone knows how you can do this, let me know and/or steal the credit, I guess.

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


text:
Is this a staircase number?
Challenge :
Check if the given number forms a number staircase or not

Input :
A integer (greater than 0 and not decimal). NOTE : You can take input as string , array of digits.

Output :
a truthy / falsy value depending on whether the number forms a staircase or not

Number staircase :
A number staircase is an integer that , when read from left to right :

Starts with 1
which may be followed by 2
which may be followed by 3
and so on till n
then the number descends starting at n - 1
then n - 2
then n - 3
and so on till it reaches 1

Note :
The may be part is used to indicate that if length > is greater than 1. If it is the order must be followed as is. i.e : 12321

Example :
12321                          ---> true
12345654321                    ---> true
9                              ---> false
1                              ---> true
2                              ---> false
123421                         ---> false
112312318901323                ---> false
123456789101110987654321       ---> true

Note :
The input given will always be an integer greater than 0 and will not be a decimal. Your output must be a truthy or falsy value depending on the input

Restrictions :
This is code-golf so shortest code in bytes (for each programming language ) wins.

Can we take input as a list of digits? Like [1,2,3,4,5,6,7,8,9,1,0,1,1,1,0,9,8,7,6,5,4,3,2,1] for 123456789101110987654321?

@Mr.Xcoder : I would rather prefer if you didn't but I guess you can

Is there an upper limit on the input?

@mypetlion : Not really , it is as high as your code can support (excluding hardcoded and purposedly low ones.) Normally the highest your language can support (but not in this case)

May we take a string of characters as input to a function? (or is this only acceptable input for a full-program?)

@JonathanAllan : You may take that as a function.

@JoKing : normally yes , but in this case I do since this . Although it is different sadly the name is same so

@JoKing : Why not!

"and so on till it reaches 0" - should be "and so on till it reaches 1".

@djhurio : nice catch. Thanks.

Very closely related, nearly a dupe. It's slightly different, since this one allows the string to go above 9, but other than that they're the same.

R, 97 bytes
function(n)"if"(n>1,{while({T=T+1;x=paste(c(1:T,T:2-1),collapse="");nchar(x)<nchar(n)})0;x==n},T)

Try it online!
Takes n as a character or an integer; using character will give correct results for integers that can't be held precisely as a 64-bit double.
Generates staircase numbers until it finds one at least as long as n is, then tests for equality.
Equivalent to:
function(n)
    if(n > 1){
        T <- T + 1
        x <- paste(c(1:T,T:2-1),collapse="")
        while(nchar(x) < nchar(n)){
            T <- T + 1
            x <- paste(c(1:T,T:2-1),collapse="")
        }
        return(x == n)
    } else
        return(TRUE)

Wouldn't replacing function(n) with n=scan(); be shorter? (for integers of course)

@pajonk I suppose so. But I'll say I'm taking it as a string so this answer is correct for larger inputs.

Jelly, 5 bytes
ŒḄ€Vċ

Try it online!
Warning: Very slow (fast for 1 and 121)! Prepend DL to make it faster.

JavaScript (ES6), 62 57 bytes
Saved 2 bytes thanks to @l4m2
Returns a boolean.
f=(s,k=1)=>(m=s.match(`^${k}(.*)${k}$`))?f(m[1],k+1):s==k

Try it online!
How?
Starting with k = 1, we look for k at the beginning and at the end of the string, and recursively iterate the process on the remaining middle sub-string with k + 1. The recursion stops as soon as there's no match anymore. The input is a staircase number if the last sub-string is equal to k.
Example for s = "1234321":
 k | s         | match     | s == k
---+-----------+-----------+--------
 1 | "1234321" | 1(23432)1 | no
 2 | "2343"    | 2(343)2   | no
 3 | "343"     | 3(4)3     | no
 4 | "4"       | null      | yes

55 bytes. Assume 0 as truthy and null as falsy (he didn't exactly specify did he)

Hum I didn't see that guess that's invalid. Sorry

@I'mnoone No worries! Interestingly, removing m[0]==s& instead would make it pass all test cases (but still fail on other ones such as "123217").

f=(s,k=1)=>(m=s.match(`^${k}(.*)${k}$`))?f(m[1],k+1):s==k ?

Pyth, 13 12 bytes
/mjk+Sd_Stdl

Saved a byte thanks to RK.
Try it here
Explanation
/mjk+Sd_Stdl
 m         lQ   For each d up to the length of the (implicit) input...
    +Sd_Std     ... get the list [1, 2, ..., d, d-1, ..., 1]...
  jk            ... concatenated.
/               Count how many times the input appears.

If you really want the input as an integer, you can use }Qmsjk+Sd_Std instead, but this is horrifyingly slow.

you can use / instead of }Q so it autocompletes Q at the end

Haskell, 55 54 bytes
-1 byte thanks to Laikoni!
f x=elem x[read$[1..z]++[z-1,z-2..1]>>=show|z<-[1..x]]

Try it online!

Python 2, 69 bytes
f=lambda s,n=1,t='1',u='':t+':'>s>t<s*f(s,n+1,t+`n+1`,`n`+u)or s==t+u

Try it online!

C# (Visual C# Interactive Compiler), 138 107 102 bytes
bool t(List<int>s)=>s.Select((j,i)=>s[0]==1&&s.Last()==1&&(i==0||j+1==s[i-1]||j-1==s[i-1])).All(x=>x);

Try it online!
Explanation:
bool t(List<int>s)=>
    s.Select((j,i) =>         //iterate over each item and store the return value
        s[0]==1&&s.Last()==1  //does the sequence start and end with 1?
        &&                    //AND
        (i==0                 //is it the first item?
        ||                    //OR
        j+1==s[i-1]           //is the item 1 greater than the previous?
        ||                    //OR
        j-1==s[i-1])          //is the item 1 smaller than the previous?
    ).All(x=>x);              //did all pass the criteria?

Actually, the Zip...Skip method in my previous comment fails on [1,1], which should return true if I understand the spec. I've deleted it.

Thanks anyway! I've never utilized Zip before, but I see now how it can be useful.

05AB1E, 9 8 bytes
L€L€ûJså

Warning: EXTREMELY SLOW! Add g to the start to speed it up.
Try it online!
Explanation:
L           1..input
 €L         for each element, map to 1..element
   €û       palindromize each element
     J      join each element from a list to a string
      så    is the input in that list?

Old Explanation:
F           For [0 .. input] map over
 NL          Push 1..i
   û         Palindromize
    J        Join
     ¹       First input
      Q      Equal?
       }   end loop
        O  Sum.

Try it online!

Palindromize ? What does this do? Because as you may know the stairs with 10+ are no palindromes

@YassinHajaj It palindromises the array, not the string

Alright thanks for the info

@YassinHajaj gLη€ûJså is another, where you can see the vectorization of the palindromization using €û palindromize each.

@okx gLη€ûJså for an 8-byte that doesn't blow up TIO.

Python 2, 77 bytes
lambda s,r=range:s in[''.join(map(str,r(1,k+2)+r(k,0,-1)))for k in r(len(s))]

Try it online!

Save four by accepting an integer if we may error once we hit longs: TIO. We'd need quite some time and memory by that point anyway!

Attache, 57 55 46 bytes
{GenerateFirst[N@Join@Bounce@1&`:,`>=:`#&_]=_}

Try it online! Ah, that's much more elegant.
With Generate (49 bytes):
{g@Generate[{g@_>=#_2}&_]=_}g:=N@Join@Bounce@1&`:

Explanation
{GenerateFirst[N@Join@Bounce@1&`:,`>=:`#&_]=_}
{                                            }   anonymous lambda, argument: _
 GenerateFirst[                  ,        ]      find the first element satisfying...
               N@Join@Bounce@1&`:                    this generation function
                                  `>=:`#&_           and this condition
                                           =_    is it equal to the input?

The generation function simply creates the Nth staircase number. Then, this search terminates once `>=:`#&_ is satisfied. Expanded, this is:
 `>=:`#&_
 (`>= : `#) & _      NB. remember _ is the input
                     NB. also, f:g is f[...Map[g, args]]
 { #_1 >= #_2 } & _
 { Size[_1] >= Size[_2] } & _
 { Size[_1] >= Size[the original input] }
 [n] -> { Size[n] >= Size[input] }

So, this terminates once the length of the generation function's output is at least that of the inputs. Thus, this generates the smallest staircase number at least as long as the input number. Thus, if the input is a staircase number, the result will be the same staircase number, and otherwise the next longest staircase number. As such, a simple check with equality to the original input is sufficient for determining whether or not it was a staircase number.
Attache, 55 bytes
0&{If[#_2>#g[_],$[_+1,_2],_2=g!_]}g:=N@Join@Bounce@1&`:

Try it online! With plan ol' recursion.

Stax, 14 bytes
Ç╗☻W╧ΩÆΘαφ←≤─♣

Run and debug it
Very slow for bigger numbers.

9 bytes

Slight change for 7 bytes

And a fast one at 8 bytes

J, 40 bytes
1#.[:(<-:"_1<@([:;>:<@":@-|@i:)@<:@#\)":

Try it online!
I'm not quite happy with this soluiton - a lot of @ and boxing < .

SNOBOL4 (CSNOBOL4), 109 bytes
	N =INPUT
	X =L ='1'
C	R =LT(SIZE(L R),SIZE(N)) X R	:F(O)
	X =X + 1
	L =L X	:(C)
O	OUTPUT =IDENT(L R,N) 1
END

Try it online!
Curiously, replacing '1' in the second line with 1 causes the program to fail on the input of 1.

K, 36 bytes
{|/($x)~/:{,/$(1+!x),1+1_|!x}'1+!#x}

Takes a string such as "12321" as a parameter.
This function is written as a long chain of function applications, as in f g h x, so read the commented versions from the bottom, going up.
{x+1} is lambda x: x+1, x is a default param name. Check out https://pastebin.com/cRwXJn7Z or the interpreter's help for operator meanings.
We generate the staircase number with n in the middle by {,/$(1+!x),1+1_|!x}:
{,/                      / join all the chars
   $                     / tostring each number
     (1+!x)              / take the range [0..x-1]; add 1 to each
            ,            / concat
             (1+1_|!x)}  / take the range [0..x-1]; reverse it; drop 1; add 1 to each

The whole function {|/($x)~/:{,/$(1+!x),1+1_|!x}'1+!#x}:
{|/                                   / any_is_true
   ($x)~/:                            / match the string with each of the generated staircases
          {,/$(1+!x),1+1_|!x}'        / make staircase number of each of the numbers
                                      / (note: the x in the inner lambda shadows the outer x)
                              1+!#x}  / take the range [1..length of the string, inclusive]

Japt, 11 bytes
Takes input as a string.
Êõõ mê m¬øU

Try it

Explanation
                :Implicit input of string U
Ê               :Length of U
 õ              :Range [1,Ê]
  õ             :Range [1,el] for each element
    mê          :Map & palidromise
       m¬       :Map & join
         øU     :Contains U?

Alternative, 10 9 bytes
This solution, which can take input as a string or an integer, will return an array of numbers for truthy or, eventually, throw an error for falsey, if it doesn't cripple your browser before that. Use with caution.
@¥Xê q}aõ

Try it

Haskell, 64 60 58 bytes
-6 thanks to @BMO!
elem.show<*>(`take`[[1..n]++[n-1,n-2..1]>>=show|n<-[1..]])

Try it online!

Theoretically works for 12345678910987654321, if you are able to construct a list with that many elements.

@BMO I knew there had to be a way to do that. Thanks

@BMO Your golf is really obvious in hindsight...

It's also very close, I would have suggested it as an improvement if I didn't already post it (I didn't see yours until I posted mine).

Perl 5 -lp, 49 bytes
$i++while s/^$i//;$i-=2;$i--while s/^$i//;$_||=$i

Try it online!
0 = truthy, anything else = falsy

Retina, 45 43 bytes
$
;1
+`^(.+)(.*)\1;\1$
$2;$.(_$1*
^(.+);\1$

Try it online! Link includes test cases. Edit: Saved 2 bytes thanks to @Leo. Explanation:
$
;1

Initialise n to 1.
+`^(.+)(.*)\1;\1$

While s begins and ends with n:
$2;$.(_$1*

Delete n from the ends of s and increment n.
^(.+);\1$

Test whether n is left.

I think your \ds can become . and save you two bytes

Java 10, 142 bytes
s->{int n=1,l,f=1;try{for(;;s=s.substring(l=(n+++"").length(),s.length()-l))if(!s.matches(n+".*"+n)&!s.equals(n+""))f=0;}finally{return f>0;}}

Try it online.
Explanation:
s->{                 // Method with String parameter and boolean return-type
  int n=1,           //  Stair integer, starting at 1
      l,             //  Length integer to reduce bytes
      f=1;           //  Result-flag, starting at 1
  try{for(;;         //  Loop until an error occurs
          s=s.substring(l=(n+++"").length(),s.length()-l))
                     //    After every iteration: remove `n` from the sides of the String
        if(!s.matches(n+".*"+n)
                     //   If the current String with the current `n` isn't a stair
           &!s.equals(n+""))
                     //   And they are also not equal (for the middle)
          f=0;       //    Set the flag to 0
   }finally{         //  After the error (StringOutOfBoundsException) occurred:
      return f>0;}}  //   Return whether the flag is still 1

Regex (PCRE), 92 bytes
^(1|\d(?=1|9)|[2-79](?=8)|[2-68](?=7)|[2-57](?=6)|[2346](?=5)|[235](?=4)|[24](?=3)|3(?=2))+$

Try it online!
I'm open to any suggestions to improve this.

Thanks to following users:
@Nooneishere
@LyricLy
@JoKing

Python 2, 147 bytes
g=s=input()
f=1
o='1'==s[0]
while`f`==s[0]:s=s[len(`f`):];f+=1
f-=2
o&=`f`==s[0]
while s and`f`==s[0]:s=s[len(`f`):];f-=1
o&=f==0
o|=g=='1'
print o

Try it online!

The output doesn't have to be the strings true and false but truthy and falsey values. 1 and 0 would work for example

@dylnan : I just read that , thanks. Still golfing (a lot to go)

Couldn't you just use s[0] instead of startswith? Errors are allowed, and you can say 'outputs 1 for staircase, anything else (including nothing) [since stderrr is ignored] for non-staircase'.

@NoOneIsHere : good idea. apparently coding while sleeping is not such a good idea thanks

You can save bytes by replacing the if x:o=0 statements with o*=x.

This doesn't work without a trailing character for truthy inputs

This fixes most of your issues, but still doesn't support staircase numbers above n=9

Your 138 byte solution always returns False, since g is never 1. You should probably test these solutions before posting them...


text:
Elixir Array Syntactic Sugar
In Elixir, (linked) lists are in the format [head | tail] where head can be anything and tail is a list of the rest of the list, and [] - the empty list - is the only exception to this.
Lists can also be written like [1, 2, 3] which is equivalent to [1 | [2 | [3 | []]]]
Your task is to convert a list as described. The input will always be a valid list (in Elixir) containing only numbers matching the regex \[(\d+(, ?\d+)*)?\]. You may take the input with (one space after each comma) or without spaces. The output may be with (one space before and after each |) or without spaces.
For inputs with leading zeroes you may output either without the zeroes or with.
Input must be taken as a string (if writing a function), as does output.
Examples
[] -> []
[5] -> [5 | []]
[1, 7] -> [1 | [7 | []]]
[4, 4, 4] -> [4 | [4 | [4 | []]]]
[10, 333] -> [10 | [333 | []]]

related, not a duplicate as this in part involves adding mode ] to the end. Additionally, the Haskell answer here is quite different to the one there.

-1 from me. Cumbersome IO formats are discouraged. If the input is a  list, let us take it as a list instead of having 90% of our code just parsing the input

very similar, but I wouldn't quite call it a dupe.

@JoKing Discouraged, not banned :)

Do we have to support leading 0s? They fit the regex.

Why does the output need a space before and after a | (if we include spaces)? Elixer seems to parse any number of spaces, including none

Possible duplicate of Sugar Free Syntax

@JoKing I'd argue that here the challenge itself is about converting between two specific formats, so parsing the input is a fundamental part of the challenge and not something extra added to it. P.S. I've realized only now what your nickname really is xD

Why do we want to take input as string , and same for output. That is 14 bytes worth in JavaScript just converting back and forth.

@MuhammadSalman: the challenge is tagged as "parsing", so converting from/to a string is a substantial part of it with intent.

Haskell, 50 bytes
f.read
f(a:b)='[':show(a+0)++'|':f b++"]"
f _="[]"

Try it online!
The +0 lets the Haskell type checker know that we are dealing with lists of numbers, so read will parse the input string for us.

+1, I love the +0 trick!

Python 2, 50 bytes
r='%s'
for x in input():r%='[%s|%%s]'%x
print r%[]

Try it online!

So beautiful ;-;

JavaScript (ES6), 50 bytes
s=>eval(s).map(v=>`[${p+=']',v}|`,p='[]').join``+p

Try it online!

Recursive version, 51 bytes
f=(s,[v,...a]=eval(s))=>1/v?`[${v}|${f(s,a)}]`:'[]'

Try it online!

Retina, 39 33 32 20 bytes
\b]
,]
+`,(.*)
|[$1]

Saved 13 bytes thanks to H.PWiz, ovs, ASCII-only, and Neil.
Try it online!
Explanation
\b]
,]

If we don't have an empty list, add a trailing comma.
+`,(.*)
|[$1]

While there are commas, wrap things with |[ thing ].

@ovs 24?

also 24?

@ASCII-only You can save another 4 bytes by replacing \b] with ,]. (Otherwise I had independently discovered the same solution.)

Oh, that's right. I forgot \b was a thing for some reason >_> 20 bytes @Mnemonic

Perl 5 -pl, 31 28 bytes
s/\d\K]/,]/;$\=']'x s/,/|[/g

Try it online!
How?
-p                    # (command line) Implicit input/output via $_ and $\
s/\d\K]/,]/;          # insert a comma at the end if the list is not empty
$\=']'x s/,/|[/g      # At the end of the run, output as many ']' as there are
                      # commas in the input.  Replace the commas with "|["

Elixir, 111 85 bytes
f=fn[h|t],f->"[#{h}|#{f.(t,f)}]"
[],_->"[]"
h,f->f.(elem(Code.eval_string(h),0),f)end

Try it online!
I have never used Elixir before. Defines a function that takes a string and a reference to itself and returns a string.

Ceylon, 113 bytes
String p(String s)=>s.split(" ,[]".contains).select((x)=>!x.empty).reversed.fold("[]")((t,h)=>"[``h`` | ``t``]");

Try it online!
Here is it written out:
// define a function p mapping Strings to Strings.
String p(String s) =>
    // we split the string at all characters which are brackets, comma or space.
    s.split(" ,[]".contains)    // → {String+}, e.g.  { "", "1", "7", "" }
    // That iterable contains empty strings, so let's remove them.
    // Using `select` instead of `filter` makes the result a sequential instead of
    // an Iterable.
     .select((x)=>!x.empty)    // → [String*], e.g.   [1, 7]
    // now invert the order.
    // (This needs a Sequential (or at least a List) instead of an Iterable.)
     .reversed                 // → [String*], e.g.   [7, 1]
    // Now iterate over the list, starting with "[]", and apply a function
    // to each element with the intermediate result.
     .fold("[]")                       // → String(String(String, String))
    //    This function takes the intermediate result `t` (for tail) and an element
    //    `h` (for head), and puts them together into brackets, with a " | " in the
    //    middle. This uses String interpolation, I could have used `"+` and `+"`
    //    instead for the same length.
          ((t,h)=>"[``h`` | ``t``]");  // → String

Try it online!
As noted by ovs in a (now deleted) comment: If one select the "without spaces" options for input and output indicated in the question, one can safe 3 more bytes (the obvious ones with spaces in them).
If we don't need to parse the input, but just could get a sequence as input, it gets much shorter (69 bytes).
String p(Object[]s)=>s.reversed.fold("[]")((t,h)=>"[``h`` | ``t``]");

Try it online!

Python 3, 65 bytes
lambda k:"["+''.join(f"{u}|["for u in eval(k))+-~len(eval(k))*"]"

Try it online!
If the input could be a list instead, then:
Python 3, 53 bytes
lambda k:"["+''.join(f"{u}|["for u in k)+-~len(k)*"]"

Try it online!

SNOBOL4 (CSNOBOL4), 114 bytes
	I =INPUT
S	N =N + 1
	I SPAN(1234567890) . L REM . I	:F(O)
	O =O '[' L ' | '	:(S)
O	OUTPUT =O '[' DUPL(']',N)
END

Try it online!
	I =INPUT				;* read input
S	N =N + 1				;* counter for number of elements (including empty list)
	I SPAN(1234567890) . L REM . I	:F(O)	;* get value matching \d until none left
	O =O '[' L ' | '	:(S)		;* build output string
O	OUTPUT =O '[' DUPL(']',N)		;* print O concatenated with a '[' and N copies of ']'
END

Befunge-98 (PyFunge), 22 21 bytes
'[,1;@j,]';#$&." |",,

Try it online!
If there weren't weird restrictions on output, we could do this in 18:
'[,1;@j,]';#$&.'|,

Fun fact, this is technically a program that does nothing in Python.

Stax, 19 bytes
É▲²:WlÖ└%ï╪☺╒▓"We↨Φ

Run and debug it
My first Stax post, so probably not optimal.
Unpacked and commented:
U,                      Put -1 under input
  {                     Block
   i                      Push loop index, needed later
    '[a$'|++              Wrap the element in "[...|"
            m           Map
             '[+        Add another "["
                s2+     Get the latest loop index + 2
                   ']*+ Add that many "]"

Run and debug this one

Husk, 22 bytes
+:'[J"|[":msr¹₁*₁Lr
"]

Try it online!

Ruby -p, 39 bytes
Full program:
$_[$&]="|[#$2]"while/(,|\d\K(?=]))(.*)/

Try it online!
Ruby, 48 45 bytes
Recursive function:
f=->s{(s[/,|\d\K(?=])/]&&="|[")&&f[s+=?]]||s}

Try it online!

R, 84 71 69 bytes
function(x){while(x<(x=sub('(,|\\d\\K(?=]))(.+)','|[\\2]',x,,T)))1;x}

Try it online!

-15 bytes thanks to @KirillL.

71 bytes with a single substitution based on my Ruby answer.

@KirillL. : thanks, I was sure there was a shorter regex to do that, but I always mess up with lookarounds :D

-2 more, I totally forgot about a shorter \K lookbehind

Jelly, 18 bytes
ŒVḢ,ŒṘÇ”|;ƲƊ¹¡⁾[]j

Try it online!

Proton, 57 bytes
k=>"["+''.join(str(u)+"|["for u:(e=eval(k)))+-~len(e)*"]"

Try it online!

Jelly, 19 bytes
ŒV©;€⁾|[”[;µ®L‘”]ẋṭ

Try it online!
A non-recursive alternative to Erik's solution.

Jelly, 18 bytes
ŒVµ⁾[]jj⁾|[ṫ3;”]ṁ$

A full program printing the result (as a monadic link it accepts a list of characters but returns a list of characters and integers).
Try it online!
How?
ŒVµ⁾[]jj⁾|[ṫ3;”]ṁ$ - Main link: list of characters  e.g. "[10,333]"
ŒV                 - evaluate as Python code              [10,333]
  µ                - start a new monadic chain, call that X
   ⁾[]             - list of characters                   ['[',']']
      j            - join with X                          ['[',10,333,']']
        ⁾|[        - list of characters                   ['|','[']
       j           - join                                 ['[','|','[',10,'|','[',333,'|','[',']']
           ṫ3      - tail from index three                ['[',10,'|','[',333,'|','[',']']
                 $ - last two links as a monad (f(X)):
              ”]   -   character                          ']'
                ṁ  -   mould like X                       [']',']'] (here 2 because X is 2 long)
             ;     - concatenate                          ['[',10,'|','[',333,'|','[',']',']',']']
                   - implicit (and smashing) print        [10|[333|[]]]

Standard ML, 71 bytes
fun p[_]="]|[]]"|p(#","::r)="|["^p r^"]"|p(d::r)=str d^p r;p o explode;

Try it online! Uses the format without spaces. E.g. it "[10,333,4]" yields "[10|[333|[4]|[]]]]".
ungolfed
fun p [_]       = "]|[]]"          (* if there is only one char left we are at the end *)
  | p (#","::r) = "|[" ^ p r ^ "]" (* a ',' in the input is replaced by "|[" and an closing "]" is added to the end *)
  | p (d::r)    = str d ^ p r      (* all other chars (the digits and the initial '[') are converted to a string and concatenated to recursive result *)

val f = p o explode  (* convert string into list of chars and apply function p *)

Try it online!

Java 10, 107 bytes
s->{var r="[]";for(var i:s.replaceAll("[\\[\\]]","").split(","))r="["+i+"|"+r+"]";return s.length()<3?s:r;}

Try it online.
Explanation:
s->{                       // Method with String as both parameter and return-type
  var r="[]";              //  Result-String, starting at "[]"
  for(var i:s.replaceAll("[\\[\\]]","")
                           //  Removing trailing "[" and leading "]"
             .split(","))  //  Loop over the items
    r="["+i+"|"+r+"]";     //   Create the result-String `r`
  return s.length()<3?     //  If the input was "[]"
          s                //   Return the input as result
         :                 //  Else:
          r;}              //   Return `r` as result

R, 140 136 bytes
Down 4 bytes as per Giuseppe's sound advice.

function(l,x=unlist(strsplit(substr(l,2,nchar(l)-1),", ")))paste(c("[",paste0(c(x,"]"),collapse=" | ["),rep("]",length(x))),collapse="")

Try it online!

substr is shorter and the first paste0 can be paste to get this to 136 bytes.

Using eval, parse, and sub instead of unlist, strsplit and substr, I also only managed 136 bytes (I thought it might be shorter but it wasn't)

@Giuseppe Thanks for the -4 bytes! I wish we had something shorter. Recursive solution maybe?

R, 108 bytes
function(l)Reduce(function(x,y)paste0("[",x,"|",y,"]"),eval(parse(t=sub("]",")",sub("\\[","c(",l)))),"[]",T)

Try it online!
It took almost a year to find a better R solution than previous...should have known Reduce would be the answer! Outputs without spaces, input can be with or without spaces.

102 using strsplit instead of eval+parse

Python 2, 63 bytes
lambda s:'['+'|['.join(map(str,eval(s))+[']'])+']'*len(eval(s))

Try it online!

sed + -E, 46 bytes
:
s/\[([0-9]+)(, ?([^]]*)|())\]/[\1 | [\3]]/
t

A fairly straightforward approach. The second line takes [\d+, ...] and changes it to [\d | [...]]. The third line jumps back to the first line, if the substitution was successful. The substitution repeats until it fails and then the program terminates. Run with sed -E -f filename.sed, passing input via stdin.

Red, 110 bytes
func[s][if s ="[]"[return s]replace append/dup replace/all b: copy s",""|[""]"(length? b)- length? s"]""|[]]"]

Try it online!
Explanation of the ungolfed version:
f: func[s][
    if s = "[]" [return s]                    ; if the list is empty, return it
    b: copy s                                 ; save a copy of the input in b
    replace/all b "," "|["                    ; replace every "," with "|["
    append/dup b "]" (length? b) - length? s  ; append as many "]" as there were ","
    replace b "]" "|[]]"                      ; replace the first "]" with "|[]]"
]                                             ; the last value is returned implicitly

Red is so easily readable, that I doubt I needed adding the above comments :)

Perl 6, 38 bytes
{'['~S:g/\s|.<($/\|\[/~']'x$_+1}o&EVAL

Try it online!


text:
Perl - convert ASCII art to use x operator
I would like to convert ASCII art to something that takes less bytes. I have string like this:
my $string = '                ██   ████   █';

And I would convert this to something like this:
print "█" x 1."█" x 1."█" x 1"█" x 1"█" x 1;

So I would write this in one line and convert to using x operator. How can achieve this?

Welcome to PPCG! I have added the code-golf tag since questions here require a winning criteria. Generally questions here allow any language to compete (you can always say you are keen to see Perl solutions), so I'd suggest that (an alternative would be to fit this to the tips category but I think it fits better as a normal golf question). EDIT: I see Shaggy also added tips now - let's see where we go :)

Don't you mean print " " x 16."█" x 2." " x 3."█" x 4." " x 3."█" x 1;?

@JonathanAllan even if it was intended as a challenge, it's horribly underspecified.

@StephenLeppik I don't think it was and agree. It could probably be made into one though!

@JonathanAllan Isn't it just asking for run-length encoding?

@Adám uh, probably.

XY problem? How can you be sure that RLE is the shortest way?

This was first posted on StackOverflow


text:
Drag Race Countdown
Challenge:
In a hypothetical scenario, the countdown timer for a race has random intervals between the counts, to prevent premature starting, e.g.
3 (0.82 seconds pass), 2 (0.67 seconds pass), 1

Input:
nothing

Output:
Write a program (or function) that prints the 3 numbers with a random time interval from 0.50 seconds to 1 second between each count.

Note:

The program must output each number (3 , 2 , 1) with the random (any number between 0.50 and 1 to the hundredths; no hard-coding) time interval between each. The precision of the random interval must go out to the hundreds (e.g: 0.52). You are not required to output the interval, only the count.
As @JoKing clarified, I mean uniformly random (you can use the pseudo-random generator of your language.
As many people have clarified, I really mean any 2-decimal number between 0.5 and 1. (0.50, 0.51, etc, all the way to 0.98, 0.99, 1)

This is code-golf, so the program with the lowest byte count wins.

Hi LordColus, and welcome to PPCG!  This seems like a good first challenge.  For future challenges, we recommend going through the sandbox first to iron out all the details.

As I said in a previous comment that has been deleted, specifying "uniformly random" is fine if you are not too stringent with precision. As it stands now, the pause times must be uniform with precision of two decimals (or is it at least two decimals?). Does that mean the distribution should be uniform on the set 0.5, 0.51, 0.52, ..., 1, or can it be any floating point (possibly with more than two decimals) beween 0.5 and 1?

I mean that it can be any 2-digit decimal between 0.5 and 1

Does my most recent edit clear it up?

@LordColus I believe so. I voted to reopen already, so I cannot do it again.

@mbomb007 Same... why did this get closed again? It's basically count from 3 to 1 with two .50-1.00 second waits in between. It's really not complicated.

05AB1E, 12 bytes
3LRε=₄D;ŸΩ.W

Try it online!

3LR          # Push [3,2,1]
   ε         # For each...
    =        # Print it.
     ₄       # Push 1000.
      D      # Duplicate top (1000).
       ;     # Divided by 2 (500).
        Ÿ    # Range from b to a ([1000 .. 500]).
         Ω   # Random pick.
          .W # Wait X ms.

Try it with debug enabled: Try it online!

SmileBASIC, 64 62 bytes
?3M?2M?1DEF M
M=MILLISEC
WHILE MILLISEC<M+500+RND(501)WEND
END

Unfortunately I can't use WAIT since that only supports intervals of 1/60 of a second (anything less isn't normally useful since input/output only update once per frame)
This requires adjustment depending on the speed of the system it's running on, so it might not be valid (46 bytes):
?3M?2M?1DEF M
FOR I=-66E4-RND(66E4)TO.NEXT
END

Invalid WAIT version (36 bytes):
?3WAIT 30+RND(30)?2WAIT 30+RND(30)?1

R, 46 44 bytes
for an actual countdown:
for(i in 3:1){cat(i)
Sys.sleep(runif(1,.5))}

Try it online!
printing interval as I initially misunderstood the challenge (46 bytes)
Thanks Giuseppe for saving 2 chars.

for(i in 3:1)cat(i,format(runif(1,.5),,2)," ")

Try it online!

I believe runif() by default has the left and right endpoints as 0 and 1 respectively, so runif(1,.5) should work the same for -2 bytes in both.

Good catch thanks @Giuseppe.

Python 2, 58 bytes
from time import*
for a in'321':print a;sleep(1-time()%.5)

Try it online!
I created a very simple random number generator that takes the seed time (as many people do).

Improvements

From 63 to 58 bytes by Jonathan Allan
MagicOctopus Urn suggested swapping sleep and count down.

1-time()%.5 should do the trick. (You need [3,2,1] by the way)

Also for a in'321' saves another two

@JonathanAllan Very good point, updated.

This sleeps once before the countdown too. I think you need the print statement before the sleep.

@MagicOctopusUrn Agreed, updated.

JavaScript (Node.js), 75 65 60 bytes

thanks to @Shaggy for reducing by 10 bytes
thanks to @Kevin Cruijssen for reducing by 5 bytes

f=(i=3)=>i&&setTimeout(f,Math.random()*500+500,i-1,alert(i))

Try it online!

55 bytes

@Shaggy will it really be random if you're using Date ? (for the second time the random occured)

Why *1000%500+500? You can just use *500+500.

With the updates to the spec, it probably won't be random enough but it might be worth asking for clarification.

Python 3, 122 bytes
import random as r,time
def w():time.sleep(abs(r.random()-.5)+.5)
print(3,end="");w();print(", 2",end="");w();print(", 1")

Try it online!

You need the imports

On scoring imported functions

Whoops! It's been fixed.

APL+WIN, 37 bytes
3⋄r←⎕dl ↑n←.49+.01×2?51⋄2⋄r←⎕dl 1↓n⋄1

Perl 5, 39 bytes
Gradually tweaked down to 39 bytes, thanks to @jonathan-allan + @xcali.
say-$_+select$a,$a,$a,1-rand.5for-3..-1

Try it online!

would 1-rand(.5) work?

Good idea.  Can then use 1-rand.5 too.

Cut four more bytes by removing the parens and changing the counter to be negative.  Try it online!

Java 8, 86 bytes
v->{for(int i=0;++i<4;Thread.sleep((int)(Math.random()*500+500)))System.out.print(i);}

Prints without delimiter. If that is not allowed it's +2 bytes by changing print to println (new-line delimiter).
Try it online.
Prove the intervals are in the correct range of [500, 1000) ms.
Explanation:
v->{                        // Method with empty unused parameter and no return-type
  for(int i=0;++i<4;        //  Loop in range [1,4)
      Thread.sleep((int)(Math.random()*500+500)))
                            //    After every iteration: sleep for [500, 1000) ms randomly
     System.out.print(i);}  //   Print the current number

Chip -wingjj, 33 bytes
0123456e7f s
???????p*9S!ZZZtaABb

Try it online!
In Chip, we cannot wait for exactly 1/100 of a second, but we can wait for 1/256 of a second, so we use that here.
p, when asked, will pause execution for the stack head (one byte) * 1/256 seconds. On each cycle, we always set the high bit of the stack (128/256) and set all other stack bits randomly (with the ?'s). This gives an even distribution between 0.50 and 1.00 seconds.
Some of the args, -w and -gjj, specify that the input, instead of using stdin, should be a countdown from 0xFF to 0x00 (then wrapping). We use this to provide the low two bits for counting down. All other output bits remain constant (at the value corresponding to ASCII 0).
Finally, once we are done, we terminate the program with t, preventing a pause after the last number.

Jelly, 21 18 bytes
3RṚðṄṛ50r³÷³XœS@ð/

Try it online!
-3 bytes from xigoi.
Explanation
from caird coinheringaahing.
3RṚðṄṛ50r³÷³XœS@ð/ - Main link. Takes no arguments on the left
3R                 - Generate the range [1, 2, 3]
  Ṛ                - Reverse it
   ð            ð  - Define a dyadic chain f(a, b):
    Ṅ              -   Print a
     ṛ             -   Replace a with b
      50r³         -   Yield a range [50, 51, ..., 100]
          ÷³       -   Divide each by 100; Yields [0.5, 0.51, ..., 1]
            X      -   Take a random element t
             œS@   -   Sleep for t seconds then return b
                 / - Reduce the range by the dyadic chain.
                     Remember, f(a, b) = b (with some side effects), so this runs:
                     f(f(3, 2), 1) = f(2, 1) = 1, printing a each time (3, 2, 1)

18 bytes: 3RṚðṄṛ50r³÷³XœS@ð/ (also fixes the problem that your program can't generate 0.5)

@xigoi That's a brilliant use of /, ṛ and œS!

Pyth, 12 bytes
V_S3N.d-1O.5

Try it online!

Python 3 translation:
V_S3         | for N in range(1, 4)[::-1]:
    N        |     print(N)
     .d-1O.5 |     time.sleep(1 - random.uniform(0, 0.5))

Nim, 70 bytes
import os,random
randomize()
for i in[3,2,1]:echo i;sleep 500.rand+500

Try it online!

[GAWK], 57 bytes
BEGIN{while(a++<2){print 4-a;sleep(rand()/2+0.5)}print 1}

Try it online!