text:
Output the Military Order
In almost every row nowadays, the people tends to order themselves as militaries would do.
Challenge
Suppose 4 people where:

person 1 has priority against person 2, 3 and 4,
person 2 has priority against person 3 and 4,
person 3 has priority against person 4,
person 4 has the lowest priority.

Then, when ordering those 1...4 people in a row, the possibilities are:
1
2
3
4
1 2
1 3
1 4
2 3
2 4
3 4
1 2 3
1 2 4
1 3 4
2 3 4
1 2 3 4

Your mission is:
Given as input the number N of people. Output all the possibilities for 1...N people in the military order.
Since this is code-golf, then the shotest answer in bytes wins!

Input can be integer or string, followed by optional newline/whitespace, or an argument to your function. You can assume 1<=N<=10.
The output should be every sequence in a row, in any order. For each row, output a list/array or any other valid way for the numbers in military order.

Just so you know, this is extremely trivial in many languages, Pyth for example has a builtin that does almost exactly this. These are just the subsets of [1..N] in sorted order.

So the lists themselves have to be sorted, but can the list of lists be in any order?

@MartinBüttner. Yes, the order of the list is of your choice. I will update explaining

Five answers and no upvotes? Come on!

Please don't downvote challenges just because some languages have built-ins for them.

What military are you familiar with? My superiors would have been livid at the suggestion that the left is the higher priority seat/position.

@Geobits I interpreted it as being front-to-back, with the front being the left of the list.

@Mego I assumed left-right because row. I guess your interpretation could work, but eww :P

Very closely related. I think one of them should be closed as a dupe of the other.

Pyth, 14 9 4 bytes
tySQ

Try it here!
Thanks @FryAmTheEggman for showing me the y function :)

@FryAmTheEggman I knew that function was somewhere but I didn't bother looking through the docs for it...

Haskell, 41 bytes
f 0=[[]]
f n=[id,(++[n])]<*>f(n-1)
tail.f

Could you explain this?

[f, g] <*> [X, Y, Z] is [f X, f Y, f Z, g X, g Y, g Z] in Haskell. To form all subsequences of [1..n], I take all subsequences of [1..n-1], twice, and append [n] to each element of the second copy.

Cool .................. +1

Japt, 5 bytes
(Yes, this is me, ETHproductions.)
1òU à

Test it online! (This version has a few extra bytes to pretty-print the output.)
How it works
      // Implicit: U = input integer
1òU   // Generate the inclusive range [1..U].
à     // Generate all combinations of this range.
      // Implicit: output last expression

Jelly, 4 bytes
RŒPḊ

Basically the same thing as Pyth. Range, ŒPower set, Ḋequeue. Try it here!

I had come up with the same thing, but was rather surprised that Jelly had 2 byte operators, I thought I had made a mistake typing it so I didn't post. Oh well :P Do you know if Jelly is actually out of 1 byte operations?

Nope, it isn't, yet! But Dennis is still running into features more important to have around than power set... ^^

ŒP (or rather, the function iterable it uses) had a stupid bug. ŒPḊ should have worked without the R (and does now).

Haskell, 38 bytes
f n=init$filter(>0)<$>mapM(:[0])[1..n]

The function (:[0]) takes x to [x,0]. Doing mapM of this onto [1..n] takes the Cartesian product of [[1,0],[2,0],...,[n,0]], giving each subset of [1..n] with missing elements replaced by 0.
*Main> mapM(:[0])[1..3]
[[1,2,3],[1,2,0],[1,0,3],[1,0,0],[0,2,3],[0,2,0],[0,0,3],[0,0,0]]

Finally, zeroes are filtered out from each list and the empty list at the end is removed.

+1, I forgot mapM is in Prelude!

You have me beat, 39 chars: f n=[[z|z<-[x..y]]|x<-[1..n],y<-[x..n]]

@recursion.ninja That only gives continuous sub-lists, not all subsequences. It doesn't give [1,3].

Mathematica, 20 bytes
Rest@*Subsets@*Range

Composes an unnamed function that takes an integer and returns a list of lists. We need Rest because Subsets contains the empty list.

Do we ignore byte contributions from Slot and Function tokens when scoring Mathematica codes here?

@IPoiler This uses Composition to prevent the need for a Function.

@LegionMammal978 It still does nothing in this form without at least a Prefix token.

@IPoiler like any unnamed function submission, this is an expression that evaluates to a function which can then be used exactly like a pure function written with &.

@MartinBüttner I don't see why it's valid to omit @ in the byte count when @ isn't considered part of the input format. This seems obvious when you consider other languages are including optional flags in byte counts. What then should be the scores for submissions like Foo@@ and Foo/@ which can be applied directly to input? Am I overcounting bytes on my anonymous function submissions by including the implicit Prefix?

@IPoiler Foo/@ is not a valid submission because it doesn't evaluate to a function object. You'd do Foo/@#&. I'm not sure why you'd count the @. If you define a normal, named function in a C-like language with int f(int x){...} you wouldn't count the (...) for calling it either.

@MartinBüttner I concede that by the tag defaults those wouldn't be permitted but why wouldn't you count (,), @, or any other argument delimiters of a language required to call the function? Those are just as fair of syntactical advantages of a language as things like In/Pre/Postfix notation or whitespace delimitation such as in bash. Ignoring those seems akin to discounting byte counts from flags, or even arguments which are specified only to use a certain form of a function (ex: step size can't be given for Range without specifying the initial value).

@IPoiler feel free to bring this up on meta, but that's how everyone has been counting function answers for years.

Haskell, 44 bytes
import Data.List
f x=tail$subsequences[1..x]

As so often, the import ruins the score.
tail removes the first list (which is always the empty list) of all subsequences of the list from 1 to x.

It turns out f 0=[[]];f n=[id,(++[n])]<*>f(n-1);tail.f is three bytes shorter! (Do you mind if I post that as a separate answer?)

@Lynn: no, I don't mind, please post.

GAP, 21 bytes
Combinations([1..n]);

Not really a programming accomplishment, but it also includes the empty ordering...

CJam, 18 bytes
L]ri{)1$f++}/:$1>p

Test it here.
Uses a trick I learned from Dennis once upon a time to generate the powerset.

Julia, 42 bytes
N->[collect(combinations(1:N,i))for i=1:N]

This is an anonymous function that accepts an integer and returns an array of arrays. We simply get the combinations of size i for each i from 1 to N. Because of the way combinations is implemented in Julia, the arrays are already sorted.
Example:
julia> f=N->[collect(combinations(1:N,i))for i=1:N]
(anonymous function)

julia> f(4)
4-element Array{Any,1}:
 [[1],[2],[3],[4]]
 [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
 [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
 [[1,2,3,4]]

MATL, 11 bytes
2i^q:B!"@!f

Try it online!
2i^q    % 2^n-1, where n is the input number
:       % range [1,...,2^n-1]
B       % convert to binary. Gives 2D array where each number is a row
!       % transpose
"       % for each column
  @     %   push that column
  !     %   transpose into a row
  f     %   indices of nonzero elements
        % implicit end for each
        % implicitly display stack contents

As an example, with input 3, the code 2i^q: gives the array [1 2 3 4 5 6 7]. Then B! gives the 2D array
[ 0 0 0 1 1 1 1;
  0 1 1 0 0 1 1;
  1 0 1 0 1 0 1 ]

and then the loop "@!f gives 3 in the first iteration, 2 in the second, [2 3] in the third etc.

MATLAB / Octave, 49 bytes
function f(n)
for r=1:n,disp(nchoosek(1:n,r));end

This generates the vector [1,2,...,n]. Then generates all subsets with 1 element, all subsets with 2 elements, ...,  with n elements.
Example run:
>> f(4)
     1
     2
     3
     4
     1     2
     1     3
     1     4
     2     3
     2     4
     3     4
     1     2     3
     1     2     4
     1     3     4
     2     3     4
     1     2     3     4

CJam (18 bytes)
ri)e!{_0#<$}%_&1>`

is equivalent to
ri)e!_0f#.<:$_&1>`

and very different to
ri,:)Maf+:m*:e_);`

but they're all the same length.

R, 36 bytes
function(x)sapply(1:n,combn,x=n,s=F)

combn returns all cmbinations of x taken m at a time. if x is a single integer, returns all combinations of 1:n. sapply required to vectorize over m. s=F stops the results being simplified and thus returns a list as required.

Python, 69 bytes
def f(n):print[[j+1for j in range(n)if 1&i>>j]for i in range(1,1<<n)]

The key here is that we're really just asking, in order, which bits are 1 for each number i in the set of all n-bit numbers.

JavaScript (ES7 proposed), 78 bytes
n=>[for(i of Array(2**n).keys())if(i)[for(j of Array(n).keys())if(i&1<<j)j+1]]

Based on @MegaTom's binary power set answer. Only works up to n=32.

Seriously, 11 bytes
,R;╗`╜╧i`Mi

This code is super gross. I'm disgusted at how it turned out. I really need to work on Seriously 2. Actually I'm just an idiot. Still need to work on Seriously 2, though.
Try it online!
Explanation:
,R;╗`╜╧i`Mi
,R;╗         get two copies of range(1, input+1), store one in register 0
    `   `M   map:
     ╜╧        n-length permutations of range(1, input+1)
       i       flatten list
          i  flatten list

Python 3, 92
Saved 17 bytes thanks to mathmandan.
Stupid itertools and its long function names.
from itertools import*
lambda i:[y for n in range(i)for y in combinations(range(1,i+1),n+1)]

I think len(x) is just i, isn't it? So after the import statement, how about  lambda i:[y for n in range(1,i+1)for y in combinations(range(1,i+1),n)]?  Or better, lambda i:[y for n in range(i)for y in combinations(range(1,i+1),n+1)].

Ruby, 47 bytes
->n{(r=*1..n).flat_map{|x|[*r.combination(x)]}}

->n{
(r=*1..n)         # set r to [1, 2, 3, ..., n-1, n]
.flat_map{|x|     # map and then flatten resulting array one level...
[*                # a golfy variant of .to_a
r.combination(x)  # combination as in combinatorics, conveniently already sorted
]}}

Ruby, 50 bytes
A shorter ruby solution exists, using a completely different method.
This solution uses the unique idea of looking at all the numbers from 1 to 2^n-1 and getting a list of which bits are 1, for each number.
->n{(1...2**n).map{|i|(1..n).reject{|a|i[a-1]<1}}}


text:
Locate and rotate
The task
This is a simple challenge.
Your input is a single non-empty string, containing only digits 0123456789 and hashes #.
It will contain exactly one run of digits, which encodes a nonnegative integer and may wrap around the end of the string, and at least one #.
The integer may have leading zeroes.
For example, ##44##, 013#### and 23###1 are valid inputs, while ###, 0099 and #4#4 are not.
Your task is to extract the integer n from the string, and output the string rotated n steps to the right.
Examples

The input #1## should be rotated 1 step to the right, so the correct output is ##1#.
The input #026### should be rotated 26 steps to the right, since the leading 0 is ignored. The correct output is 26####0.
The input 1####2 contains the integer 21 wrapped over the end, so it should be rotated 21 steps to the right. The correct output is ##21##.

Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
You can assume that the number n fits into the standard int type of your language.
Conversely, if that standard int type implements arbitrary-precision integers, you must support (in theory) an arbitrarily large n.
Test cases
#1## -> ##1#
##4## -> #4###
1####1 -> ####11
1####2 -> ##21##
#026### -> 26####0
#000### -> #000###
###82399 -> ##82399#
51379#97 -> #9751379
#98##### -> ###98###
#######4## -> #4########
60752#1183 -> 8360752#11
####99366800## -> 366800######99
########9##### -> ###9##########
91#####515694837 -> 1#####5156948379
###6114558###### -> #6114558########
######219088736090042#### -> 9088736090042##########21
#46055080150577874656291186550000138168########### -> 0138168############4605508015057787465629118655000
568375993099127531613012513406622393034741346840434468680494753262730615610086255892915828812820699971764142551702608639695081452206500085233149468399533981039485419872101852######################3680 -> 99533981039485419872101852######################36805683759930991275316130125134066223930347413468404344686804947532627306156100862558929158288128206999717641425517026086396950814522065000852331494683

Do we have to support all test cases? Some of those numbers are pretty big... Would using a language with 8-bit integers be acceptable?

@Dennis It's possible to solve the challenge with modular arithmetic without actually loading the integer into memory... but you're right, it's a hassle in many languages. Let's say you only need to handle those test cases where n fits into the native int type of your language (which may be arbitrary-precision). I'll update the challenge text later.

What should we do if input=1234?

@CatsAreFluffy "and at least one #"

CJam, 11 bytes
q_'#%W%sim>

Try it online! or verify all test cases.
Note that this won't work for the last two test cases, since the involved numbers don't fit into 64 bits.
How it works
q_          e# Read all input and push it twice.
  '#%       e# Split at runs of '#'.
     W%     e# Reverse the resulting array.
       si   e# Cast to string, then to int.
         m> e# Rotate the original input that many places to the right.

Oooh... so simple!

Julia, 71 65 bytes
s->join(circshift([s...],maximum(parse,split(s*s,"#",keep=1<0))))

This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.
We append the input to itself, split it into an array with # as the separator, parse each integer, and take the maximum. This defines the number of times we shift the string to the right. We splat the string into a Char array, shift, and join it back together.

Python, 66 bytes
lambda l:(2*l)[-int(''.join(l.split('#')[::-1]))%len(l):][:len(l)]

Retina, 65 57 49

(\d*)#*(\d+)
$2$1 $0
^\d+
$*
+`1 (.*)(.)
 $2$1
<space>

Saved 8 bytes thanks to Martin!
Try it Online!
Note that this will time out / run out of memory for the very large test cases online, and on most sane machines, for some of the larger ones.
This takes the last number in the string and the first or no number in the string and puts them in front of the string. Then it converts that combined number to unary and repeatedly rotates while dropping a unary digit.

Jelly, 12 10 bytes
ẋ2~ṣ0‘ḌṂṙ@

Try it online! or verify all test cases.
Background
Say the input is 51379#97.
By repeating the string twice (51379#9751379#97), we can make sure that it will contain a contiguous representation of the number.
Next, we apply bitwise NOT to all characters. This attempts to cast to int, so '1' gets evaluated to 1, then mapped to ~1 = -2. On failure (#), it returns 0.
For our example, this gives
[-6, -2, -4, -8, -10, 0, -10, -8, -6, -2, -4, -8, -10, 0, -10, -8]

Next, we split at zeroes to separate the part that encodes the number from the rest.
[[-6, -2, -4, -8, -10], [-10, -8, -6, -2, -4, -8, -10], [-10, -8]]

Bitwise NOT maps n to -n - 1, so we increment each to obtain -n.
[[-5, -1, -3, -7, -9], [-9, -7, -5, -1, -3, -7, -9], [-9, -7]]

Next, we convert each list from base 10 to integer.
[-51379, -9751379, -97]

The lowest number is the negative of the one we're searching for. Since Jelly list rotation atom ṙ rotates to the left, this avoid multiplying by -1 to rotate to the right.
How it works
ẋ2~ṣ0‘ḌṂṙ@  Main link. Input: S (string)

ẋ2          Repeat the string twice.
  ~         Apply bitwise NOT to all characters.
            This maps 'n' to ~n = -(n+1) and '# to 0.
   ṣ0       Split at occurrences of zeroes.
     ‘      Increment all single-digit numbers.
      Ḍ     Convert each list from base 10 to integer.
       Ṃ    Take the minimum.
        ṙ@  Rotate S that many places to the left.

MATL, 28 25 17 16 bytes
!G1Y4XXPZcXvUYS!

8 bytes less borrowing Dennis' idea of splitting the array and reversing the order of the pieces
The two last test cases don't work because the number is too large.
EDIT (May 20, 2016) The code in the link uses Xz instead of Xv, owing to recent changes in the language.
Try it online!
!         % take implicit input: string. Transpose into column char array
G         % push input string again
1Y4       % predefined literal '\d' (for regexp)
XX        % match regexp. Gives cell array with 1 or 2 strings
P         % flip that array
ZcXv      % join the strings in that array, without spaces
U         % convert to number
YS        % rotate the transposed input that many times
!         % put back into row form (string). Implicitly display

PowerShell, 153 bytes
(But see the Extra Credit section, below)
param($a)$d=[System.collections.arraylist][char[]]$a;for($b=+("$a$a"-split"#"-ne'')[1];$b;$b--){$r=$d[-1];$d.removeAt($d.Count-1);$d.insert(0,$r)}-join$d

PowerShell doesn't have the concept of "shifting" an array, so I had to roll my own solution. Will take a long time for larger numbers, but it should eventually complete anything that fits in a 32-bit int.
Takes input $a, and sets a new variable $d as a [System.Collections.ArrayList] object. This is done because, technically, arrays in PowerShell are immutable (further explained below in Extra Credit), and thus don't support arbitrary insertions or removals, which is needed for shifting. Then, we enter a for loop.
The initial condition is a trick I found -- if we concatenate the input together, split on #, and ignore empties, the second element of the resulting array will be equal to our number, regardless of wrapping. We set that to $b, and decrement $b each time until it's zero.
Each iteration, we set helper $r as the last element in the arraylist, remove that last element, and then insert the element onto the front ... effectively "shifting" the array to the right by one element.
Finally, we simply output with -join$d so that it's concatenated into one string.

Extra Credit
If the problem was shifting the array left instead of right, we can do it significantly shorter using multiple assignment. Basically, "If the assignment value contains more elements than variables, all the remaining values are assigned to the last variable."
In essence, this means something like $c=@(1,2,3) and $a,$b=$c
will have $a=1 an int and $b=@(2,3) an array.
PowerShell, 90 bytes, does a left shift instead of a right shift
param($a)$b=+("$a$a"-split"#"-ne'')[1];$a=[char[]]$a;for(;$b;$b--){$r,$a=$a;$a+=$r}-join$a

Here we once again take input, and set $b as above. We re-cast $a as a char-array, and then enter the same for loop as above. This time, though, we've not needed to support arbitrary removal/insertion, so we don't need to use the costly [System.Collections.ArrayList] object, nor the expensive method calls. Instead we simply set $r to be the first element of $a, and the remaining elements are re-saved in $a. Then we += to tack it back on to the end.
(As I said, PowerShell arrays are technically immutable, but the += operator here is overloaded - it takes an array and another object, mushes them together (technical term) into a new array, returns that and saves it as the variable name, and destroys the original array. Functionally, we've just added an element to the end of the array, but technically (and from a memory/garbage-cleanup perspective, etc.) it's a brand-new array. This can obviously become a costly operation if the array is large or complex. The flipside is that, since arrays are immutable, indexing into them or iterating over them is very cheap.)
Output remains the same action, with a -join statement to turn it into a single string.

Pyth, 22 14 bytes
.>zs-.<zxz\#\#

Try it here!
Explanation

.>zs-.<zxz\#\#    # z=input

     .<z          # rotate z left by
        xz\#      # index of the first occurence of a hash
                  # this ensures that the integer is not wrapped around the end
    -       \#    # filter all hashes out
   s              # cast to an integer, also removes leading zeroes
.>z               # do the final roation of the input string and print it

This works for all testcases and also almosts finishes instantly for the very big numbers.

You can do -...\# instead of h:..."\d+"1. Also, no need to convert z into a list of chars, .> works also on a string.

@Jakube Thanks for the hint, was pretty tired when I did this. ^^

Seriously, 21 bytes
,;;+'#@s`≈`MM@#@`/`nΣ

Try it online!
Warning: this solution is very inefficient, so the larger test cases will time out on TIO. Use the local interpreter.
Explanation:
,;;+'#@s`≈`MM@#@`/`nΣ
,;;+                   make 3 copies of input, and concatenate two of them
    '#@s               split on #s
        `≈`MM          convert strings to ints, take maximum
             @#@       explode final copy of input
                `/`n   rotate to the right n times
                    Σ  join

Concat and take maximum: great idea!

@LuisMendo I was amused to see Alex's answer pop up with the same strategy while I was writing up the explanation here.

Looks like the only one that initially used the naïve approach was me :-) (rotating the initial string until all digits were contiguous)

JavaScript (ES6), 67 64 bytes
s=>(l=s.length,s+s).substr(l-s.split(/#+/).reverse().join``%l,l)

Another port of Dennis's CJam answer.
Edit: Saved 3 bytes by appropriating the part of edc65's answer that he didn't draw attention to.

Using a ternary and a sum instead of reverse().join(), you should beat my score

@Downgoat Sorry, I've got them mostly right lately but I did this one late at night and so I wasn't thinking straight.

@edc65 No, that made my score higher. So I copied the s+s trick instead. (I actually thought about that last night but I was too tired to try it out at the time.)

Mathematica, 69 Bytes
#~StringRotateRight~ToExpression[""<>Reverse@TextCases[#,"Number"]]&

Find sequences of numbers in the, if there are 2 then their order needs to be reversed. Concatenate the strings (if it's only one it just returns the number string). Convert string to numeric and rotate the string that number of times.

FromDigits works instead of ToExpression.

JavaScript (ES6) 66
For once, the stupid negative % of javascript for negative numbers come useful
z=>(z+z).substr(-(l=z.length,[a,b]=z.match(/\d+/g),b?b+a:a)%l-l,l)

@WashingtonGuedes no, the sum in b+a is a string concatenation. a='32',b='1', (b?b+a:a)=='132', (b|0+a)==33

Pyth, 10 bytes
.>zss_cz\#

Try it online. Test suite.
This is a translation of Dennis' CJam answer. I'm making it a community wiki, since I didn't come up with it.
Explanation
      cz\#   split input at #
     _       reverse
    s        join
   s         cast to integer
.>z          rotate input right

Perl 5, 41 bytes
39 bytes plus two for the -lF flags (-M5.01 is free): perl -lF -M5.01 script.pl
/#+/;map{unshift@F,pop@F}1..$'.$`;say@F

Explanation:

-lF reads the input, removes the trailing newline, puts the remainder into the string $_, splits it up into characters, and puts that split into the array @F.
/#+/ finds the first string of #s in $_ and sets $` equal to the stuff before it and $' equal to the stuff after it. If $` is empty then $' may contain more #s. However, $'.$` is a string whose initial substring is the number of times to rotate the array.
Now we build the list 1..$'.$`, which treats $'.$` as an integer and thus numifies it, which strips any final #s, so the list is from 1 to the number of times to rotate the array.
For each element in that list, we rotate the array (pop the last element and unshift it onto the beginning).
Then say all the elements of the rotated array.

Ruby - 68 72 70 bytes
s=ARGV[0]
p s.split(//).rotate(-(s+s).scan(/\d+/).map(&:to_i).max)*""

split converts string into an array
(s+s).scan(/\d+/) concatenate string to itself and get an array of numbers (as strings)
map(&:to_i) convert strings to ints
max pick the largest int
rotate max times
*"" convert the array back into a string (shorthand for join)

Usage : ruby scriptname.rb "[string]"

i'm new here. what's the etiquette on posting multiple answers in different languages? I added a separate answer in case one was wrong. if it's not ok to add multiple answers, let me know and i'll take it down

Multiple answers in different languages is fine, even encouraged (provided that they are all correct).

05AB1E, 14 13 bytes
Well, the code is very unlikely to terminate for the numbers bigger than 100000, but if you're patient enough, there will be an output :). Code:
'#¡rJ¹sF¤rS\J

Explanation:
'#¡             # Split the input on '#'
   r            # Reverse the stack
    J           # Join the stack
     ¹          # Take the first input
      s         # Swap with the number
       F        # For N in range(0, number), do...
        ¤       #   Obtain the last character
         r      #   Reverse the stack
          S     #   Split everything to individual characters
           \    #   Delete the last character
            J   #   Join the stack

Try it online!
Uses CP-1252 encoding

Mathematica, 73 58 bytes
#~StringRotateRight~Max[FromDigits/@StringSplit[#<>#,"#"]]&

Much byte.
15 bytes saved thanks to IPoiler

StringRotateRight saves some bytes here.

VBSCRIPT,   82  99 BYTES
previous code didn't handle cases with number wrapped over the end
b=len(a):f=replace(a,"#","/",1,1):c=replace(split(f&f,"/")(1),"#",d) mod b:d=right(a,c)&left(a,b-c)

UNGOLFED
b=len(a)                                 -a->implicit input, get its length
f=replace(a,"#","/",1,1)  -replace first instance of # so we can split later
c=replace(split(f&f,"/")(1),"#",d) mod b    -get the number and calc the mod
d=right(a,c)&left(a,b-c)                    -d->implicit output

this kinda sucks ... there's probably a better way to do it, even in VBscript

Welcome to Programming Puzzles and Code Golf Stack Exchange. This answer could be improved by adding a code breakdown and explanation below your golfed code. Also, could you save bytes by creating a function instead of a program, where a is the function input, and it returns the output? That way, you wouldn't need the inputbox and msgbox calls.

Why do you need b?

matlab(86)72
 @(n)circshift(n,[0 str2num(circshift(n(n~='#'),[0,-find(n=='#',1)+1]))])

The function totates the string two times, once for integer extraction, second for the desired task, it doesnt take too much time because matlab proceeds to rotate by (Dim)modulus(Length) to the exception that it falls in segmentation failure for bigger ranges.
Will struggle how to golf it more ....

(86)
  @(n)circshift(n,[0 str2num([strtok(n(find(n=='#',1,'last'):end),'#') strtok(n,'#')])])

The difference between this function and the previous, this one does concatenate two distant occurences of integers way backwards, while the first one just rotates it.

Matlab(73)
  @(a)regexprep(a,'(\d*)#*(\d*)#*','${circshift($0,[0 str2num([$2 $1])])}')

This is using another approach that i wonder if @luis used it, because refering to his description there is some points in common while (un)?fortunately i dont understand the cropped Matl language.

source: Stack Exchange

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

sort: votes


text:
Tips for golfing in Rust
While Rust is very, very rarely competitive in code golfing competitions (Java is often shorter), it can still be fun to golf in. What are some tricks for making Rust code shorter?
Please post only one tip in each answer.

Use closures instead of functions
A closure:
|n|n+1

is shorter than a function:
fn f(n:i32)->i32{n+1}

Closures longer than one statement need braces but are still far shorter than a function.

Converting &str to String
Never do these:
s.to_string()  // 13 bytes
s.to_owned()   // 12 bytes

This is always shorter:
s.repeat(1)    // 11 bytes

If s is a string literal:
format!(s)     // 10 bytes

For example: use format!("") instead of String::new() to save 2 bytes.
If type inference works:
s.into()       // 8 bytes

Avoid .iter().enumerate()
Let's say you have some x that implements the IntoIterator Trait and you need to call a function f that takes the index of an element and a reference to it.
The standard way of doing this is
x.iter().enumerate().map(f)

instead you can do
(0..).zip(x).map(f)

and save yourself not only the unusually long enumerate but also the call to iter!

Now I want to do this in regular Rust code.

Unfortunately enumerate produces shorter assembly. https://godbolt.org/z/hnee1GK34 But zip is better in every other way. It doesn't require the index to be usize.

it appears that they produce the same assembly starting with rust 1.60

If you need many mutable variables, it can waste a lot of space declaring them and initializing them, since each requires the mut keyword and you can't do anything like a=b=c=0. A solution then is to declare a mutable array
let mut a=[0;5];

You spend 3 extra bytes each time you use them vs. a normal variable:
a[0]+=1;

but it can often still be worth it.
Using tuples for the same trick is often an even better option:
let mut t=(1,4,"this", 0.5, 'c');

This has the advantage of saving a byte on each use vs. the array:
t.0=2

It also lets them be of different types. On the downside, it requires more characters to initialize.

Use @ to define multiple variables to the same value
@ is meant to define an alias for pattern matching (like destructuring an array but also getting the original array at the same time). But it works with plain variables too.
let a=2;let b=2; // 16 bytes
let(a,b)=(2,2);  // 15 bytes
let a@b=2;       // 10 bytes

It works in destructuring too:
let a=1;let b=1;let c=2;let d=2; // 32 bytes
let(a,b,c,d)=(1,1,2,2);          // 23 bytes
let(a@b,c@d)=(1,2);              // 19 bytes

If they need to be mutable (otherwise, what's the point), both variables need the mut keyword, e.g. let mut a@mut b=1;

When using string formatting for example with print!(), one can use both numbered and unnumbered formatters to save one byte per item to format:
Best shown with an example:
fn main() {
    print!(
        "{}{}{}. Yes, {0}{}{2}. All you other{1}{2}s are just imitating.",
        "I'm", " Slim", " Shady", " the real",
    );
}

Which outputs:

I'm Slim Shady. Yes, I'm the real Shady. All you other Slim Shadys are just imitating.

So the unnumbered formatters will get assigned to the items in order, this allows you to skip the index on them. Note that you can only use one unnumbered formatter per item to format, after that it will get used up.

Skipping trailing semicolons
In functions returning (), where the last expression is also of type (), you don't need the trailing ;:
fn main(){print!("Hello, world!")}

Replace all filter_map with flat_map
It works because:

filter_map takes a FnMut(Self::Item) -> Option<B>
flat_map takes a FnMut(Self::Item) -> impl IntoIterator
Option implements IntoIterator, which will return an
iterator with one item for Some and empty iterator for None

When working with strings with newlines in them, you save one byte if you use a literal line break in the source code vs having a \n in the string and/or using println.
print!("Hello
World!
");

is 2 bytes less than:
println!("Hello\nWorld!");

Save another byte by using print with literal line break instead of println

Do-while loops
Rust does not have a C-style do-while loop:
do{do_work();}while(condition);

But blocks are also expressions in Rust, so you can write:
while{do_work();condition}{}

Reading lines
After considering various things, I think that is generally the shortest way to retrieve a line. The line has a newline, it can be removed by trimming (.trim()) or if that cannot be done by slicing.
let y=&mut"".into();std::io::stdin().read_line(y);

For multiple lines, lines iterator can be used, the iterated line doesn't end in newline then. A glob import is needed to import BufRead, needed for lines to be available for StdinLock<'_> type.
use std::io::*;let y=stdin();y.lock().lines()

When using whole number floating point numbers, you can omit the trailing .0 to save one byte.
let a=1.

is 1 byte less than:
let a=1.0

When using FP numbers that have an integer part of 0, you can omit the leading zero as well; .0, .5 are both valid

Use ..=
Replace all ..i+1 with ..=i to save 1 byte, works on both array index a[i..=i] and range (0..=n)

clippy actually has a warning for this

The reverse is better for numbers

Use closure parameter to define variable instead of let
{let(a,b)=(A,B);X}

can be replaced by
(|a,b|X)(A,B)

to save 5 bytes if the type of a and b can be inferred, it usually works when they are integers or are passed to another function directly in X.
This works well on 2 or more variables, but for a single variable, this could still save 2 bytes if it allows you to get rid of the {}.

Declare multiple variables using pattern matching
(Somewhat of an extension of https://codegolf.stackexchange.com/a/99124/97519)
Using multiple let statements:
let a=x;let b=y;
let a=x;let b=y;let c=z;

Using a tuple match saves 1 char for 2 variables and 3 more chars for ever variable after:
let(a,b)=(x,y);
let(a,b,c)=(x,y,z);

Similarly, you can use array patterns for initializing multiple mutable variables to the same value (this works with immutable variables too but is pretty useless):
let[mut a,mut b]=[x;2];

Why is the immutable version useless?

@AdHocGarfHunter why would you want to initialize two immutable variables to the same value?

Prefer todo! over panic!
todo! is shorter than panic! by 1 byte, so prefer to use it if you need to panic and exit the program. It's also shorter than print! by a byte, so it can shorten your program if you can output to stderr instead of stdout.
todo!("optional message for stderr")

Use the ? operator to unwrap infallible results. ? is used for error propagation in conjunction with the result and option types, and per this meta post returning them with infallible results is a standard output method. For example, the following code summing the value of a string when interpreted in base a and b, with ?:
|s,a,b|Ok(i32::from_str_radix(s,a)?+i32::from_str_radix(s,b)?)

and without:
|s,a,b|i32::from_str_radix(s,a).unwrap()+i32::from_str_radix(s,b).unwrap()

As you can see, with ? it is much shorter, and it works with options as well, although often for smaller gains.

The unwrap in this example is inside a map, usually filter_map is used in this case, but for code golf, just use flat_map instead: |n|n.to_string().chars().flat_map(|c|c.to_digit(10)).sum(), see my answer for why flat_map works

@JayXon you're right, I have a better example up now.

if let can sometimes be shorter than match
Using match:
match a{M(v)=>expr,_=>other}

Using if let costs 2 bytes if there are only 2 branches and 1 is wildcard:
if let M(v)=a{expr}else{other}

More effective when your match needed {} anyways, like if the types don't match. For example:
match a{M(v)=>{expr;}_=>{other;}}

vs.:
if let M(v)=a{expr;}else{other;}

saves 1 byte.

Loops are sometimes shorter than iterators
Even with the extra curly braces, in some cases it can be shorter to declare a mutable variable and use a loop instead of using Iterator methods.
For example, to do something with every third element of a slice and then return the last index:
|n:&[_]|{let mut i=0;while i<n.len(){println!("{}",n[i]);i+=3}i-3}

|n:&[_]|(0..=n.len()/3).map(|i|{println!("{}",n[i*3]);i*3}).last().unwrap()

Using any(|x|f(x)>()) is generally shorter than using last() though you are correct loops can sometimes be even shorter

(0..).scan can be shorter than std::iter::successors
If you want to make endless sequences that are based on previous state:
std::iter::successors(Some(a),|x,_|Some(/*something*/))

This will be shorter by a character:
(0..).scan(a,|x,_|{let y=*x;*x=/*something*/;Some(y)})

If you don't mind dropping the first case, it can be even shorter:
(0..).scan(a,|x,_|{*x=/*something*/;Some(*x)})

Get the nth element of a String or &str slice
In rust you can't directly index a string or slice. If you want to build a string from indexes of another string you would typically do this:
s.chars().nth(n).unwrap() // char
s.bytes().nth(n).unwrap() // u8

Shorter is this, but it will depend s so won't work if s is generated from a expression:
s.as_bytes()[n]as char // char, supports only single byte characters
s.as_bytes()[n] // u8

However, if you are ok with a &str (like if you want to collect into a String or concatenate with a existing String). This also supports only single byte characters.
&s[n..][..1] // &str
&s[n..=n] // &str, if `n` is a single variable or sufficiently short expression

If your expression is a literal you can use byte string instead to index it directly:
b"hello world"[n] // u8
b"hello world"[n]as char // char

&s[n..][..1] and &s[n..n+1] have the same "supports only single byte characters" caveat; slicing strings at non-char boundaries leads to a panic. Still a great tip if that holds though!

s.as_bytes() does not consume s, s.into_bytes() does.
also no space needed between ] and as, and &s[n..=n] saves one

scan and fold on Iterators can be used for stateful iteration
If your closure consists of variable declarations and iterating over something while keeping an internal state, you might be able to save some bytes by using scan or fold instead of a for loop:
|i:&str|{let(mut a,mut b,mut c)=(1,2,0);for x in i.chars(){/*AAA*/;/*BBB*/;c=/*CCC*/}c}

scan is good for handling many mutable variables, at the cost of some operations (such as assignment) requiring dereferencing with * and needing to collect the final value using a method like last:
|i:&str|i.chars().scan((1,2),|(a,b),x|{/*AAA*/;/*BBB*/;Some(/*CCC*/)}).last()

fold can also be used in a similar manner by passing values in the accumulator:
|i:&str|i.chars().fold((1,2,3),|(a,b,c),x|(/*AAA*/,/*BBB*/,/*CCC*/)).2

Using slice patterns to get both an array and variables with the same value
It is a common trick to use array slicing to compactly assign many variables to the same value:
let[a,b,c]=[0;3]
// vs
let(a,b,c)=(0,0,0)
// or
let a=0;let b=0;let c=0;

I've never really seen this used on arrays, even though it also saves bytes there:
let[a,..@b]=[0;99]; // store "the rest" of the slice in b
// vs
let(a,b)=(0,[0;98]);
// or
let a=0;let b=[0;98];

Saves just one byte so may not be worth it if it increases the array size by one byte.
It works for mutable variables too:
let[mut v,mut u@..]=[0;99];
// vs
let(mut u,mut v)=(0,[0;98]);

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

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


text:
Generate lazy microwave input
Related: Program my microwave oven and Generate lazy values.
My colleague is so lazy that he doesn't even bother to move his finger when programming the microwave oven. (This is actually true!)
Help him find the microwave input that gives the time closest to what he wants, but where all digits are the same. If two inputs result in the same time difference from the desired time, choose the one with fewer digits. If both have the same number of digits, choose the lesser – so he doesn't have to wait so long.
Input is the integer that a perfectionist would enter, e.g. 430 is 4 minutes and 30 seconds while 100 and 60 each is 1 minute. It will be greater than 0 and will not exceed 9999.
Output must an integer, e.g. 444 is 4 minutes and 44 seconds and 55 is 55 seconds.
Both input and output may only be in simple seconds (no minutes) if the total time is below 1 minute and 40 seconds.
This is code-golf, so your code must be as short as possible.
Test cases:
  30 →   33
  60 →   55
  70 →  111
  90 →   88
 100 →   55
 101 →   66
 120 →   77
 130 →   88
 200 →   99
 201 →  222
 500 →  444
 700 →  666
1000 →  888
1055 →  999
1056 → 1111
1090 → 1111

I like the half-lazy approach. Just keep mashing the "add 30 sec" button until it's there :D

@Geobits  Awful lot of presses until 11:30. Anyway, the fact is that he uses the method I wrote above... :-D

Yea, I usually just type it in for anything over a few minutes. It's a delicate tradeoff between number of presses and finger-travelling distance ;)

Is input/output in # of seconds allowed?

My colleague is so lazy that he doesn't even bother to move his finger when programming the microwave oven. Didn't expect any less from someone working at Dyalog APL headquarters... :)

Jelly, 26 bytes
bȷ2ḅ60
³ÇạÇ,
9Rẋ€4R¤ḌFÇ€ṂṪ

Explanation:
bȷ2ḅ60             f(x) = x tobase 100 frombase 60
³ÇạÇ,              g(x) = (abs(f(arg) - f(x)), x)
9Rẋ€4R¤            main(arg) = [1..9] repeat each with [1..4],
       ḌF           then get digits and flatten,
         Ç€         then map g,
           Ṃ        then minimum,
            Ṫ       then last element.

Try it online!

JavaScript (ES6), 112 bytes
n=>{c=n=>n*3+n%100*2;d=n=c(n);for(r=i=0;i<1e4;i++)/^(.)\1*$/.test(i)&(m=c(i)-n,m<0?m=-m:m)<d&&(d=m,r=i);return r}

Uses a helper function c which calculates five times the actual number of elapsed seconds.

Dyalog APL, 37 bytes
{⍵⊃⍨⊃⍋⊃|-/(60⊥0 100∘⊤)¨⎕⍵}⍎¨,⎕D∘./⍨⍳4

⍳4 1 2 3 4
⎕D "0123456789"
∘./⍨ repetition table (like a multiplication table, but where each cell contains B repetitions of A instead of A×B)
, make table into list of strings
⍎¨ make each string into number (Now we have a list off all possible results.)
{…} function where the argument is represented by ⍵
⎕⍵ precede argument with prompted input
(…)¨ apply to each of the two (the argument and the list)...
0 100∘⊤ convert to base-100
60⊥ convert from base-60
-/ calculate the difference between the two
| absolute value
⊃ extract list (because -/ encapsulated its result)
⍋ sort order (Does not sort, only returns the order in which to place the arguments to achieve ascending order. If two elements are equal, they stay in current order. Since our list has elements of increasing length, this takes care of ties.)
⊃ the first one, i.e. the one with smallest absolute difference from the input
⍵⊃⍨ take that element from the argument list (the list of possible results)
Thanks to the colleague in question for shaving off one byte.

Note: I did not have any solution at the time of posting the OP.


text:
Generate lazy values
Related: Program my microwave oven. Inspired by Generate lazy microwave input.
The lazy value of the non-negative integer N is the smallest of the integers that are closest to N while all their digits are identical.
Return (by any means) the lazy value of a given (by any means) N.
N ≤ the largest integer that your language represents in non-exponent form by default. 1000000 (A lot of interesting solutions are lost because of this too-high requirement.)
Test cases:
   0 →    0
   8 →    8
   9 →    9
  10 →    9
  16 →   11
  17 →   22
  27 →   22
  28 →   33
 100 →   99
 105 →   99
 106 →  111
 610 →  555
 611 →  666
7221 → 6666
7222 → 7777

The colleague in question proved that there will be no ties: Except for 9/11, 99/111, etc. for which one is shorter than the other, two consecutive valid answers are always an odd distance apart, so no integer can be exactly equidistant from them.

JavaScript (ES6), 31 bytes
n=>~-(n*9+4).toPrecision(1)/9|0

Directly computes the lazy value for each n.
Edit: Only works up to 277777778 due to the limitations of JavaScript's integer type. Alternative versions:
n=>((n*9+4).toPrecision(1)-1)/9>>>0

35 bytes, works up to 16666666667.
n=>((n=(n*9+4).toPrecision(1))-n[0])/9

38 bytes, works up to 944444444444443. But that's still some way short of 253 which is 9007199254740992.

@user81655 I've added some alternative versions with their numeric limitations.

I couldn't get this algorithm to work with Number.MAX_SAFE_INTEGER either because 8e16 - 1 is expressed as 8e16. Sadly, it looks like the only way would be hard-coding the maximum result. +1 nonetheless.

@user81655 I lowered the upper bound to allow the solution.

Got you to 10k @Neil, love the golfs!

@NiCkNewman Woohoo! Thanks!

Could you explain this for those of us unfamiliar with Javascript?

@ngenisis Because lazy values are of the form k*((10^n)-1)/9, multiplying the original number by 9 should give you a number near to k10^n. Adding 4 and calling toPrecision achieves the necessary rounding. It then remains to regenerate the lazy value given k10^n.

Jelly, 16 bytes
ḤRµDIASµÐḟµạ³ỤḢị

Try it online!
How it works
ḤRµDIASµÐḟµạ³ỤḢị  Main link. Input: n

Ḥ                 Compute 2n.
 R                Yield [1, ..., 2n] or [0].
  µ               Begin a new, monadic chain. Argument: R (range)
   D              Convert to base 10.
    I             Compute all differences of consecutive decimal digits.
     A            Take the absolute values of the differences.
      S           Sum the absolute values.
       µÐḟ        Filter-false by the chain to the left.
          µ       Begin a new, monadic chain. Argument: L (lazy integers)
           ạ³     Take the absolute difference of each lazy integer and n (input).
             Ụ    Grade up; sort the indices of L by the absolute differences.
                  This is stable, so ties are broken by earlier occurrence and,
                  therefore, lower value.
              Ḣ   Head; retrieve the first index, corresponding to the lowest
                  absolute difference.
               ị  Retrieve the item of L at that index.

Oracle SQL 11.2, 200 bytes
WITH v(i)AS(SELECT 0 FROM DUAL UNION ALL SELECT DECODE(SIGN(i),0,-1,-1,-i,-i-1)FROM v WHERE LENGTH(REGEXP_REPLACE(:1+i,'([0-9])\1+','\1'))>1)SELECT:1+MIN(i)KEEP(DENSE_RANK LAST ORDER BY rownum)FROM v;

Un-golfed
WITH v(i) AS
(
  SELECT 0 FROM DUAL      -- Starts with 0
  UNION ALL
  SELECT DECODE(SIGN(i),0,-1,-1,-i,-i-1) -- Increments i, alternating between negatives and positives
  FROM   v
  WHERE  LENGTH(REGEXP_REPLACE(:1+i,'([0-9])\1+','\1'))>1  -- Stop when the numbers is composed of only one digit
)
SELECT :1+MIN(i)KEEP(DENSE_RANK LAST ORDER BY rownum) FROM v;

Pyth - 26 bytes
This answer doesn't always return the smallest value in a tie, but that isn't in the specs, so awaiting clarification fixed for 3 bytes.
hSh.g.a-kQsmsM*RdjkUTtBl`Q

Test Suite.

MATL, 25 bytes
2*:"@Vt!=?@]]N$vtG-|4#X<)

Uses brute force, so it may take a while for large numbers.
Try it online!
2*:       % range [1,2,...,2*N], where is input
"         % for each number in that range
  @V      %   push that number, convert to string
  t!=     %   test all pair-wise combinations of digits for equality
  ?       %   if they are all equal
    @     %     push number: it's a valid candidate
  ]       %   end if
]         % end for each
N$v       % column array of all stack contents, that is, all candidate numbers
t         % duplicate
G-|       % absolute difference of each candidate with respect to input
4#X<      % arg min
)         % index into candidate array to obtain the minimizer. Implicitly display

Pyth, 16 bytes
haDQsM*M*`MTSl`Q

Try it online: Demonstration or Test Suite
Explanation:
haDQsM*M*`MTSl`Q   implicit: Q = input number
              `Q   convert Q to a string
             l     take the length
            S      create the list [1, 2, ..., len(str(Q))]
         `MT       create the list ["0", "1", "2", "3", ..., "9"]
        *          create every combination of these two lists:
                   [[1, "0"], [1, "1"], [1, "2"], ..., [len(str(Q)), "9"]]
      *M           repeat the second char of each pair according to the number:
                   ["0", "1", "2", ..., "9...9"]
    sM             convert each string to a number [0, 1, 2, ..., 9...9]
  D                order these numbers by:
 a Q                  their absolute difference with Q
h                  print the first one

Perl, 32
Based on the beautiful JavaScript solution by Neil.
$_=0|1/9*~-sprintf"%.e",$_*9+4.1

Starts to fail at 5e15

Mathematica, 122 bytes
f@x_:=Last@Sort[Flatten@Table[y*z,{y,1,9},{z,{FromDigits@Table[1,10~Log~x+1-Log[10,1055555]~Mod~1]}}],Abs[x-#]>Abs[x-#2]&]

Function named x.

JavaScript (ES6), 59 bytes
n=>eval(`for(i=a=0;i<=n;a=i%10?a:++i)p=i,i+=a;n-p>i-n?i:p`)

Recursive Solution (56 bytes)
This is a bit shorter but does not work for n > 1111111110 because the maximum call stack size is exceeded, so it is technically invalid.
f=(n,p,a,i=0)=>ni-n?i:p:f(n,i,(i-=~a)%10?a:i++,i)

Explanation
Iterates through every lazy number until it gets to the first which is greater than n, then compares n to this and the previous number to determine the result.

var solution =

n=>
  eval(`           // eval enables for loop without {} or return
    for(
      i=a=0;       // initialise i and a to 0
      i<=n;        // loop until i > n, '<=' saves having to declare p above
      a=i%10?a:++i // a = amount to increment i each iteration, if i % 10 == 0 (eg.
    )              //     99 + 11 = 110), increment i and set a to i (both become 111)
      p=i,         // set p before incrementing i
      i+=a;        // add the increment amount to i
    n-p>i-n?i:p    // return the closer value of i or p
  `)
N = <input type="number" oninput="R.textContent=solution(+this.value)">

I lowered the upper bound to allow your solution.

Japt, 18 bytes
9*U+4 rApUs l¹/9|0

Try it online!
Based on Neil's technique
Non-competing solution:
*9+4 h /9|0

And now you can do *9+4 h /9|0 :-)

@ETHproductions Thanks! I'm having a lot of fun with Japt :)

05AB1E, 20 bytes
9Ývy7L×})˜ïD¹-ÄWQÏ{¬

Try it online!
9Ý                   # Push 0..9
  vy7L×})˜           # For each digit, 0-9, push 1-7 copies of that number.
          ïD         # Convert to integers, dupe the list.
            ¹        # Push original input (n).
             -Ä      # Push absolute differences.
               WQ    # Get min, push 1 for min indices.
                 Ï{¬ # Push indices from original array that are the min, sort, take first.

99 is surely more lazy than 111, as it only requires two button presses.

@Adám fair enough, added head command.

Mathematica, 56 bytes
Min@Nearest[##&@@@Table[d(10^n-1)/9,{n,0,6},{d,0,9}],#]&

Pure function with first argument #, works for inputs up to 10^6.
For a nonnegative integer n and a digit d, 10^n-1 = 99...9 (9 repeated n times), so d(10^n-1)/9 = dd...d (d repeated n times). Creates a Table of values for 0 <= n <= 6 and 0 <= d <= 9, then flattens the table, finds the list of elements Nearest to # and takes the Min.
I believe this version will work for arbitrarily large integers:
Min@Nearest[##&@@@Table[d(10^n-1)/9,{n,0,IntegerLength@#},{d,0,9}],#]&


text:
Golf the xᵗʰ root of x
While bored in high-school (when I was half my current age...), I found that \$f(x) = x^{x^{-1}}\$ had some interesting properties, including e.g. that the maximum \$f\$ for \$0 ≤ x\$ is \$f(e)\$, and that the binding energy per nucleon of an isotope can be approximated as \$6 × f(x ÷ 21)\$...
Anyway, write the shortest function or program that calculates the xth root of x for any number in your language's domain.
Examples cases
For all languages
     -1   >       -1
   ¯0.2   >    -3125
   ¯0.5   >        4
    0.5   >     0.25
      1   >        1
      2   >    1.414
      e   >    1.444
      3   >    1.442
    100   >    1.047
  10000   >    1.001

For languages that handle complex numbers
   -2   >        -0.7071i
    i   >            4.81
   2i   >    2.063-0.745i
 1+2i   >   1.820-0.1834i
 2+2i   >   1.575-0.1003i

For languages that handle infinities
-1/∞   >   0    (or ∞ or ̃∞)
   0   >   0    (or 1 or ∞)
 1/∞   >   0
   ∞   >   1
  -∞   >   1

For languages that handle both infinities and complex numbers
 -∞-2i   >   1      (or ̃∞)

 ̃∞ denotes directed infinity.

Here is a Wolfram Alpha plot for positive real x. If you omit the x limits in the query, Wolfram Alpha will include negative values of x where the function value depends on a choice of "branch" for the complex logarithm (or for a similar complex function).

What about for languages that do not handle power of decimals?

@KennyLau Feel free to post with a note that says so, especially if the algorithm would work, had the language supported it.

TI-BASIC, 3 bytes
Ans×√Ans

TI-BASIC uses tokens, so Ans and ×√ are both one byte.
Explanation
Ans is the easiest way to give input; it is the result of the last expression. ×√ is a function for the x'th root of x, so for example 5×√32 is 2.

As far as I am aware ans would count as hardcoding inputs into variables and does not seem to be an accepted input method for [tag:code-golf]. In that case, please make a full program or a function.

@flawr I can see what you're saying but it seems it's always been done like this. Maybe it warrants a meta post?

Ans is STDIN/STDOUT for TI-Basic.

stdin and stdout are text streams, usually for interactive text input and output. Ans is not interactive, unlike some other functions in TI-BASIC, which are interactive.

@Timtech Certainly not. There are functions like Input and Prompt.

You can vote on the validity of Ans on meta.

What I meant is that Ans is the only way for functions to take input and return output without messing with the global variables (technically Ans is global, but I'm referring to the A, B, etc.)

Question: Are there more than 256 tokens? If so, your byte count is invalid.

@CatsAreFluffy Yes, but they are two bytes. There are 256 (actually a little less) one-byte tokens.

@flawr The reason Ans is usually accepted is because its value is set by any expression (expressions are separated by :). Therefore something like 1337:prgmXTHROOT would input 1337, which looks a lot like input via CLAs in a normal language.

@CatsAreFluffy http://tibasicdev.wikidot.com/tokens

Jelly, 2 bytes
*İ

Try it online!
How it works
*İ    Main link. Input: n

 İ    Inverse; yield 1÷n.
*     Power (fork); compute n ** (1÷n).

Jelly doesn't have a stack. A dyad follow by a monad in a monadic chain behaves like APL's forks.

No, J's ^% is a hook (which do not exist in Dyalog APL), not a fork. Jelly and APL code is difficult to compare since Jelly is left-to-right. The nearest equivalent would be ÷*⊢ (also a fork), which computes (1/x)**x because of the different direction. Since Jelly's atoms aren't overloaded (they are either monadic or dyadic, but never both), there can be monadic 1,2,1- and 2,1-forks.

Thanks for the clarification. Naturally, I'm quite intrigued by Jelly (which I still think should be named ȷ or something similar.)

Javascript (ES2016), 11 bytes
x=>x**(1/x)

I rarely ever use ES7 over ES6.

x=>x**x**-1 also works, again for 11 bytes.

All hail the new exponentiation operator!

Python 3, 17 bytes
lambda x:x**(1/x)

Self-explanatory

I quite like lambda x:x**x**-1, but it's not shorter.

@Seeq Your expression is the same length, but it has the advantage of working in both Python 2 and 3.

Python 2's shortest is lambda x:x**x**-1, so it is the same in 2 and 3.

I couldn't find this answer for ages and was really annoyed when I did.

J, 2 bytes
^%

Try it online!.
How it works
^%  Monadic verb. Argument: y

 %  Inverse; yield 1÷y.
^   Power (hook); compute y ** (1÷y).

I was gonna write this answer. I'm too slow at this.

@Bijan Over a year too slow, it seems. :P

I see, I've only been golfing for a week now.

Haskell, 12 11 bytes
Thanks @LambdaFairy for doing some magic:
(**)<*>(1/)

My old version:
\x->x**(1/x)

(**)<*>(1/) is 11 bytes.

@LambdaFairy Thanks! Do you mind explaining? It looks like you are doing some magic with partially applied functions but as I am quite new to Haskell I do not really understand how this works=)

This uses the fact that a 1-argument function can be considered an applicative functor (the "reader monad"). The <*> operator takes an applicative that produces a function, and an applicative that produces a value, and applies the function to the value. So in this case, a mind-bending way to apply a 2-argument function to a 1-argument function.

The function <*> takes 3 arguments, two functions f and g and an argument x. It is defined as (<*>) f g x = f x (g x), i.e. it applies f to x and g x. Here it's partially applied to f and g leaving out x, where f = (**) and g = (1/) (another partially applied function (a section) that calculates the reciprocal value of it's argument). So ( (**)<*>(1/) ) x is (**) x ((1/) x) or written in infix: x ** ((1/) x) and with the section resolved: x ** (1/x). -- Note: <*> is used in function context here and behaves differently in other contexts.

@nimi So it's the equivalent of the S combinator i.e. S(**)(1/)?

@Neil: yes.

Pyth, 3 bytes
@QQ

Trivial challenge, trivial solution...
(noncompeting, 1 byte)
@

This uses the implicit input feature present in a version of Pyth that postdates this challenge.

Does this solution predate the feature of implicit input?

@KennyLau Yes, by a long time. But I've edited the one-byte solution in anyway.

JavaScript ES6, 18 bytes
n=>Math.pow(n,1/n)

Java 8, 18 bytes
n->Math.pow(n,1/n)

Java isn't in last place?!?!
Test with the following:
import java.lang.Math;

public class Main {
  public static void main (String[] args) {
    Test test = n->Math.pow(n,1/n);
    System.out.println(test.xthRoot(6.0));
  }
}

interface Test {
  double xthRoot(double x);
}

It's the fact that it's a function

Mathematica, 8 7 4 7 bytes
#^#^-1&

More builtin-only answers, and now even shorter! Nope.
By definition, the next answer should be 13 bytes. (Fibonacci!) The pattern is still broken. :(

#^#^-1& saves 1 byte.

NOW it is golfed.

NOW it is golfed.

When Mthmtca is released, we are going to rule this board.

Hmm...time to look through my answers and make a compressed version of every builtin...

Surely just Surd isn't valid as it requires two arguments?

Oh...reverting.

R, 19 17 bytes
function(x)x^x^-1

-2 bytes thanks to @Flounderer

Why not x^(1/x) ? Edit: x^x^-1 seems to work too.

That's a snippet, and apparently people don't like snippets.

@CatsAreFluffy it is the definition of a function.

MATL, 5 bytes
t-1^^

Try it online!
t       % implicit input x, duplicate
 -1     % push -1
   ^    % power (raise x to -1): gives 1/x
    ^   % power (raise x to 1/x). Implicit display

Java, 41 bytes
float f(float n){return Math.pow(n,1/n);}

Not exactly competitive because Java, but why not?

Welcome to PPCG! I think you might be missing a return type on this function.

Oops, got sloppy.  A Java 8 answer already beat this one of course...

CJam, 6 bytes
rd_W##

Try it online!
How it works
rd     e# Read a double D from STDIN and push it on the stack.
  _    e# Push a copy of D.
   W   e# Push -1.
    #  e# Compute D ** -1.
     # e# Compute D ** (D ** -1).

Perl 5, 10 bytes
9 bytes plus 1 for -p
$_**=1/$_

NARS APL, 2 bytes
√⍨

NARS supports the √ function, which gives the ⍺-th root of ⍵. Applying commute (⍨) gives a function that, when used monadically, applies its argument to both sides of the given function. Therefore √⍨ x ↔ x √ x.
Other APLs, 3 bytes
⊢*÷

This is a function train, i.e. (F G H) x ↔ (F x) G H x.  Monadic ⊢ is identity, dyadic * is power, and monadic ÷ is inverse. Therefore, ⊢*÷ is x raised to 1/x.

Ruby, 15 Bytes
a=->n{n**n**-1}

Ungolfed:
-> is the stabby lambda operator where a=->n is equivalent to a = lambda {|n|}

Python 2 - 56 bytes
The first actual answer, if I'm correct. Uses Newton's method.
n=x=input();exec"x-=(x**n-n)/(1.*n*x**-~n);"*999;print x

Functions are okay.

dc, 125 bytes
15k?ddsk1-A 5^*sw1sn0[A 5^ln+_1^+ln1+dsnlw!<y]syr1<y1lk/*sz[si1[li*li1-dsi0<p]spli0<p]so0dsw[lzlw^lwlox/+lw1+dswA 2^!<b]dsbxp

Unlike the other dc answer, this works for all real \$x\$ greater than or equal to \$1 (\$1 ≤ x$). Accurate to 4-5 places after the decimal.
I would have included a TIO link here, but for some reason this throws a segmentation fault with the version there (dc 1.3) whereas it does not with my local version (dc 1.3.95).
Explanation
As dc does not support raising numbers to non-integer exponents to calculate \$x^\frac1x\$, this takes advantage of the fact that:
$$x^\frac1x = e^\frac{\ln x}x$$
So, to calculate \$\ln(x)\$, this also takes advantage of the fact that:
$$\int \frac1x dx = \ln(x) + c$$
whose definite integral from \$1\$ to \$b = x\$ is numerically-approximated in increments of \$10^{-5}\$ using the following summation formula:
$$\int_1^b \frac1x dx = \sum_{i=1}^{10^{5}(b-1)} \frac 1 {10^5 + i}$$
The resulting sum is then multiplied by \$\frac1x\$ to get \$\frac{\ln(x)}x\$. \$e^{\frac{\ln(x)}x}\$ is then finally calculated using the \$e^x\$ Maclaurin Series to 100 terms as follows:
$$e^x=\sum^{10^2}_{n=0}\frac{x^n}{n!}$$
This results in our relatively accurate output of \$x^\frac1x\$.

+1 This has got to be one of the best dc answers out there. I'm bookmarking this!

@KritixiLithos Thank you! I appreciate the kind words. :)

This is why we love this site (sorry Jelly people).

Seriously, 5 bytes
,;ì@^

Try it online!
Explanation:
,;ì@^
,;     input, dupe
  ì@   1/x, swap
    ^  pow

, 5 chars / 7 bytes
Мű⁽ïï

Try it here (Firefox only).
Trivial.

Pyke (commit 29), 6 bytes
D1_R^^

Explanation:
D      - duplicate top
 1_    - load -1
   R   - rotate
    ^  - ^**^
     ^ - ^**^

Can haz link pls?

Oh, I thought you meant there's no implementation available. Yes, the interpreter doesn't have to be hosted, just a link to the repo / source (or docs) will suffice

Pylons, 5 bytes.
ideAe

How it works.
i # Get command line input.
d # Duplicate the top of the stack.
e # Raise the top of the stack to the power of the  second to the top element of the stack.
A # Push -1 to the stack (pre initialized variable).
e # Raise the top of the stack to the power of the second to the top element of the stack.
  # Implicitly print the stack.

Japt, 3 bytes
UqU

Test it online!
Very simple: U is the input integer, and q is the root function on numbers.

C++, 48 bytes
#include<math.h>
[](auto x){return pow(x,1./x);}

The second line defines an anonymous lambda function. It can be used by assigning it to a function pointer and calling it, or just calling it directly.
Try it online

Does ^ not work in C++ as it does in C?

@minerguy31: ^ is bitwise xor in C (and C++).

C, 23 bytes
#define p(a)pow(a,1./a)

This defines a macro function p which evaluates to the ath root of a.
Thanks to Dennis for reminding me that gcc doesn't require math.h to be included.
Thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ for reminding me that the space after the first ) is not needed.
Try it online

With GCC, you don't need to include math.h.

-1 byte: #define p(a)pow(a,1./a)

Milky Way 1.6.5, 5 bytes
'1'/h

Explanation
'      ` Push input
 1     ` Push the integer literal
  '    ` Push input
   /   ` Divide the STOS by the TOS
    h  ` Push the STOS to the power of the TOS

 x**(1/x)

Usage
$ ./mw <path-to-code> -i <input-integer>

O, 6 bytes
j.1\/^

No online link because the online IDE doesn't work (specifically, exponentiation is broken)
Explanation:
j.1\/^
j.      push two copies of input
  1\/   push 1/input (always float division)
     ^  push pow(input, 1/input)

oh hey you did it yay

C# - 18 43 41 bytes
float a(float x){return Math.Pow(x,1/x);}

-2 byes thanks to @VoteToClose
Try it out
Note:

 First actual attempt at golfing - I know I could do this better.

Welcome to the crowd! It is exactly because of newcomers that I make trivial challenges like this.

Fixed. Thanks for informing me about this

@crayzeedude No problem at all. Nice job and again, welcome to PPCG!

Does C# have float?

Indeed it does.

PARI/GP, 9 bytes
x->x^x^-1

This is shorter than the alternatives x->x^(1/x) and x->sqrtn(x,x). It uses the right-associativity of ^ and the strong binding of the unary -. GP isn't quite functional enough to curry (a,b)->sqrtn(a,b) into (x)->sqrtn(x,x); the best it can manage is x->call(sqrtn,[x,x]) which is far too long.

PHP 5.6, 32 30 29 bytes
function($x){echo$x**(1/$x);}

or
function($x){echo$x**$x**-1;}

30->29, thank you Dennis!

Awk, 8 bytes
$1^$1^-1

A shell command to check it
awk '{print $1^$1^-1}'

Longer version (+1) with
$1^(1/$1)

MATLAB, 11bytes
@(x)x^(1/x)

Creates an anonymous function. This will work with all test cases including complex numbers and infinities.
This also works with Octave. You can try online here. Simply enter something like:
f=@(x)x^(1/x)

At the command line of the online interpreter, then do:
f(-1)

To test.

C#, 25 bytes, type: double
Bare form of a lambda expression:
x=>System.Math.Pow(x,1/x)

The expression can be assigned to a function variable, e.g. (Func<double, double>), ...
System. can be omitted, if using System; is used (but more bytes).
Complete test program (143 bytes) with the input of the question:
using System;class P{static void Main(){Array.ForEach(new double[]{-.2,-.5,.5,1,2,Math.E,3,100,10000},x=>Console.WriteLine(Math.Pow(x,1/x)));}}

Result:
-3125
4
0,25
1
1,4142135623731
1,44466786100977
1,44224957030741
1,0471285480509
1,0009214583193

C#, 37 bytes, type: Complex
x=>System.Numerics.Complex.Pow(x,1/x)

Also the assembly for System.Numerics needs to be referenced.
The division operator is overloaded for complex arguments.
Test program (189 bytes) with the input of the question for complex numbers:
using System;using C=System.Numerics.Complex;class P{static void Main(){Array.ForEach(new C[]{new C(-2,0),new C(0,1),new C(0,2),new C(1,2),new C(2,2)},x=>Console.WriteLine(C.Pow(x,1/x)));}}

Result:
(4,32963728535968E-17, -0,707106781186548)
(4,81047738096535, 0)
(2,0628722350809, -0,745007062179724)
(1,81984053615444, -0,183434723804562)
(1,57500291115344, -0,100274868564155)

Test program (264 bytes) with infinity:
using System;using C=System.Numerics.Complex;class P{static void Main(){var p=double.PositiveInfinity;var n=double.NegativeInfinity;Array.ForEach(new C[]{new C(-1/p,0),new C(0,0),new C(1/p,0),new C(p,0),new C(n,0),new C(n,2) },x=>Console.WriteLine(C.Pow(x,1/x)));}}

Result:
(0, 0)
(0, 0)
(0, 0)
(1, 0)
(1, 0)
(1, 0)

Vitsy, 4 + 1 (function declaration) = 5 bytes
Hey, look, my language actually does this. Go figure.
Di^^
D    Duplicate the top item (input)
 i   Push -1.
  ^  Pop top (-1), put the second to top to the power of the popped item (x^-1)
   ^ Same as above, except we now have the desired number.
This is a function that leaves the value requested on the stack. For view-ability, I have also made the program output on the Try it Online! link.
Try it Online!

-1: Anonymous functions are allowed.

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Unfortunately, that's what I thought. However, I was informed that I would have to include the return character before the function in order for it to be valid.

Bean, 11 bytes
Hexdump:
00000000 26 4c a0 43 95 4c a5 3a 8e 20 43  &L C.L¥:. C
0000000b

Equivalent JavaScript:
A**(1/A)

Implicitly converts first line of input to number as A and implicitly outputs the result of the expression.
Try the demo here.
Try the test suite here.

Codename Dragon, 16 bytes
a=<>;dispa^(1/a)

I'm abusing the lack of a syntax error.
Ungolfed:
disp((a=<>)^(1/a))

This is a simple program that takes input through <>.
You can find an interpreter here, no github site yet.

Jolf, 5 bytes
Try it here!
^j/1j
 j    input
^ /1j to the 1/j pow.

Gnuplot, 13 bytes
f(x)=x**(1/x)

or
f(x)=x**x**-1

Brachylog, 8 7 bytes
Thanks to Fatalize for saving a byte.
^?^-1=.

Explanation
^?^-1=.
     =.   unify output with
^?^-1     input raised to the 1/input power

You can save one byte: you don't need the first ?, it is implicitely the current variable at the beginning of the predicate.

Racket, 28 22 bytes
(λ(n)(expt n(/ 1 n)))

@cat gets credit for the 6 byte save. Thanks!
Seriously, Racket is impossible to golf with :). Nothing to see here, move along!

You can do (λ(n)(expt n(/ 1 n))) as an anonymous function for 22 bytes

We need a golfing dialect of Racket, like we need a golfing dialect of Factor except people have already made LISPs for golf and the code becomes mostly parentheses.

I forgot that anonymous functions are generally okay. We definitely could use a lovely LISP for golfing. But yeah, I can only imagine the parens are still going to reduce competitiveness.

Factor, 14 10 bytes
1 over / ^

Expects input on top of the stack.

Convex, 3 bytes
Convex is a new language that I am developing that is heavily based on CJam and Golfscript. The interpreter and IDE can be found here. Input is an integer into the command line arguments. Indexes are one-based. Uses the CP-1252 encoding. This answer in non-competing as it was created after this challenge.
_¹#

Explanation:
    Implied input
_   Duplicate top of stack
 ¹  Find reciprocal
  # Power
    Implied output

Can be found... where?

@cat oops. Fixed. Note that I literally just updated the interpreter though, but this still works.

Lua, 20
n=(...)print(n^n^-1)

How it works:
n=(...)              Take input and store at n
       print(
             n^n^-1  n^(n^(-1))
                   )

Quetzalcoatl, 4 bytes
c.I?

Explanation:
c    # Input
 .   # Duplicate
  I  # Inverse
   ? # Power

So... "Quetzalcoatl" can have an operator which finds x^x^-1...

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ What operator are you referring to?

Like Python's a**a**-1.

dc, 8 6 chars
Outputs to the top of the stack:
?d1r/^

Or if I can expect the input at the top of the stack, this 5 char solution works too:
d1r/^

Explanation:
?        take input from STDIN and execute it (numbers are executed by pushing to the stack)
 d1r     duplicate top of stack, push 1 and swap them
    /^   divide and exponentiate

Alas, dc does not allow for fractional exponents so this answer does not actually work for any given inputs above 1, and gives the wrong answer for 0 < input < 1. It does the same thing as many of the other programs though.

Python 3: 34
n=complex(input());print(n**(1/n))

Unless I'm missing something this would do nicely. I like that Python normally uses spaces, but this solution doesn't need them.

Why the int(...)?

Python 3 won't implicitly take an input as an integer. So it needs to be converted for the arithmetic in the second statement. Unless it does work for this scenarios in which case my solution will be shorter

OP: for any number in your language's domain

@Adám I'm not sure that I understand that part then. I just thought it meant it would take any number in the normal base. For Python that is base 10.

If Python natively handles real numbers, then input may be a real (i.e. non-integer).

@Adám oh of course. Well in that case as all integers are floats, but not all floats are integers. I can expect a float input

Doesn't Python handle complex numbers as well?

Yeah, complex, +4 BYTES NOW!!!!!!!

@Adám The output will be different.

wow I didn't know Python could handle complex numbers. @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ what do I need to change. If I change float to complex the code no longer works?

@george If you want to handle complex (like 3+1j or 7j) numbers, simply replace float with complex. The result of complex(17) will be (17+0j), while complex(11j) results in 11j. Note that 11 is an int, while 11j and (11+2j) are both complex. You can easily replace (1+2j) with 1+2j.

Ah I did try that, but in my maths classes I use "i" as the imaginary number and I tried this and it chucked an error

@george It's not 14i, it's 14j.

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ sorry my last post was clear. I meant when I first tried using complex I got an error because I had used 14i but when you posted afterwards explains it with "j" I figured that was what it was. Thank you

05AB1E, 3 bytes
Dzm

Explanation:
D    # Duplicate the input
 z   # Inverse, 1 ÷ input
  m  # Power, calculating input ** (1 ÷ input)

Try it online!.

Wait a minute! If it couldn't parse floats, then floats were not in the domain, and so an integer solution was acceptable.

@Adám Oh, I didn't know that! The code would still be the same though :p.

Weird how -.2 still returns -3124.999999999999

And, also, I think he meant you can remove the non-competing tag.

@carusocomputing Hmm, how is that weird then?

Oh, nevermind, python does the same; I thought Python was evaluating at -3125, but it isn't.

zm works now.

TI-Basic, 4 bytes
Ans^Ansֿ ¹

Since TI-Basic is tokenized, this code is a mere four bytes.

We already have a TI-BASIC answer at 3 bytes.

Is ans accepted as input method?

QBIC, 9 bytes
:?a^(1/a)

Gets a numeric input from the command line and does the math...

Mouse-2002, 13 bytes
x:x.b/x.&ROOT

Other programs assume the number's on the top of the stack and so shall I.
x:    ~ put TOS in x
x.    ~ push x
b /   ~ divide by 1
x.    ~ push x again
&ROOT ~ y to the x root

Scala, 33 bytes
def f=(x:Double)=>Math.pow(x,1/x)

Perl, 11 bytes
Added 2 bytes for -pn.
$_**=1/$_

Try it here !

Pyth, 1 byte
@

Pyth takes implicit input, so @ is really equivalent to @QQ, where Q is the evaluated input.
Try it online!

Test suite (with complex numbers)

Mumps, 14 Bytes
R I W I**(1/I)

R reads from input into variable I, and the W (write) statement does the mathematical calculations.
I will warn you: the output will be ugly as there are no implied newlines in Mumps, and at least the way I read the challenge, the OP didn't require them. If you did want cleaner output, add 2 bytes and add a newline:
R I W !,I**(1/I)

SQL (MySQL), 60 bytes
CREATE FUNCTION G(X REAL) RETURNS REAL RETURN POWER(X,1./X);

Caps lock is cruise control for cool golf.

Can you do )RETURNS instead of ) RETURNS for -1 byte?

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Possibly; I don't have a MySQL server handy right now to test it, though.

Desmos, 14 bytes
a=1
\sqrt[a]{a}

Demonstration

That looks interesting. So \sqrt is a root-of function, and not square-root?

@Adám It is TeX. \sqrt is the Square Root symbol, and the brackets change the root.

tcl, 23
I post two approaches which occupy the exact same number of bytes.
puts [expr $n**(1./$n)]

—
puts [expr $n**$n**-1.]

Available to test on http://rextester.com/EMW19680

SmileBASIC, 18 bytes
INPUT X?POW(X,1/X)

Excel, 10 bytes
=A1^(1/A1)

Self explanatory.

Common Lisp, 24 bytes
(lambda(x)(expt x(/ x)))

Try it online!

Vyxal, 2 bytes
Ėe

Try it Online!
The es are coming!
 e # x to the power of
Ė  # 1/x

Julia 1.0, 9 bytes
~x=x^x^-1

Try it online!
This solution handles both complex numbers and infinities.

05AB1E, 2 bytes
zm

Try it online!
zm  # full program
    # implicit input...
 m  # to the power of...
z   # 1 divided by...
    # implicit input
    # implicit output

Thunno 2, 2 bytes
Ị*

Attempt This Online!
Ị calculates the reciprocal, and * does exponentiation.

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


text:
LaTeX Table Generator
Write a function or program which, given a number of lines and columns, generates a corresponding tabular environment for LaTeX with no data in it.
Table format and tabular Environment
Here is an example of a table with 2 rows and 4 columns:

As you can see, we do not count the first row nor do we count the first column: those are for the labels of the table.
The top left corner is also "missing", in that there is no border around it.
The corresponding LaTeX's code to generate this table is the following:
\begin{tabular}{|c|c|c|c|c|}
    \cline{2-5}
    \multicolumn{1}{c|}{} & & & & \\
    \hline
    & & & & \\
    \hline
    & & & & \\
    \hline
\end{tabular}

There are as many c in the first line as there are total columns (that is, 1 more than the number of columns given as input). These c are separated by | (and there are | on both the extreme left and extreme right too).
The first horizontal separator is generated by \cline{2-X} where X is the index of the last column (starting from 1).
The first element of the first row is always \multicolumn{1}{c|}{} (this removes the borders of the top left corner).
Each row has C &, C being the number of columns given as input. Each line ends with \\.
Each row is followed by a \hline.

Formatting details

You must indent everything between the begin{tabular}{...} and \end{tabular} tags with 4 spaces.
The &'s are separated with exactly one space on each row. The first one of the row does not have an extra space before it (since it already has 4 spaces before it). Note that this is not true for the first row, where the first & has a space before it because of the \multicolumn element.
\\ is separated from the last & by a space.
Each \hline and row description is on its own new line.

Input
Input is a couple of two integers representing the number of columns and the number of rows. Note that this is the number of columns and rows excluding the very first row and very first column.
You may assume that the row and column inputs will always be at least 1, and less than 1024.
Those two numbers can be taken whichever way is most appropriate in your language (two args, a list, etc.).
Output
The output is a string of the LaTeX code that generates a table with the appropriate number of rows and columns. This can be returned from a function or outputted to STDOUT.
A trailing new line is allowed after the \end{tabular}. Trailing spaces are not allowed at the end of any line.
Test cases
Input: (1,1)
Output:
\begin{tabular}{|c|c|}
    \cline{2-2}
    \multicolumn{1}{c|}{} & \\
    \hline
    & \\
    \hline
\end{tabular}

Input: 2 rows, 4 columns
Output:
\begin{tabular}{|c|c|c|c|c|}
    \cline{2-5}
    \multicolumn{1}{c|}{} & & & & \\
    \hline
    & & & & \\
    \hline
    & & & & \\
    \hline
\end{tabular}

Scoring
This is code-golf, so the shortest code in bytes \emph{wins}.

JavaScript (ES6), 172 170 bytes
a=>b=>`\\begin{tabular}{${'|c'[r='repeat'](++b)}|}
    \\cline{2-${b--}}
    \\multicolumn{1}{c|}{} ${('& '[r](b)+`\\\\
    \\hline
    `)[r](a+1).trim()}
\\end{tabular}`

Called as F(a)(b) (credit to Patrick Roberts for finding this method)
Would have been much messier if not for template strings. Originally came in at 200, when I had a separate repeat for the multicolumn &'s, but cut it down a good amount by combining them and using trim to get rid of the final unneeded indentation.

Python 2, 197 bytes
This solution uses string formatting to reduce repetition. Each string component is assembled, then placed within the template. It is tricky to use so many backslashes in Python strings. I used the raw string r'\\' and multi-line '''blah \n blah''' string techniques here.
def a(d,e):
 c='c|'*e;b='& '*e+r'\\';g=' '*4+b+'\n    \\hline\n';f=g*d;h='{tabular}'
 return r'''\begin%s{|c|%s}
    \cline{2-%s}
    \multicolumn{1}{c|}{} %s
    \hline
%s\end%s'''%(h,c,e+1,b,f,h)

Before the minifier, it looks like this:
def latextable(height, width):
    columns = 'c|' * width;
    linespec = '& ' * width + r'\\';
    line = ' '*4 + linespec + '\n    \\hline\n';
    block = line * height;
    mode = '{tabular}'
    return r'''\begin%s{|c|%s}
    \cline{2-%s}
    \multicolumn{1}{c|}{} %s
    \hline
%s\end%s''' % (mode, columns, width+1, linespec, block, mode)

print latextable(1, 1)
print latextable(2, 4)

The output tests:
\begin{tabular}{|c|c|}
    \cline{2-2}
    \multicolumn{1}{c|}{} & \\
    \hline
    & \\
    \hline
\end{tabular}
\begin{tabular}{|c|c|c|c|c|}
    \cline{2-5}
    \multicolumn{1}{c|}{} & & & & \\
    \hline
    & & & & \\
    \hline
    & & & & \\
    \hline
\end{tabular}

As a side note, I wrote a latex macro processor like this to format my thesis. I think I spent longer on developing that macro processor than on writing the words...

You forgot one space between the return and your raw string in your first code block.

Also you can go with g=' '*4 instead of g='    ' to save one byte.

@DenkerAffe, thanks for finding that error. My minifier has a bug!

C#, 248 byte
string t(int r,int c){string i="\r\n    ",d="",q="",m;for(int j=0;j++<c;){d+="c|";q+="& ";}q+=$"\\\\{i}\\hline";m=@"\begin{tabular}{|c|"+d+"}"+i+@"\cline{2-"+(c+1)+"}"+i+@"\multicolumn{1}{c|}{} "+q;for(;r-->0;)m+=i+q;return m+"\r\n\\end{tabular}";}

Tester:
using System;
class Table
{
    static int Main()
    {
        var x = new Table();
        Console.WriteLine(x.t(1,1));
        Console.WriteLine(x.t(2,4));
        Console.Read();
        return 0;
    }
    string t(int r,int c){string i="\r\n    ",d="",q="",m;for(int j=0;j++<c;){d+="c|";q+="& ";}q+=$"\\\\{i}\\hline";m=@"\begin{tabular}{|c|"+d+"}"+i+@"\cline{2-"+(c+1)+"}"+i+@"\multicolumn{1}{c|}{} "+q;for(;r-->0;)m+=i+q;return m+"\r\n\\end{tabular}";}

    string tab(int row, int col){
        string i="\r\n    ",sc="",sr="",msg;
        for(int j=0;j++<col;){sc+="c|";sr+="& ";}
        sr+=$"\\\\{i}\\hline";
        msg=@"\begin{tabular}{|c|"+sc+"}"+i+@"\cline{2-"+(col+1)+"}"+i+@"\multicolumn{1}{c|}{} "+sr;
        for(;row>0;)msg+=i+sr;
        return msg+"\r\n\\end{tabular}";
    }
}

I could save 4 bytes when I use "\n" instead of "\r\n" as linebreak.


text:
Find the optimal sliding door width
Sliding doors have varying prices based on the width of the doors. The different prices are as follows:

60 - 80 cm:   ¤150
81 - 100 cm:  ¤200
101 - 120 cm: ¤220

When buying a closet you would obviously want to minimize the cost, so your task is to find the width of the doors that minimizes the total cost based on the total width of the closet.
Rules:

The total width will be taken as input
All doors will have the same width
Choose the smallest doors if two type of doors cost the same
The widths are in centimeters, integers not decimals

Round up decimals

The price shall be returned as an integer (no need for the currency sign)
The input and output formats are optional, but the order of the output must be: Number of doors, Width, Price.
Input will be in the range [120 1000).

This is code golf. Shortest code in bytes win.
Examples:
Input: 156
Output: 2, 78, 300

Input: 331
Output: 3, 111, 660

Input: 420
Output: 4, 105, 880

Width of 201 is an interesting test case...

Sliding door? Clearly every door needs a @Doorknob.

05AB1E, 47 bytes
Code:
D120/ó>DU=/ó>=D101›iX220*=q}D80›iX200*=q}X150*=

Not the best submission, but at least something :)
Try it online!

Putting 333 into the TIO gives an output of [3, 112, 660] when (afaik) the output should be [3, 111, 660] since 3*111 equals 333 perfectly

Similar problem with 201 giving [2, 101, 400] instead of [2, 101, 440]

Perl, 190 180 154 133 128 117 bytes
includes +1 for -p
use POSIX;$m=1E4;for$q(80,100,120){($m,@z)=($p,$n,ceil$_/$n)if$m>($p=(150,200,220)[$x++]*($n=ceil$_/$q))}$_="@z $m"

Commented:
use POSIX;                                  # for ceil()
$m = 1E4;                                   # init min price to 10k
for $q (80,100,120) {                       # iterate widths
    ($m,@z) = ($p,$n, ceil $_/$n)           # update min, output
    if $m > (                               #
       $p = (150,200,220)[$x++]             # grab price
          * ( $n = ceil $_/$q )             # times nr of doors needed
    )
}
$_="@z $m"

Save 11 bytes by inlining and splitting hash to two arrays
Save 5 bytes by using -p (thanks to @dev-null)
Save 18 bytes by using POSIX::ceil and 3 more by using list syntax for hash (thanks to @msh210)

Shorter than sub r{$a=$_[0];~~$a==$a?$a:1+~~$a} is sub r{use POSIX;ceil pop}.

Shorter than (80=>150,100=>200,120=>220) is (80,150,100,200,120,220).

Does this work for very very wide doors (where the price is more than 10_000)?

@msh210 Thanks for the tips, I'll incorporate them! No, it only works for the range specified in the question [120-1000), but one can always change 1E4 to 1E9...

Oh, I didn't notice that the question had specified a range.

@dev-null Thanks, updated the answer. Not sure why I didn't go for -p in the first place!

JavaScript (ES6), 101 bytes
t=>[[80,150],[100,200],[120,220]].map(([w,p])=>[n=-~(~-t/w),-~(~-t/n),n*p]).sort((a,b)=>a[2]-b[2])[0]

-~(~-a/b) is the same as Math.ceil(a/b) in 31-bit integers.

PowerShell, 137 135 bytes
param($a)$j=9e9;60..120|%{if((($c=[math]::ceiling($a/$_))*($p=(220,(200,150)[$_-le80])[$_-le100]))-lt$j){$j=($k=$c)*$p;$i=$_}}
$k;$i;$j

Output is newline-separated.
We take input $a, set our cost $j to 9000000000 (a large number that's way more than we would ever need). Next, we loop from 60..120 with |%{...}. Each iteration we calculate the $p price of the current item with a pseudo-ternary statement, then calculate the $c ceiling of $a/$_. If the current total is smaller than the smallest total we've seen ($j), save all these variables: $j (the total), $k (the number of doors required), and $i (the door width), and continue the loop. Once the loop is finished, just output the best values.
Edit -- Saved two bytes by moving the $c and $p assignments into the if conditional

Pyth, 65 bytes
ho+eNcehNTm[d*hd?>81ed150?<101ed220 200)f}eTr60 121m[d.EcQd)r2 17

Try it here!
Explanation
First this generates a list of all possible door count/door width combinations and calculates the price for every of those combinations. Then we only have to order it by price and door width and take the first element of the resulting list.
Code explanation follows after I golfed this down Please help me golf this, this is way too long.

ho+eNcehNTm[d*hd?>81ed150?<101ed220 200)f}eTr60 121m[d.EcQd)r2 17  # Q=input

                                                   m        r2 17  # map range(2,17) to
                                                    [d     )       # list with door count first
                                                      .EcQd        # and width second
                                        f                          # Filter map result with T
                                         }   r60 121               # in range(60,121)
                                          eT                       # door width
          m                                                        # map filter result with d
           [d                          )                           # to a list with door count and width first
             *hd                                                   # mult door count with
                ?>81ed150?<101ed220 200                            # price per door, simple lookup with ternaries
 o                                                                 # order map result with N
  +eNcehNT                                                         # order key=price+width/10
h                                                                  # first element is the best

JavaScript (ES6) 96
n=>[80,100,120].map((d,i)=>[d=-~(~-n/d),-~(~-n/d),d*[150,200,220][i]]).sort((a,b)=>a[2]-b[2])[0]

As noted by @Neil, =-~(~-n/d) is equivalent to division with rounding up for integeres of 32 bit or less.

R, 135 104 bytes
"!"=utf8ToInt;cbind(n<-16:1,w<-ceiling(scan()/n),p<-n*approx(!"<Qex",!"–ÈÜÜ",w,"c")$y)[order(p)[1],]

Try it online!
Saved 31 bytes by

decompressing numbers
using utf8ToInt
using "!" to shorten function call
using vectorized functions
not defining total length
using cbind directly rather than after defining variables

How it works:

approx returns the price of a
single door based on its length. It returns NA outside of the
range [60,120].
Based on the spec, the total numbers of doors can't be more than 16
(total length 1000).  All number of doors from 16 to 1 are tested,
and the triplet (number of doors, door width, total price) is
returned.
The order function is used to locate the minimum price; the
correct triplet is extracted based on that. In case of ties, order
will return the entry that comes first, and since we looped from 16
to 1 the greatest numbers of doors (smallest door width) will be
returned.

Using stepfun is longer  - as one needs to remove width outside of [60,120].


text:
Block-diagonal matrix from columns
Inspired by Copied from this question at Stack Overflow.
Given a matrix A, create a matrix B such that the columns of A are arranged in a block-diagonal fashion. For example, given
1 2 3
4 5 6

the output would be
1 0 0
4 0 0
0 2 0
0 5 0
0 0 3
0 0 6

Rules
Input and output may be in the form of 2D arrays, nested arrays, or strings with different separators for rows and columns.
Numbers in the input (matrix A) will be positive integers.
Unary format is allowed, as long as zeros in the output are displayed in some reasonable way. For example, the above result could be displayed using quotation marks to enclose each number:
'1' '' ''
'1111' '' ''
'' '11' ''
'' '11111' ''
'' '' '111'
'' '' '111111'

Test cases
Input, output:
1 2 3
4 5 6

1 0 0
4 0 0
0 2 0
0 5 0
0 0 3
0 0 6

10 20

10  0
 0 20

10
20

10
20

  1   2   3
 10  20  30
100 200 300

  1   0   0
 10   0   0
100   0   0
  0   2   0
  0  20   0
  0 200   0
  0   0   3
  0   0  30
  0   0 300

 2  4
 6  8
10 12

 2  0
 6  0
10  0
 0  4
 0  8
 0 12

Will all the numbers in A be different?

@Nᴮᶻ No, they can be equal

MATL, 6 bytes
"@N$Yd

Works in current version (13.0.0) of the language/compiler.
Input has the following form, with semicolon as row separator, and commas or spaces as column separators within each row:
[1, 2, 3; 4, 5, 6]

Try it online!
Explanation
"         % implicitly input 2D array and loop over its columns
  @       %   push column
  N$Yd    %   build block-diagonal matrix from all stack contents. Stack contents are
          %   a single column in the first iteration, or a partially built 2D array
          %   and a new column in all other iterations
          % end loop
          % implicit display

Worked example
Consider the input [1 2 3; 4 5 6]. The for loop beginning with " takes each column of the input. Within each iteration, @ pushes the current column onto the stack. So in the first iteration it pushes [1; 4]. N$ specifies that all the stack contents will be used as inputs of the following function, Yd.
This function (corresponding to MATLAB's blkdiag) "diagonally concatenates" its inputs to produce a block diagonal matrix (2D array). So in the first iteration Yd it takes one input and produces an output equal to that input, [1; 4], which is left on the stack.
In the second iteration the second column of the input, [2; 5], is pushed. Now Yd takes two 2×1 inputs, namely [1; 4] and [2; 5], and produces the 4×2 array [1 0; 4 0; 0 2; 0 5].
In the third iteration Yd takes the latter 4×2 array and the third column of the input, [3; 6], and produces the final result [1 0 0; 4 0 0; 0 2 0; 0 5 0; 0 0 3; 0 0 6].

ES6, 65 bytes
a=>[].concat(...a[0].map((_,i)=>a.map(b=>b.map((c,j)=>i-j?0:c))))

Takes as input and returns as output an array of arrays.

@WashingtonGuedes The inner map returns a copy of the original 2D array with all but one column zeroed out. These copies then need to be concatenated, rather than just being elements of an outer 3D array.

Mathematica, 40 39 Bytes
Credit to @Seeq for Infixing Flatten.
Transpose[DiagonalMatrix/@#]~Flatten~1&

Input is a list of row vectors delimited by {} brackets. So the initial example is represented by
{{1,2,3},{4,5,6}}

Generate an array of DiagonalMatrix where each one has diagonal elements from the rows of the input (3-D array). Transpose so the Flatten operation removes the correct bracket pairs to give the desired matrix (now 2-D array).

Wouldn't DiagonalMatrix/@# work? And, by extension, Transpose[DiagonalMatrix/@#]~Flatten~1&

Good catch, I intended to fix that after rolling it up. Didn't think to use the Infix Flatten though. +1.

Pyth, 17
s.em.>+dm0thQkbCQ

Try it online or run the Test Suite.
You can add a leading j to help visualize the 2D array.

Ruby, 81 78 76 62 bytes
->a{i=-1;a[0].flat_map{i+=1;a.map{|b|x=b.map{0};x[i]=b[i];x}}}

sigh Manually keeping track of the index is shorter than with_index.
->a{
i=-1;            # index of the flat_map
a[0]             # duplicate all rows as many times as necessary
.flat_map{       # we're wrapping each "group" of original rows with yet another
                 #  array, so we need to flat_map to get rid of those
i+=1;            # increment the index of the current subarray
a.map{|b|        # for each sub-subarray (these are the rows)...
x=b.map{0};      # zero everything out
x[i]=b[i];       # replace the desired elements
x}}}             # finally, return the modified array

Jelly, 13 bytes
ZLR’×L0ẋ;"Zz0

Try it online!
How it works
ZLR’×L0ẋ;"Zz0  Main link. Input: M (matrix)

Z              Transpose M.
 L             Get the length of the result. This yields the number of M's columns.
  R            Range; for m columns, yield [1, ..., m].
   ’           Decrement to yield [0, ..., m-1].
    ×L         Multiply each by the length (number of rows) of M.
               This yields [0, n, ..., n(m-1)], where n is the number of rows.
      0ẋ       Push a list of lists of zeroes.
               First element is [], last is n(m-1) zeroes.
        ;"Z    Prepend the kth vector of zeroes to the kth column of M.
           z0  Zip, filling the non-rectangular 2D array with zeroes.

MATLAB, 69 68 bytes
   function h=d(a)
   [r,c]=size(a);h=repmat(a,c,1).*kron(eye(c),~~(1:r)')

One byte was shaved off: thanks to Luis Mendo :)

Mathematica, 111 bytes
Join@@@ReplacePart[Table[0,#2/#3]~Table~#3~Table~#3,Table[{n,n}->#[[n]],{n,#3}]]&[Length@#,Length@Flatten@#,#]&

What's the input syntax? This throws Table and Part errors when using standard MMA matrix notation and results in an array of mixed dimensions.

R, 41 bytes
pryr::f(Matrix::.bdiag(plyr::alply(a,2)))

Assumes pryr, Matrix and plyr packages are installed.
This creates a function that takes a 2D array (a) and returns a "sparseMatrix" where (where 0's are represented as .)
(a=matrix(1:6,ncol=3))
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    4    6
pryr::f(Matrix::.bdiag(plyr::alply(a,2)))(a)
# 6 x 3 sparse Matrix of class "dgTMatrix"
#
# [1,] 1 . .
# [2,] 2 . .
# [3,] . 3 .
# [4,] . 4 .
# [5,] . . 5
# [6,] . . 6

Explanation:
plyr::alply(a,2) each column of a and returns combines these results in a list
Matrix::.bdiag(lst) creates a block diagonal matrix from a list of matrices
pryr::f is a shorthand way to create a function.
A fully base R solution in 59 bytes (using the logic of @PieCot's Matlab answer):
function(a){l=dim(a);diag(l[2])%x%matrix(1,nrow=l[1])*c(a)}

APL (Dyalog Classic), 11 bytes
⍉⍪⍉↑(0,⊢)\⎕

Try it online!