Title: Output a Magical 8 Trapezium

Body:
Your task is to output a Magical 8 Trapezium:

```<code>        1 × 8 + 1 = 9
       12 × 8 + 2 = 98
      123 × 8 + 3 = 987
     1234 × 8 + 4 = 9876
    12345 × 8 + 5 = 98765
   123456 × 8 + 6 = 987654
  1234567 × 8 + 7 = 9876543
 12345678 × 8 + 8 = 98765432
123456789 × 8 + 9 = 987654321
</code>```

Output in your chosen language in the fewest bytes possible.

Note the number of spaces at the start of each line to maintain the trapezium shape.

Trailing spaces are allowed.

You can use × or the letter x - whichever you prefer.

Body:
golflua, 56 characters

p=""~@i=1,9p=p..i; w(S.q("%9s x 8 + %d = "..p*8+i,p,i))$

Sample run:

bash-4.3$ golflua -e 'p=""~@i=1,9p=p..i; w(S.q("%9s x 8 + %d = "..p*8+i,p,i))$'
        1 x 8 + 1 = 9
       12 x 8 + 2 = 98
      123 x 8 + 3 = 987
     1234 x 8 + 4 = 9876
    12345 x 8 + 5 = 98765
   123456 x 8 + 6 = 987654
  1234567 x 8 + 7 = 9876543
 12345678 x 8 + 8 = 98765432
123456789 x 8 + 9 = 987654321


答:
J, <s>32</s> 31 bytes

```<code>[:(*/@#~>:#:[:i.[:*/>:)&|./2&p:
</code>```

Grabs the lists of primes and exponents of the input integer, reverse each, and build up the divisors from that.

Usage

```<code>   f =: [:(*/@#~>:#:[:i.[:*/>:)&|./2&p:
   f 2
1 2
   f 72
1 2 4 8 3 6 12 24 9 18 36 72
   f 101
1 101
</code>```

Explanation

```<code>[:(*/@#~>:#:[:i.[:*/>:)&|./2&p:  Input: n
                           2&p:  Factor n as a list where the first row are the primes
                                 and the second are their exponents
[:                     &|./      Reverse each list
                    >:           Increment each exponent by 1
                [:*/             Reduce it using multiplication
            [:i.                 Construct a range from 0 to that product exclusive
        >:                       The list of each exponent incremented
          #:                     Reduce each number in the previous range as a mixed base
                                 using the incremented exponents
      #~                         For each mixed base value in that range, copy from
                                 the list of primes that many times
   */@                           Reduce the copied primes using multiplication
                                 Return this list of products as the result
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sort a number's divisors by prime factorization

Body:
Given an input of an integer \$n ≥ 2\$, output a list of its divisors sorted by the
exponents in their prime factorizations, in ascending order, ordering first by
the largest prime, then by the second largest, and so on.

As an example, take the integer \$72\$, which is \$2^3\cdot3^2\$. It has
the divisors

```<code>1     3^0 · 2^0
2     3^0 · 2^1
3     3^1 · 2^0
4     3^0 · 2^2
6     3^1 · 2^1
8     3^0 · 2^3
9     3^2 · 2^0
12    3^1 · 2^2
18    3^2 · 2^1
24    3^1 · 2^3
36    3^2 · 2^2
72    3^2 · 2^3
</code>```

When sorted in ascending order by the exponents on the prime factors, with
larger primes taking priority, this becomes

```<code>1     3^0 · 2^0
2     3^0 · 2^1
4     3^0 · 2^2
8     3^0 · 2^3
3     3^1 · 2^0
6     3^1 · 2^1
12    3^1 · 2^2
24    3^1 · 2^3
9     3^2 · 2^0
18    3^2 · 2^1
36    3^2 · 2^2
72    3^2 · 2^3
</code>```

Note that the list is sorted first by the order of the exponent of 3, and then
by the exponent of 2. You can also think of this as reading from left to right
and top to bottom across the following grid:

```<code>        2^0  2^1  2^2  2^3

3^0     1    2    4    8
3^1     3    6    12   24
3^2     9    18   36   72
</code>```

Test cases:

```<code>2 => 1 2
72 => 1 2 4 8 3 6 12 24 9 18 36 72
101 => 1 101
360 => 1 2 4 8 3 6 12 24 9 18 36 72 5 10 20 40 15 30 60 120 45 90 180 360
3780 => 1 2 4 3 6 12 9 18 36 27 54 108 5 10 20 15 30 60 45 90 180 135 270 540 7 14 28 21 42 84 63 126 252 189 378 756 35 70 140 105 210 420 315 630 1260 945 1890 3780
30030 => 1 2 3 6 5 10 15 30 7 14 21 42 35 70 105 210 11 22 33 66 55 110 165 330 77 154 231 462 385 770 1155 2310 13 26 39 78 65 130 195 390 91 182 273 546 455 910 1365 2730 143 286 429 858 715 1430 2145 4290 1001 2002 3003 6006 5005 10010 15015 30030
65536 => 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536
74088 => 1 2 4 8 3 6 12 24 9 18 36 72 27 54 108 216 7 14 28 56 21 42 84 168 63 126 252 504 189 378 756 1512 49 98 196 392 147 294 588 1176 441 882 1764 3528 1323 2646 5292 10584 343 686 1372 2744 1029 2058 4116 8232 3087 6174 12348 24696 9261 18522 37044 74088
</code>```

Since this is code-golf, the shortest code in bytes wins.

Body:
J, <s>32</s> 31 bytes

[:(*/@#~>:#:[:i.[:*/>:)&|./2&p:

Grabs the lists of primes and exponents of the input integer, reverse each, and build up the divisors from that.

Usage

   f =: [:(*/@#~>:#:[:i.[:*/>:)&|./2&p:
   f 2
1 2
   f 72
1 2 4 8 3 6 12 24 9 18 36 72
   f 101
1 101

Explanation

[:(*/@#~>:#:[:i.[:*/>:)&|./2&p:  Input: n
                           2&p:  Factor n as a list where the first row are the primes
                                 and the second are their exponents
[:                     &|./      Reverse each list
                    >:           Increment each exponent by 1
                [:*/             Reduce it using multiplication
            [:i.                 Construct a range from 0 to that product exclusive
        >:                       The list of each exponent incremented
          #:                     Reduce each number in the previous range as a mixed base
                                 using the incremented exponents
      #~                         For each mixed base value in that range, copy from
                                 the list of primes that many times
   */@                           Reduce the copied primes using multiplication
                                 Return this list of products as the result

ContentLicense: CC BY-SA 3.0


问:
Random sampling without replacement
Create a function that will output a set of distinct random numbers drawn from a range. The order of the elements in the set is unimportant (they can even be sorted), but it must be possible for the contents of the set to be different each time the function is called.

The function will receive 3 parameters in whatever order you want:

Count of numbers in output set

Lower limit (inclusive)

Upper limit (inclusive)

Assume all numbers are integers in the range 0 (inclusive) to 231 (exclusive). The output can be passed back any way you want (write to console, as an array, etc.)

Judging

Criteria includes the 3 R's

Run-time - tested on a quad-core Windows 7 machine with whatever compiler is freely or easily available (provide a link if necessary)

Robustness - does the function handle corner cases or will it fall into an infinite loop or produce invalid results - an exception or error on invalid input is valid

Randomness - it should produce random results that are not easily predictable with a random distribution. Using the built in random number generator is fine. But there should be no obvious biases or obvious predictable patterns. Needs to be better than that random number generator used by the Accounting Department in Dilbert

If it is robust and random then it comes down to run-time. Failing to be robust or random greatly hurts its standings.

答:
R, 31 or 40 bytes (depending on the meaning of the word “range”)

If the input has 3 numbers, a[1], a[2], a[3], and by “range” you mean “an integer sequence from a[2] to a[3]”, then you have this:

```<code>a=scan();sample(a[2]:a[3],a[1])
</code>```

If you have an array n from which you are about to resample, but under the restriction of the lower and upper limits, like “resample values of the given array n from the range a[1]...a[2]”, then use this:

```<code>a=scan();sample(n[n>=a[2]&n<=a[3]],a[1])
</code>```

I am quite surprised why the previous result was not golfed considering the built-in sample with replacement facilities! We create a vector that satisfies the range condition and re-sample it.

Robustness: the corner cases (sequences of the same length as the range to sample from) are handled by default.

Run-time: extremely fast because it is built in.

Randomness: the seed is automatically changed every time the RNG is invoked.

Title: Random sampling without replacement

Body:
R, 31 or 40 bytes (depending on the meaning of the word “range”)

If the input has 3 numbers, a[1], a[2], a[3], and by “range” you mean “an integer sequence from a[2] to a[3]”, then you have this:

a=scan();sample(a[2]:a[3],a[1])

If you have an array n from which you are about to resample, but under the restriction of the lower and upper limits, like “resample values of the given array n from the range a[1]...a[2]”, then use this:

a=scan();sample(n[n>=a[2]&n<=a[3]],a[1])

I am quite surprised why the previous result was not golfed considering the built-in sample with replacement facilities! We create a vector that satisfies the range condition and re-sample it.

Robustness: the corner cases (sequences of the same length as the range to sample from) are handled by default.

Run-time: extremely fast because it is built in.

Randomness: the seed is automatically changed every time the RNG is invoked.


问:
Do X without Y
Usually, it is said that "Doing X without Y" can be a trap to beginners writing challenges (source). However, I am cocky and think that I can definitely make an X without any Ys. Randomly. Oh yes, this will be good.

Challenge: Given an odd integer n greater than or equal to 1, output an ex of side length n made of random printable ascii characters sans "y" and "Y", and the space. All allowed characters must have a nonzero chance of occurring, but not necessarily uniform. This is a code-golf so the shortest code in bytes wins. You should, however, randomize each char--that is, the struts of the ex shouldn't be equal, unless if by chance.

The chars to appear

```<code>!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXZ[\]^_`abcdefghijklmnopqrstuvwxz{|}~"
</code>```

Constructing the ex

Side length 1:

```<code>x
</code>```

Side length 3:

```<code>x x
 x
x x
</code>```

Side length 5:

```<code>x   x
 x x
  x
 x x
x   x
</code>```

etc.

Example outputs

```<code>input
output
empty line

3
h 2
 ^
9 5

1
:

5
D   1
 W z
  W
 q j
W   1
</code>```

Example implementation

You do not need to handle invalid inputs.

function generate(sideLength){
    var result = "";
    var INNER = "@"
    for(var i = 0; i < sideLength; i++){
        var p = i < sideLength / 2 ? i : sideLength - i - 1;
        result += " ".repeat(p) + ((sideLength / 2 | 0) == p ? "" : INNER) + " ".repeat(Math.max(sideLength - p * 2 - 2, 0)) + INNER + "\n";
    }

    return result.replace(RegExp(INNER, "g"), function(e){
        let c = "y";
        while(c === "y" || c === "Y"){
            c = String.fromCharCode((Math.random() * 94) + 33 | 0);
        }
        return c;
    });
}

function print(v){
    output.innerHTML = "";
    output.appendChild(document.createTextNode(v));
}

function update(){
    var n = Number(input.value);
    if(n !== Math.floor(n)) print("error: " + n + " is not an integer.");
    else if(n % 2 === 0)    print("error: " + n + " is not odd.");
    else if(n < 1)          print("error: " + n + "is less than one.");
    else                    print(generate(n));
}

input.onchange = update;

update();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  font-family: Consolas, monospace;
}

#output {
  white-space: pre;
}</code>```

<input id="input" min=1 value=1 type=Number>

```

答:
Lua, 277 Bytes

Well... Lua is sooooo good at manipulating strings :D. First time I had to use local in a statement! I could save some bytes by using Lua 5.1 instead of 5.3 because they moved the global function unpack into the object table at Lua 5.2. But I prefer to stick with the latest version I have :).

Defines a function that should be called with a single parameter (the second one is used for recursion purpose) and returns a string.

function f(n,N)N=N or n e=" "p="\n"r=math.random C=e.char
R={}for i=1,4 do x=r(33,126)R[i]=x~=89 and x~=121 and x or r(33,88)end
local s,S,a,b,c,d=e:rep((N-n)/2),e:rep(n-2),table.unpack(R)return
n<2 and s..C(a)..p or s..C(a)..S..C(b)..s..p..f(n-2,N)..s..C(c)..S..C(d)..s..p
end
```

<h3>Ungolfed</h3>

<pre class="lang-lua prettyprint-override"><code>function f(n,N)
  N=N or n                          -- N is equal to the n we had on the first call
  e=" "                             -- shorthand for the space
  p="\n"                            -- shorthand for the newline
  r=math.random                     -- shorthand for math.random
  C=e.char                          -- uses the string e to obtain the function string.char
  R={}                              -- define an array for our random values
  for i=1,4                         -- iterate 4 times (for the random characters)
  do
    x=r(33,126)                     -- random between ASCII "!" and "~"
    R[i]=x~=89 and x~=121           -- if we didn't pick y or Y
           and x                    -- keep this number
         or r(33,88)                -- or roll for a character between "!" and "X"
  end
  local s,S                         -- these variables have to be local
          ,a,b,c,d                  -- or the recursion would change them
         =e:rep((N-n)/2),e:rep(n-2) -- s and S are the number of spaces for the X
           ,table.unpack(R)         -- a,b,c and d are the 4 random characters
  return n<2                        -- if n==1
           and s..C(a)..p           -- we're at the center of the X, time to end recursion
         or                         -- else
           s..C(a)..S..C(b)..s..p   -- concatenate the topmost line for n
           ..f(n-2,N)               -- with the inner X
           ..s..C(c)..S..C(d)..s..p -- and the bottom line
end
</code>```

Title: Do X without Y

Body:
Lua, 277 Bytes

Well... Lua is sooooo good at manipulating strings :D. First time I had to use local in a statement! I could save some bytes by using Lua 5.1 instead of 5.3 because they moved the global function unpack into the object table at Lua 5.2. But I prefer to stick with the latest version I have :).

Defines a function that should be called with a single parameter (the second one is used for recursion purpose) and returns a string.

function f(n,N)N=N or n e=" "p="\n"r=math.random C=e.char
R={}for i=1,4 do x=r(33,126)R[i]=x~=89 and x~=121 and x or r(33,88)end
local s,S,a,b,c,d=e:rep((N-n)/2),e:rep(n-2),table.unpack(R)return
n<2 and s..C(a)..p or s..C(a)..S..C(b)..s..p..f(n-2,N)..s..C(c)..S..C(d)..s..p
end

Ungolfed

function f(n,N)
  N=N or n                          -- N is equal to the n we had on the first call
  e=" "                             -- shorthand for the space
  p="\n"                            -- shorthand for the newline
  r=math.random                     -- shorthand for math.random
  C=e.char                          -- uses the string e to obtain the function string.char
  R={}                              -- define an array for our random values
  for i=1,4                         -- iterate 4 times (for the random characters)
  do
    x=r(33,126)                     -- random between ASCII "!" and "~"
    R[i]=x~=89 and x~=121           -- if we didn't pick y or Y
           and x                    -- keep this number
         or r(33,88)                -- or roll for a character between "!" and "X"
  end
  local s,S                         -- these variables have to be local
          ,a,b,c,d                  -- or the recursion would change them
         =e:rep((N-n)/2),e:rep(n-2) -- s and S are the number of spaces for the X
           ,table.unpack(R)         -- a,b,c and d are the 4 random characters
  return n<2                        -- if n==1
           and s..C(a)..p           -- we're at the center of the X, time to end recursion
         or                         -- else
           s..C(a)..S..C(b)..s..p   -- concatenate the topmost line for n
           ..f(n-2,N)               -- with the inner X
           ..s..C(c)..S..C(d)..s..p -- and the bottom line
end


问:
Removing unique elements from string
I came upon this question, because it seems to be very common use-case to find unique characters in string. But what if we want to get rid of them?

Input contains only lower case alphabets. Only letters from a to z are used. Input length may be from 1 to 1000 characters.

Example:

input: helloworld

output: llool

Objective: Shortest code wins

Language: Any of the top 20 of TIOBE languages

答:
Python (56)

Here's another (few chars longer) alternative in Python:

```<code>a=raw_input();print''.join(c for c in a if a.count(c)>1)
</code>```

If you accept output as a list (e.g. ['l', 'l', 'o', 'o', 'l']), then we could boil it down to 49 characters:

```<code>a=raw_input();print[c for c in a if a.count(c)>1]
</code>```

Title: Removing unique elements from string

Body:
Python (56)

Here's another (few chars longer) alternative in Python:

a=raw_input();print''.join(c for c in a if a.count(c)>1)

If you accept output as a list (e.g. ['l', 'l', 'o', 'o', 'l']), then we could boil it down to 49 characters:

a=raw_input();print[c for c in a if a.count(c)>1]


问:
Array Escape - get out of there
One day you awake only to find yourself caught in an array. You try to just walk out of there, taking one index at the time, but it seems there are other rules:

The array is completely filled with natural numbers.

If you find yourself on an index n, you go to the index array[n], except:

If you find yourself on an index n which is a prime number, you take array[n] steps back

Example:
You start on index 4, in this array (start index is 0):

```<code>array = [1,4,5,6,8,10,14,15,2,2,4,5,7];
-----------------^ you are here
</code>```

As the value of the field you are on is 8, you go to the index 8 as the first step. The field you land on contains the value 2. You then go to index 2 as your second step. As2is a prime number, you take 5 steps back, which is your third step. As there is no index -3, you successfully escaped the array in a total of 3 steps.

Your task is:

To write a program or function, which accepts an array and a start index as parameter, and outputs the amount of steps to escape the array. If you can't escape the array (e.g. [2,0,2] with start-index 2 => you constantly go from index 2 to 0), output a falsy value. You may use one-based indexing or zero-based indexing, but please specify which you use.

Test cases

Input: [2,5,6,8,1,2,3], 3

Output: 1

Input: [2, 0, 2], 2

Output: false

Input: [14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11], 5;

Output: 6

The shortest answer wins.

答:
Racket, <s>183</s> 156 bytes

Probably more bytes savable with further golfing, but that's it for me. :)

(require math)(define(e l i[v'()][g length])(cond[(memq i v)#f][(not(< -1 i(g l)))(g v)][else(e l((λ(a)(if(prime? i)(- i a)a))(list-ref l i))(cons i v))]))
```

<p>Complete module with test suite with cleaner function:</p>

<pre class="lang-rkt prettyprint-override"><code>#lang racket

(require math)

(define (e l i [v'()] [g length])
  (cond
    [(memq i v) #f]
    [(not (< -1 i (g l))) (g v)]
    [else (e l
             ((λ (a) (if (prime? i)
                         (- i a)
                         a))
              (list-ref l i))
             (cons i v))]))

(module+ test
  (require rackunit)
  (define escape-tests
    '((((2 5 6 8 1 2 3) 3) . 1)
      (((2 0 2) 2) . #f)
      (((14 1 2 5 1 3 51 5 12 3 4 41 15 4 12 243 51 2 14 51 12 11) 5) . 6)))
  (for ([t escape-tests])
    (check-equal? (apply e (car t)) (cdr t) (~a t))))
</code>```

Run it like raco test e.rkt

Major kudos for @cat discovering the undocumented prime? function.

Title: Array Escape - get out of there

Body:
Racket, <s>183</s> 156 bytes

Probably more bytes savable with further golfing, but that's it for me. :)

(require math)(define(e l i[v'()][g length])(cond[(memq i v)#f][(not(< -1 i(g l)))(g v)][else(e l((λ(a)(if(prime? i)(- i a)a))(list-ref l i))(cons i v))]))

Complete module with test suite with cleaner function:

#lang racket

(require math)

(define (e l i [v'()] [g length])
  (cond
    [(memq i v) #f]
    [(not (< -1 i (g l))) (g v)]
    [else (e l
             ((λ (a) (if (prime? i)
                         (- i a)
                         a))
              (list-ref l i))
             (cons i v))]))

(module+ test
  (require rackunit)
  (define escape-tests
    '((((2 5 6 8 1 2 3) 3) . 1)
      (((2 0 2) 2) . #f)
      (((14 1 2 5 1 3 51 5 12 3 4 41 15 4 12 243 51 2 14 51 12 11) 5) . 6)))
  (for ([t escape-tests])
    (check-equal? (apply e (car t)) (cdr t) (~a t))))

Run it like raco test e.rkt

Major kudos for @cat discovering the undocumented prime? function.


答:
Python 2, <s>204</s> <s>191</s> 183 bytes

Okay, Python competition here is getting fierce. Here's my attempt on shaving as many bytes as possible. <s>By now I'm stuck</s> (Ok, stuck again).

Credits to @NonlinearFruit for the way random characters are selected.

183 byte version:

```<code>import re,random
s=i=input();t=lambda:re.sub("y|Y","t",chr(random.randint(33,126)))
while i>-s:i-=2;u=abs(i);z=(s-u)/2-1;print('',' '*-~z+t()+'\n')[-1==i]+(' '*z+t()+' '*u+t())*(i>-s)
</code>```

Try It Online! (Ideone)

Main change is to rewrite the conditional

```<code>(" "*(z+1)+t()+"\n"if -1==i else"")
</code>```

as

```<code>(""," "*-~z+t()+'\n')[-1==i]
</code>```

which saves 7 bytes.

191 byte version:

```<code>import re,random
s=i=input();t=lambda:re.sub("y|Y","t",chr(random.randint(33,126)))
while i>-s:
 i-=2;u=abs(i);z=(s-u)/2-1;print(' '*(z+1)+t()+'\n'if -1==i else'')+(' '*z+t()+' '*u+t())*(i>-s)
</code>```

Try It Online! (Ideone)

Main changes are the way random characters are selected and some code rearrangement such as s=input();i=s; becoming s=i=input();, removing the r=range assignment as it is no longer needed and calling abs directly as it results in less bytes of code.

<s>Beating the previous shortest answer in Python by 1 byte!</s> @R. Kap 's approach is used for generating the random characters.
Each iteration of the while loop a row of the ex is printed.

204 byte version:

```<code>from random import*
s=input();i=s;a=abs;r=range;t=lambda:chr(choice(r(33,89)+r(90,121)+r(122,128)))
while i>-s:
 i-=2;z=(s-a(i))/2-1;print(' '*(z+1)+t()+'\n'if -1==i else'')+(' '*z+t()+' '*a(i)+t())*(i>-s)
</code>```

Try It Online! (Ideone)

Ungolfed version to get an idea of how it works:

```<code>from random import *
random_character = lambda : chr(choice(range(33,89)+range(90,121)+range(122,128)))

size = input()
current_row = size

while current_row > -size:
    current_row-=2
    n_leading_spaces = (size-abs(current_row)/2)-1
    row_to_print = ''
    if current_row == -1:
        row_to_print = ' ' * (n_leading_spaces+1) + random_chr() + '\n'
    if current_row > -size:
        row_to_print += ' ' * n_leading_spaces + random_chr()+' '*abs(current_row)+random_chr()
    print row_to_print
</code>```

It was hard to handle the 1-character case!

Title: Do X without Y

Body:
Usually, it is said that "Doing X without Y" can be a trap to beginners writing challenges (source). However, I am cocky and think that I can definitely make an X without any Ys. Randomly. Oh yes, this will be good.

Challenge: Given an odd integer n greater than or equal to 1, output an ex of side length n made of random printable ascii characters sans "y" and "Y", and the space. All allowed characters must have a nonzero chance of occurring, but not necessarily uniform. This is a code-golf so the shortest code in bytes wins. You should, however, randomize each char--that is, the struts of the ex shouldn't be equal, unless if by chance.

The chars to appear

```<code>!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXZ[\]^_`abcdefghijklmnopqrstuvwxz{|}~"
</code>```

Constructing the ex

Side length 1:

```<code>x
</code>```

Side length 3:

```<code>x x
 x
x x
</code>```

Side length 5:

```<code>x   x
 x x
  x
 x x
x   x
</code>```

etc.

Example outputs

```<code>input
output
empty line

3
h 2
 ^
9 5

1
:

5
D   1
 W z
  W
 q j
W   1
</code>```

Example implementation

You do not need to handle invalid inputs.

function generate(sideLength){
    var result = "";
    var INNER = "@"
    for(var i = 0; i < sideLength; i++){
        var p = i < sideLength / 2 ? i : sideLength - i - 1;
        result += " ".repeat(p) + ((sideLength / 2 | 0) == p ? "" : INNER) + " ".repeat(Math.max(sideLength - p * 2 - 2, 0)) + INNER + "\n";
    }

    return result.replace(RegExp(INNER, "g"), function(e){
        let c = "y";
        while(c === "y" || c === "Y"){
            c = String.fromCharCode((Math.random() * 94) + 33 | 0);
        }
        return c;
    });
}

function print(v){
    output.innerHTML = "";
    output.appendChild(document.createTextNode(v));
}

function update(){
    var n = Number(input.value);
    if(n !== Math.floor(n)) print("error: " + n + " is not an integer.");
    else if(n % 2 === 0)    print("error: " + n + " is not odd.");
    else if(n < 1)          print("error: " + n + "is less than one.");
    else                    print(generate(n));
}

input.onchange = update;

update();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  font-family: Consolas, monospace;
}

#output {
  white-space: pre;
}</code>```

<input id="input" min=1 value=1 type=Number>

```

Body:
Python 2, <s>204</s> <s>191</s> 183 bytes

Okay, Python competition here is getting fierce. Here's my attempt on shaving as many bytes as possible. <s>By now I'm stuck</s> (Ok, stuck again).

Credits to @NonlinearFruit for the way random characters are selected.

183 byte version:

import re,random
s=i=input();t=lambda:re.sub("y|Y","t",chr(random.randint(33,126)))
while i>-s:i-=2;u=abs(i);z=(s-u)/2-1;print('',' '*-~z+t()+'\n')[-1==i]+(' '*z+t()+' '*u+t())*(i>-s)

Try It Online! (Ideone)

Main change is to rewrite the conditional

(" "*(z+1)+t()+"\n"if -1==i else"")

as

(""," "*-~z+t()+'\n')[-1==i]

which saves 7 bytes.

191 byte version:

import re,random
s=i=input();t=lambda:re.sub("y|Y","t",chr(random.randint(33,126)))
while i>-s:
 i-=2;u=abs(i);z=(s-u)/2-1;print(' '*(z+1)+t()+'\n'if -1==i else'')+(' '*z+t()+' '*u+t())*(i>-s)

Try It Online! (Ideone)

Main changes are the way random characters are selected and some code rearrangement such as s=input();i=s; becoming s=i=input();, removing the r=range assignment as it is no longer needed and calling abs directly as it results in less bytes of code.

<s>Beating the previous shortest answer in Python by 1 byte!</s> @R. Kap 's approach is used for generating the random characters.
Each iteration of the while loop a row of the ex is printed.

204 byte version:

from random import*
s=input();i=s;a=abs;r=range;t=lambda:chr(choice(r(33,89)+r(90,121)+r(122,128)))
while i>-s:
 i-=2;z=(s-a(i))/2-1;print(' '*(z+1)+t()+'\n'if -1==i else'')+(' '*z+t()+' '*a(i)+t())*(i>-s)

Try It Online! (Ideone)

Ungolfed version to get an idea of how it works:

from random import *
random_character = lambda : chr(choice(range(33,89)+range(90,121)+range(122,128)))

size = input()
current_row = size

while current_row > -size:
    current_row-=2
    n_leading_spaces = (size-abs(current_row)/2)-1
    row_to_print = ''
    if current_row == -1:
        row_to_print = ' ' * (n_leading_spaces+1) + random_chr() + '\n'
    if current_row > -size:
        row_to_print += ' ' * n_leading_spaces + random_chr()+' '*abs(current_row)+random_chr()
    print row_to_print

It was hard to handle the 1-character case!


问:
Convert exponents into ASCII art

Task

Your task is to convert strings like this:

```<code>abc^d+ef^g + hijk^l - M^NO^P (Ag^+)
</code>```

To strings like this:

```<code>   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )
</code>```

Which is an approximation to abcd+efg + hijkl - MNOP (Ag+)

In words, raise the characters directly next to carets to the upper line, one character for one caret.

Specs

Extra trailing whitespaces in the output are allowed.

No chained carets like m^n^o will be given as input.

A caret will not be followed immediately by a space or by another caret.

A caret will not be preceded immediately by a space.

All carets will be preceded by at least one character and followed by at least one character.

The input string will only contain printable ASCII characters (U+0020 - U+007E)

Instead of two lines of output, you are allowed to output an array of two strings.

To those who speak regex: the input string will match this regex:

```<code>/^(?!.*(\^.\^|\^\^|\^ | \^))(?!\^)[ -~]*(?<!\^)$/
</code>```

Leaderboard

var QUESTION_ID=86647,OVERRIDE_USER=48934;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
PowerShell v2+, <s>88</s> 83 bytes

```<code>-join([char[]]$args[0]|%{if($c){$_;$b+=' '}elseif($_-94){$b+=$_;' '}$c=$_-eq94});$b
</code>```

A little longer than the others, but showcases a little PowerShell magic and a little different logic.

Essentially the same concept as the Python answers -- we iterate over the input character-by-character, remember whether the previous one was a caret ($c), and put the current character into the appropriate spot. However, the logic and method for determining where to output is handled a little differently, and without a tuple or separate variables -- we test if the previous character was a caret, and if so output the character to the pipeline and concatenate a space onto $b. Otherwise we check if the current character is a caret elseif($_-94) and so long as it's not, we concatenate the current character onto $b and output a space to the pipeline. Finally, we set whether the current character is a caret for the next go-round.

We gather those characters from the pipeline together in parens, encapsulate them in a -join which turns them into a string, and leave that along with $b on the pipeline. Output at the end is implicit with a newline inbetween.

For comparison, here's a direct port of @xnor's Python answer, at 85 bytes:

```<code>$a=,''*2;[char[]]$args[($l=0)]|%{$a[!$l]+="$_"*($c=$_-ne94);$a[$l]+=' '*$c;$l=!$c};$a
</code>```

Title: Convert exponents into ASCII art

Body:
PowerShell v2+, <s>88</s> 83 bytes

-join([char[]]$args[0]|%{if($c){$_;$b+=' '}elseif($_-94){$b+=$_;' '}$c=$_-eq94});$b

A little longer than the others, but showcases a little PowerShell magic and a little different logic.

Essentially the same concept as the Python answers -- we iterate over the input character-by-character, remember whether the previous one was a caret ($c), and put the current character into the appropriate spot. However, the logic and method for determining where to output is handled a little differently, and without a tuple or separate variables -- we test if the previous character was a caret, and if so output the character to the pipeline and concatenate a space onto $b. Otherwise we check if the current character is a caret elseif($_-94) and so long as it's not, we concatenate the current character onto $b and output a space to the pipeline. Finally, we set whether the current character is a caret for the next go-round.

We gather those characters from the pipeline together in parens, encapsulate them in a -join which turns them into a string, and leave that along with $b on the pipeline. Output at the end is implicit with a newline inbetween.

For comparison, here's a direct port of @xnor's Python answer, at 85 bytes:

$a=,''*2;[char[]]$args[($l=0)]|%{$a[!$l]+="$_"*($c=$_-ne94);$a[$l]+=' '*$c;$l=!$c};$a


答:
Perl, 35 bytes

34 bytes code + 1 for -p

$_=s/\^(.)|./$1||$"/ger.s/\^./ /gr
```

<h3>Usage</h3>

<pre class="lang-sh prettyprint-override"><code>perl -pe '$_=s/\^(.)|./$1||$"/ger.s/\^./ /gr' <<< 'abc^d+ef^g + hijk^l - M^NO^P (Ag^+)'
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )
</code>```

Note: This is exactly the same as Value Ink's answer which I spied afterwards. Will remove if needed as this doesn't really add to the Ruby solution.

Title: Convert exponents into ASCII art

Body:
Task

Your task is to convert strings like this:

```<code>abc^d+ef^g + hijk^l - M^NO^P (Ag^+)
</code>```

To strings like this:

```<code>   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )
</code>```

Which is an approximation to abcd+efg + hijkl - MNOP (Ag+)

In words, raise the characters directly next to carets to the upper line, one character for one caret.

Specs

Extra trailing whitespaces in the output are allowed.

No chained carets like m^n^o will be given as input.

A caret will not be followed immediately by a space or by another caret.

A caret will not be preceded immediately by a space.

All carets will be preceded by at least one character and followed by at least one character.

The input string will only contain printable ASCII characters (U+0020 - U+007E)

Instead of two lines of output, you are allowed to output an array of two strings.

To those who speak regex: the input string will match this regex:

```<code>/^(?!.*(\^.\^|\^\^|\^ | \^))(?!\^)[ -~]*(?<!\^)$/
</code>```

Leaderboard

var QUESTION_ID=86647,OVERRIDE_USER=48934;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
Perl, 35 bytes

34 bytes code + 1 for -p

$_=s/\^(.)|./$1||$"/ger.s/\^./ /gr

Usage

perl -pe '$_=s/\^(.)|./$1||$"/ger.s/\^./ /gr' <<< 'abc^d+ef^g + hijk^l - M^NO^P (Ag^+)'
   d   g       l    N P    +
abc +ef  + hijk  - M O  (Ag )

Note: This is exactly the same as Value Ink's answer which I spied afterwards. Will remove if needed as this doesn't really add to the Ruby solution.


问:
Legalize Reversed Date
Input:

A Date (containing dd, MM and yyyy). A date-object, or three separate integers are also valid as input.

Output:

Each part (dd, MM and yyyy) individually reverted and than rounded to the nearest valid date.

For example (in the format dd-MM-yyyy):

21-10-2016 becomes 12-01-6102

Challenge rules:

Only dd, MM, yyyy is valid, but the order and which separate-symbols you use is your own choice.

So these are some valid format examples: dd-MM-yyyy; MM/dd/yyyy; yyyy MM dd; ddMMyyyy, etc.

And these are some invalid format examples: dd MMM yyyy; dd-MM-'yy; etc.

You can also choose to just input a Date-object if your language supports it or three separate integer parameters, instead of the string representing a date.

Please state which date-format you've used! (And the input and output must be in the same format.) It is also allowed to output a Date-object, as long as it can handle all test cases and the challenge rule below.

The Julian to Gregorian Calendar transition is ignored for this challenge. So 1582 is just a valid reversed year for 2851.

See Challenge info / tips for all valid years, months and days.

Since you cannot have February as reversed of any other month, you don't have to worry about leap years.

All reversed years, months and days:

The year can always be reversed without a problem, reaching from 0001 (reversed of 1000) to 9999 (remains 9999). (So 0000 isn't a valid input, and there are also no test cases for it.)

The only months you'll have reversed are: January (reversed from October / 10); October (reversed from January / 01); November (remains November / 11); and December (reversed from every other month / 02-09, 12).

The only days you'll have reversed are: 01 (reversed from 10), 02 (reversed from 20), 03 (reversed from 30), 10 (reversed from 01), 11 (remains 11), 12 (reversed from 21), 13 (reversed from 31), 20 (reversed from 02), 21 (reversed from 12), 22 (remains 22), 30 (reversed from 03 or the same as 31 for November!), 31 (reversed from 04-09 / 13-19 / 23-29).

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return statements/output, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases (dd-MM-yyyy as format):

```<code>21-07-2016   ->   12-12-6102
12-11-1991   ->   21-11-1991
01-01-2000   ->   10-10-0002
27-08-1875   ->   31-12-5781
18-12-2010   ->   31-12-0102
13-01-1981   ->   31-10-1891
04-11-1671   ->   30-11-1761  // Semi-tricky case, since November has 30 days
28-11-2036   ->   30-11-6302  // Semi-tricky case, since November has 30 days
14-06-1855   ->   31-12-5581
30-10-9999   ->   03-01-9999
01-01-2851   ->   10-10-1582
</code>```

答:
Python 2, 154 bytes

```<code>z=input().split("-");r=[x[::-1]for x in z];z[1]=r[1]if r[1]<'12'else '12';z[0]=r[0]if r[0]<'31'else '30'if z[1]=='11'else '31';z[2]=r[2];print "-".join(z)
</code>```

Takes the input as a string, so quotes need to be specified in the input, e.g. "11-04-2016".

Title: Legalize Reversed Date

Body:
Python 2, 154 bytes

z=input().split("-");r=[x[::-1]for x in z];z[1]=r[1]if r[1]<'12'else '12';z[0]=r[0]if r[0]<'31'else '30'if z[1]=='11'else '31';z[2]=r[2];print "-".join(z)

Takes the input as a string, so quotes need to be specified in the input, e.g. "11-04-2016".


问:
Golf all the 16 logic gates with 2 inputs and 1 output!
For example, the gate A and B is a logic gate with 2 inputs and 1 output.

There are exactly 16 of them, because:

each logic gate takes two inputs, which can be truthy or falsey, giving us 4 possible inputs

of the 4 possible inputs, each can have an output of truthy and falsey

therefore, there are 2^4 possible logic gates, which is 16.

Your task is to write 16 programs/functions which implement all of them separately.

Your functions/programs must be independent.

They are valid as long as they output truthy/falsey values, meaning that you can implement A or B in Python as lambda a,b:a+b, even if 2 is produced for A=True and B=True.

Score is total bytes used for each function/program.

List of logic gates

0,0,0,0 (false)

0,0,0,1 (and)

0,0,1,0 (A and not B)

0,0,1,1 (A)

0,1,0,0 (not A and B)

0,1,0,1 (B)

0,1,1,0 (xor)

0,1,1,1 (or)

1,0,0,0 (nor)

1,0,0,1 (xnor)

1,0,1,0 (not B)

1,0,1,1 (B implies A)

1,1,0,0 (not A)

1,1,0,1 (A implies B)

1,1,1,0 (nand)

1,1,1,1 (true)

Where the first number is the output for A=false, B=false,
the second number is the output for A=false, B=true,
the third number is the output for A=true, B=false,
the fourth number is the output for A=true, B=true.

Leaderboard

var QUESTION_ID=82938,OVERRIDE_USER=48934;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+(?:\.\d+)?)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
MarioLANG, <s>265</s> 263 bytes

This is going to be a fairly long answer since this is a 2D language. Trailing newlines are significant wherever they appear.

Note that these programs were written and tested on Try it Online!. There are some things that can be done on the Ruby interpreter but not in TIO's. See Martin Ender's answer for the code golfed further making use of that.

False (2 bytes)

```<code>:

</code>```

Outputs the initial value of the first cell, which is 0.

A and B (<s>15</s> 14 bytes)

```<code>;-
=[
+<;
:=:

</code>```

Takes in A and check if it's 0. If it is, it outputs 0 and ends. Otherwise, it takes in B and outputs it.

A and not B (25 bytes)

```<code>;-
=[
 <;
 =-
++[<:
:===

</code>```

Check if A is 1. If it is, outputs 0 and ends. Otherwise, takes in B and check if it's 1. If it is, outputs 0, if it isn't, outputs 1.

A (4 bytes)

```<code>;
:

</code>```

Takes in A and outputs it.

not A and B (<s>14</s> 13 bytes)

```<code>;
=[
-<;
:=:

</code>```

Takes in A and checks if it's 0. If it is, takes in B outputs it. Otherwise, outputs 0.

B (6 bytes)

```<code>;
;
:

</code>```

Takes in A, then B, then outputs B.

A xor B (34 bytes)

```<code>;);[!(
====#:
+![(<
:#=="
 >-:
 "=
</code>```

Takes in A and B. If B is 1, output NOT A. If B is 0, output A.

A or B (13 bytes)

```<code>;
=[
:<;:
 ==
</code>```

If A is 1, output A. Otherwise, output B.

A nor B (23 bytes)

```<code>;
=[
 <;
-=[
:-<+:
 ===
</code>```

If A is 1, output (0). Otherwise, output NOT B.

A xnor B (27 bytes)

```<code>;
)
;
[!(
=#=[
(<-<+
:":=:

</code>```

Takes in A and B. If B is 0, output NOT A. Otherwise, output A.

not B (18 bytes)

```<code>;-
=[
+<;
:=:

</code>```0

Takes in B. If B is 0, add 1 and output. Otherwise, subtract 1 and output. This same construct is used for negation in the other gates.

B implies A (23 bytes)

```<code>;-
=[
+<;
:=:

</code>```1

If A is 1, output 1. Otherwise, output NOT B.

not A (17 bytes)

```<code>;-
=[
+<;
:=:

</code>```2

Same as the NOT B answer, except only takes the first the input, not the second.

A implies B (16 bytes)

```<code>;-
=[
+<;
+=:
:

</code>```

If A is 0, output 1. Otherwise, output B.

A nand B (24 bytes)

```<code>;-
=[
+<;
+=[
:-<+:
 ===
</code>```

If A is 0, output 1. Otherwise, output NOT B.

True (3 bytes)

```<code>+
:

</code>```

Increments the first cell and outputs it, giving 1.

Body:
MarioLANG, <s>265</s> 263 bytes

This is going to be a fairly long answer since this is a 2D language. Trailing newlines are significant wherever they appear.

Note that these programs were written and tested on Try it Online!. There are some things that can be done on the Ruby interpreter but not in TIO's. See Martin Ender's answer for the code golfed further making use of that.

False (2 bytes)

:

Outputs the initial value of the first cell, which is 0.

A and B (<s>15</s> 14 bytes)

;-
=[
+<;
:=:

Takes in A and check if it's 0. If it is, it outputs 0 and ends. Otherwise, it takes in B and outputs it.

A and not B (25 bytes)

;-
=[
 <;
 =-
++[<:
:===

Check if A is 1. If it is, outputs 0 and ends. Otherwise, takes in B and check if it's 1. If it is, outputs 0, if it isn't, outputs 1.

A (4 bytes)

;
:

Takes in A and outputs it.

not A and B (<s>14</s> 13 bytes)

;
=[
-<;
:=:

Takes in A and checks if it's 0. If it is, takes in B outputs it. Otherwise, outputs 0.

B (6 bytes)

;
;
:

Takes in A, then B, then outputs B.

A xor B (34 bytes)

;);[!(
====#:
+![(<
:#=="
 >-:
 "=

Takes in A and B. If B is 1, output NOT A. If B is 0, output A.

A or B (13 bytes)

;
=[
:<;:
 ==

If A is 1, output A. Otherwise, output B.

A nor B (23 bytes)

;
=[
 <;
-=[
:-<+:
 ===

If A is 1, output (0). Otherwise, output NOT B.

A xnor B (27 bytes)

;
)
;
[!(
=#=[
(<-<+
:":=:

Takes in A and B. If B is 0, output NOT A. Otherwise, output A.

not B (18 bytes)

;;
==[
:-<+:
 ===

Takes in B. If B is 0, add 1 and output. Otherwise, subtract 1 and output. This same construct is used for negation in the other gates.

B implies A (23 bytes)

;
=[
 <;
 =[
:-<+:
 ===

If A is 1, output 1. Otherwise, output NOT B.

not A (17 bytes)

;
==[
:-<+:
 ===

Same as the NOT B answer, except only takes the first the input, not the second.

A implies B (16 bytes)

;-
=[
+<;
+=:
:

If A is 0, output 1. Otherwise, output B.

A nand B (24 bytes)

;-
=[
+<;
+=[
:-<+:
 ===

If A is 0, output 1. Otherwise, output NOT B.

True (3 bytes)

+
:

Increments the first cell and outputs it, giving 1.


答:
Cinnamon Gum, 21 bytes

```<code>0000000: 5306 6533 bd92 d1db 8899 8381 a2f8 8f8c  S.e3............
0000010: 1230 249e a1                             .0$..
</code>```

Non-competing. Try it online.

Explanation

I'm not much of a regex golfer so there's probably a better way to do this.

The string decompresses to:

```<code>S(?<!\^)[^^]& &\^&`S\^.&
</code>```

(note the trailing space)

The first S stage receives input and uses a negative lookbehind to replace all characters other than carets with no preceding caret with a space, then deletes all carets. Then it immediately outputs the modified input string with a newline and removes that S stage. Since STDIN is now exhausted and the previous stage didn't provide any input, the next S stage receives the last line of STDIN again and then replaces all carets followed by any character with a space and outputs that.

In Perl psuedo-code:

```<code>$first_stage_sub_1 = ($input =~ s/(?<!\^)[^^]/ /gr);
$first_stage_sub_2 = ($first_stage_sub_1 =~ s/\^//gr);
print $first_stage_sub_2, "\n";

$second_stage_sub = ($input =~ s/\^./ /gr);
print $second_stage_sub, "\n";
</code>```

Title: Convert exponents into ASCII art

Body:
Cinnamon Gum, 21 bytes

0000000: 5306 6533 bd92 d1db 8899 8381 a2f8 8f8c  S.e3............
0000010: 1230 249e a1                             .0$..

Non-competing. Try it online.

Explanation

I'm not much of a regex golfer so there's probably a better way to do this.

The string decompresses to:

S(?<!\^)[^^]& &\^&`S\^.&

(note the trailing space)

The first S stage receives input and uses a negative lookbehind to replace all characters other than carets with no preceding caret with a space, then deletes all carets. Then it immediately outputs the modified input string with a newline and removes that S stage. Since STDIN is now exhausted and the previous stage didn't provide any input, the next S stage receives the last line of STDIN again and then replaces all carets followed by any character with a space and outputs that.

In Perl psuedo-code:

$first_stage_sub_1 = ($input =~ s/(?<!\^)[^^]/ /gr);
$first_stage_sub_2 = ($first_stage_sub_1 =~ s/\^//gr);
print $first_stage_sub_2, "\n";

$second_stage_sub = ($input =~ s/\^./ /gr);
print $second_stage_sub, "\n";


问:
Golf you a quine for great good!
Using your language of choice, golf a quine.

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.

No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.

No error quines -- there is already a separate challenge for error quines.

Points for:

Smallest code (in bytes)

Most obfuscated/obscure solution

Using esoteric/obscure languages

Successfully using languages that are difficult to golf in

The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:

var QUESTION_ID=69;
var OVERRIDE_USER=98;

var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}
function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}
function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=!1;comment_page=1;getComments()}})}
function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}
getAnswers();var SCORE_REG=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}
function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))
body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)
valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,})});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)
lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+a.language+'').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages)
if(languages.hasOwnProperty(lang))
langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)return-1;return 0});for(var i=0;i<langs.length;++i)
{var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

  <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654">

Winners by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}

{{LANGUAGE}}	{{NAME}}	{{SIZE}}

 ```

答:
F#, 90 bytes

```<code>let q="let q=%A
printf(Printf.TextWriterFormat<_>q)q"
printf(Printf.TextWriterFormat<_>q)q
</code>```

F#’s smart printf comes back to byte us! We can’t write let q="...";;printf q q, as the first parameter to printf isn’t actually a string:

```<code>printf : TextWriterFormat<'T> -> 'T
</code>```

F# uses some compiler magic under the hood to guarantee type-safe printf calls. For example, "yay %d wow!" is a valid TextWriterFormat<int -> unit> literal, but not a valid TextWriterFormat<double -> unit> literal. But if we define the format string separately, the compiler will see it as a regular old string and complain. Instead, we have to convert q ourselves in the first argument.

What about let q:TextWriterFormat<_>="..."? First of all, that’s two bytes longer. But second of all, the second argument to printf really needs to be a string, otherwise the typechecker will infer that we’re formatting a formatter, which in turn formats a formatter, which formats a…

```<code>error FS0001: Type mismatch. Expecting a
    'a
but given a
    Printf.TextWriterFormat<('a -> unit)>
The resulting type would be infinite when unifying ''a' and
    'Printf.TextWriterFormat<('a -> unit)>'
</code>```

Yep, an infinite type. Oops.

Title: Golf you a quine for great good!

Body:
F#, 90 bytes

let q="let q=%A
printf(Printf.TextWriterFormat<_>q)q"
printf(Printf.TextWriterFormat<_>q)q

F#’s smart printf comes back to byte us! We can’t write let q="...";;printf q q, as the first parameter to printf isn’t actually a string:

printf : TextWriterFormat<'T> -> 'T

F# uses some compiler magic under the hood to guarantee type-safe printf calls. For example, "yay %d wow!" is a valid TextWriterFormat<int -> unit> literal, but not a valid TextWriterFormat<double -> unit> literal. But if we define the format string separately, the compiler will see it as a regular old string and complain. Instead, we have to convert q ourselves in the first argument.

What about let q:TextWriterFormat<_>="..."? First of all, that’s two bytes longer. But second of all, the second argument to printf really needs to be a string, otherwise the typechecker will infer that we’re formatting a formatter, which in turn formats a formatter, which formats a…

error FS0001: Type mismatch. Expecting a
    'a
but given a
    Printf.TextWriterFormat<('a -> unit)>
The resulting type would be infinite when unifying ''a' and
    'Printf.TextWriterFormat<('a -> unit)>'

Yep, an infinite type. Oops.


Title: Do X without Y

Body:
C, 268 bytes

V(c){for(c=89;c==89||c==121;c=rand()%95+33);return c;}p(n,s){n^1?s-n?printf("%*.c",s-n,32):0,printf("%c%*.c%c\n",V(),n*2-3,32,V()),p(n-1,s),s-n?printf("%*.c",s-n,32):0,printf("%c%*.c%c\n",V(),2*n-3,32,V()):printf("%*.c%c\n",s-n,32,V());}f(n){srand(time(NULL));p(n,n);}

Call f() with the size of the x to draw.


Title: Removing unique elements from string

Body:
I came upon this question, because it seems to be very common use-case to find unique characters in string. But what if we want to get rid of them?

Input contains only lower case alphabets. Only letters from a to z are used. Input length may be from 1 to 1000 characters.

Example:

input: helloworld

output: llool

Objective: Shortest code wins

Language: Any of the top 20 of TIOBE languages

Body:
Ruby 46 40 36

gets.chars{|c|$><<c if$_.count(c)>1}


答:
Python 3, 82 bytes

```<code>lambda x:[min(x[0][::-1],['31','30'][x[1]=='11']),min(x[1][::-1],'12'),x[2][::-1]]
</code>```

An anonymous function that takes input, via argument, of the date as a list of strings of the form ['dd', 'mm', 'yyyy'] and returns the validated reversed date in the same format.

How it works

Python compares characters and strings by their Unicode code-points. This means that any comparison on two or more integers returns the same as that comparison on those integers as strings. Hence, calling min on two integers as strings returns the smallest integer as a string; by taking the reversed date-part as one argument and the maximum value as another, the day and month are clamped to the desired range. The date-parts are reversed by indexing with steps of -1 ([::-1]), and the maximum value for the month is changed from '31' to '30' if the month is November by indexing into a list with the Boolean result of a conditional.

Try it on Ideone

Title: Legalize Reversed Date

Body:
Input:

A Date (containing dd, MM and yyyy). A date-object, or three separate integers are also valid as input.

Output:

Each part (dd, MM and yyyy) individually reverted and than rounded to the nearest valid date.

For example (in the format dd-MM-yyyy):

21-10-2016 becomes 12-01-6102

Challenge rules:

Only dd, MM, yyyy is valid, but the order and which separate-symbols you use is your own choice.

So these are some valid format examples: dd-MM-yyyy; MM/dd/yyyy; yyyy MM dd; ddMMyyyy, etc.

And these are some invalid format examples: dd MMM yyyy; dd-MM-'yy; etc.

You can also choose to just input a Date-object if your language supports it or three separate integer parameters, instead of the string representing a date.

Please state which date-format you've used! (And the input and output must be in the same format.) It is also allowed to output a Date-object, as long as it can handle all test cases and the challenge rule below.

The Julian to Gregorian Calendar transition is ignored for this challenge. So 1582 is just a valid reversed year for 2851.

See Challenge info / tips for all valid years, months and days.

Since you cannot have February as reversed of any other month, you don't have to worry about leap years.

All reversed years, months and days:

The year can always be reversed without a problem, reaching from 0001 (reversed of 1000) to 9999 (remains 9999). (So 0000 isn't a valid input, and there are also no test cases for it.)

The only months you'll have reversed are: January (reversed from October / 10); October (reversed from January / 01); November (remains November / 11); and December (reversed from every other month / 02-09, 12).

The only days you'll have reversed are: 01 (reversed from 10), 02 (reversed from 20), 03 (reversed from 30), 10 (reversed from 01), 11 (remains 11), 12 (reversed from 21), 13 (reversed from 31), 20 (reversed from 02), 21 (reversed from 12), 22 (remains 22), 30 (reversed from 03 or the same as 31 for November!), 31 (reversed from 04-09 / 13-19 / 23-29).

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return statements/output, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases (dd-MM-yyyy as format):

```<code>21-07-2016   ->   12-12-6102
12-11-1991   ->   21-11-1991
01-01-2000   ->   10-10-0002
27-08-1875   ->   31-12-5781
18-12-2010   ->   31-12-0102
13-01-1981   ->   31-10-1891
04-11-1671   ->   30-11-1761  // Semi-tricky case, since November has 30 days
28-11-2036   ->   30-11-6302  // Semi-tricky case, since November has 30 days
14-06-1855   ->   31-12-5581
30-10-9999   ->   03-01-9999
01-01-2851   ->   10-10-1582
</code>```

Body:
Python 3, 82 bytes

lambda x:[min(x[0][::-1],['31','30'][x[1]=='11']),min(x[1][::-1],'12'),x[2][::-1]]

An anonymous function that takes input, via argument, of the date as a list of strings of the form ['dd', 'mm', 'yyyy'] and returns the validated reversed date in the same format.

How it works

Python compares characters and strings by their Unicode code-points. This means that any comparison on two or more integers returns the same as that comparison on those integers as strings. Hence, calling min on two integers as strings returns the smallest integer as a string; by taking the reversed date-part as one argument and the maximum value as another, the day and month are clamped to the desired range. The date-parts are reversed by indexing with steps of -1 ([::-1]), and the maximum value for the month is changed from '31' to '30' if the month is November by indexing into a list with the Boolean result of a conditional.

Try it on Ideone


答:
PowerShell v2+, 112 bytes

```<code>Param($i)function f{Random(33..126-ne121-ne89|%{[char]$_})};1..$i|%{$a=,' '*$i;$a[$_-1]=f;$a[$i-$_]=f;$a-join''}
</code>```

Reads input off the command line.

For each line, an array of spaces is created, the correct indices filled in with characters pulled from function f, then the char array is joined to output as one line.

Title: Do X without Y

Body:
PowerShell v2+, 112 bytes

Param($i)function f{Random(33..126-ne121-ne89|%{[char]$_})};1..$i|%{$a=,' '*$i;$a[$_-1]=f;$a[$i-$_]=f;$a-join''}

Reads input off the command line.

For each line, an array of spaces is created, the correct indices filled in with characters pulled from function f, then the char array is joined to output as one line.


问:
Count up folks!

Introduction

It may sound strange, but we haven't got ONE challenge for counting from 1 to n, inclusive.

This is not the same thing. That one is a (closed) not well-explained challenge.

This is not the same thing. That one is about counting up indefinitely.

Challenge

Write a program or function that prints every integer from 1 to n inclusive.

Rules

You can get n any way.

You can assume that n will always be a positive integer.

You can get n in any base, but you should always output in decimal.

Output must be separated by any character (or pattern) not in 0123456789. Non-decimal leading or trailing characters are allowed (for example when using arrays such as [1, 2, 3, 4, 5, 6]).

Standard loopholes are denied.

We want to find the shortest approach in each language, not the shortest language, so I will not accept any answer.

You must update your answer(s) after this edit, answers posted before the last edit must comply with the change rule about standard loopholes (I didn't want to deny them, but I didn't want to make the community roar, so I denied them).

You can use any post-dating language version (or language). You cannot use any language or language version made just for this challenge.

Bonuses

20%

Your program must be able to count at least up to 18446744073709551615 (2^64-1). For example, if a new datatype is the only way to support big integers, you must construct it. If your language does not have any way to support huge integers up to 2^64-1, the upper limit of that particular language must be supported instead.

EDIT: I've changed the limit from 2^64 to 2^64-1 to allow more answers.

EDIT: I made the 2^64-1 rule a bonus, since there has not been much interest in this challenge. If your answer supports 2^64-1, you can now edit it to include the bonus. Also, you can post an answer not supporting it, if it is shorter.

答:
Python 3, 31 bytes

print(*range(1,int(input())+1))
```

Outputs the range of numbers space-separated. Uses * operator magic to explode the output of range into separate arguments to print, which separates its arguments with spaces by default.

Title: Count up folks!

Body:
Python 3, 31 bytes

print(*range(1,int(input())+1))

Outputs the range of numbers space-separated. Uses * operator magic to explode the output of range into separate arguments to print, which separates its arguments with spaces by default.


问:
Thwart Lepton compression
Dropbox recently released Lepton (GitHub), a method that losslessly compresses JPEG images round-trip, saving an average of 22%.

Because of the pigeonhole principle, any general compression algorithm cannot be guaranteed to result in a smaller file (general because it doesn't apply to inputs constrained to a specific format). Lepton exploits common characteristics about JPEGs, which if subverted, might pigeonhole it to produce a file larger than the source.

Requirements

Write a program that generates:

A valid JPEG/JFIF image,

with a size between 0.5 MB and 1 MB,

no smaller than 256 × 256 px,

no larger than 4096 × 4096 px,

recognizable by Lepton (it can successfully "compress" to a .lep image), and

decompresses to an identical .jpg (as the input).

APPx, COM, and other metadata, non-graphical marker sections are restricted in the JPEG (injecting arbitrary amounts of random bytes into the image to asymptotically approach 1:1 compression is lame.)

an APP0 JFIF marker is permitted but no thumbnail is allowed (should be exactly 16 bytes)

tl;dr If you're not intentionally shoving metadata into an EXIF segment and you disable any sort of thumbnail your language library of choice wants to put into the image, that should be OK.

Post the code and image.

If you want to write a program that produces a Lepton image that when converted yields a JPEG meeting the criteria, that's fine. It must remain identical across arbitrarily many JPEG → Lepton → JPEG → ... cycles.

Scoring

The byte size of the Lepton image divided by the source JPEG image. Higher (worse Lepton compression) is better. Run Lepton with default flags and switches.

Getting Lepton

A 5-second crash-course to build Lepton:

```<code>git clone https://github.com/dropbox/lepton.git
cd lepton
./autogen.sh && ./configure && make

# fish shell: ./autogen.sh ;and ./configure ;and make
</code>```

Then ./lepton --help should tell you things.

答:
Naive Noise, 1024 × 1024: score 85.55%

A compliant example in Python to get the ball rolling. Not optimized in any way; probable shortcomings:

No idea what the default quality setting is.

Each 8x8 block has practically the exact same average value (~50%) to the one adjacent to it: Lepton says that they use that information to save space.

Totally default quantization and Huffman tables (whatever the library decides to use).

```<code>import numpy as np
from PIL import Image

np.random.seed(0) # make sure it's repeatable.

size = 1024

imgr = np.random.randint(0, 0xFF, (size, size, 3)).astype('uint8')
pimg = Image.fromarray(imgr)
pimg.save('noise.jpg')
</code>```

Then some bash to do the thing:

```<code>./lepton noise.jpg noise.lep 2>\dev\null # vomits out a lot of technobabble
./lepton noise.lep noise-out.jpg 2>\dev\null

diff -qs noise.jpg noise-out.jpg

SIZE1=$(stat -f "%z" noise.jpg) # http://superuser.com/a/570920/18931
SIZE2=$(stat -f "%z" noise.lep)
RATIO=$(bc <<< "scale=4; $SIZE2/$SIZE1")
echo "$SIZE2/$SIZE1 = $RATIO"

# Files noise.jpg and noise-out.jpg are identical
# 538817/629769 = .8555
</code>```

Title: Thwart Lepton compression

Body:
Naive Noise, 1024 × 1024: score 85.55%

A compliant example in Python to get the ball rolling. Not optimized in any way; probable shortcomings:

No idea what the default quality setting is.

Each 8x8 block has practically the exact same average value (~50%) to the one adjacent to it: Lepton says that they use that information to save space.

Totally default quantization and Huffman tables (whatever the library decides to use).

import numpy as np
from PIL import Image

np.random.seed(0) # make sure it's repeatable.

size = 1024

imgr = np.random.randint(0, 0xFF, (size, size, 3)).astype('uint8')
pimg = Image.fromarray(imgr)
pimg.save('noise.jpg')

Then some bash to do the thing:

./lepton noise.jpg noise.lep 2>\dev\null # vomits out a lot of technobabble
./lepton noise.lep noise-out.jpg 2>\dev\null

diff -qs noise.jpg noise-out.jpg

SIZE1=$(stat -f "%z" noise.jpg) # http://superuser.com/a/570920/18931
SIZE2=$(stat -f "%z" noise.lep)
RATIO=$(bc <<< "scale=4; $SIZE2/$SIZE1")
echo "$SIZE2/$SIZE1 = $RATIO"

# Files noise.jpg and noise-out.jpg are identical
# 538817/629769 = .8555


问:
Calculate the number e
From Wikipedia:

The number e is an important mathematical constant that is the base of the natural logarithm. It is approximately equal to 2.71828, and is the limit of (1 + 1/n)n as n approaches infinity.

Challenge

Calculate the number e to 15 digits after the decimal point.

This means that your output must start with 2.718281828459045 or equivalent.

Your program can output digits after the required output - these may be accurate or inaccurate, inaccuracy after 15 digits does not disqualify you from the challenge. Your program may also output nothing after the required 15 digits.

This is code-golf, shortest implementation in bytes wins.

Constraints

You may not use built in constants or hardcode the number.

Standard loopholes and rules apply.

Reference Implementation (Ruby)

```<code>def e(i)
  e = 1.0                        # make it floating point
  i.times { |n|                  # loop repeats n times
    e += 1.0/(1..n+1).reduce(:*) # factorial - no factorial function
  }                              # in the Ruby standard library
  return e
end
e(200)                           # Almost certainly will return e
</code>```

答:
Haskell, <s>33</s> 31 Bytes

-2 Bytes thanks to @xnor

```<code>sum[1/product[1..i]|i<-[0..99]]
</code>```

Straightforward implementation of the series definition. (I have posted a version of this to Reddit before.)

Title: Calculate the number e

Body:
Haskell, <s>33</s> 31 Bytes

-2 Bytes thanks to @xnor

sum[1/product[1..i]|i<-[0..99]]

Straightforward implementation of the series definition. (I have posted a version of this to Reddit before.)


答:
R, 196 bytes

```<code>n=scan()
if(n<4)c(1,n)else{
r=2:n
d=NULL
while(n>1){i=r[min(which(n%%r==0))];d=c(d,i);n=n/i}
m=unique(d)
b=table(d)
l=list()
for(i in 1:length(m))l[[i]]=m[i]^(0:b[i])
apply(expand.grid(l),1,prod)}
</code>```

This is going to be inefficient as heck because I hardly resisted the temptation of using library(primes). It creates a vector d of all prime factors of the input, computes their frequency (number of occurreces),  and then computes the cartesian product of all possible powers (from 0 to the respective frequency b[i]), to which the prod function is applied. Dang it, special cases of 2 and 3! Otherwise, this is a nice showcase of R dataframe handling and vector functions / by-row operations (and even the purely statistical table function!).

Of course, its efficiency can be improved at the cost of 15 bytes using r=2:ceiling(sqrt(n)), if someone cares. Here is a nicer ungolfed version:

```<code>factorise <- function(n){
  if (n<4) c(1,n) else { # Now that all special cases have been handled
    r=2:ceiling(sqrt(n)) # We check all divisors smaller than the square root
    d=NULL # Initiate the variable for divisors
    while (n>1) {
      i=r[min(which(n%%r==0))] # Check the first divisor with a zero remainder
      d=c(d,i) # Append it to the list of divisors
      n=n/i   # Divide by it and check again
    }
    m=unique(d) # Get unique divisors, and they are already sorted
    b=table(d) # Count their frequencies
    l=list() # Initiate a list of all possible powers of unique factors
    for(i in 1:length(m)) l[[i]]=m[i]^(0:b[i]) # Calculate powers
    apply(expand.grid(l),1,prod) # Make a cartesian dataframe and row-multiply
  }
}
</code>```

Body:
Given an input of an integer \$n ≥ 2\$, output a list of its divisors sorted by the
exponents in their prime factorizations, in ascending order, ordering first by
the largest prime, then by the second largest, and so on.

As an example, take the integer \$72\$, which is \$2^3\cdot3^2\$. It has
the divisors

```<code>1     3^0 · 2^0
2     3^0 · 2^1
3     3^1 · 2^0
4     3^0 · 2^2
6     3^1 · 2^1
8     3^0 · 2^3
9     3^2 · 2^0
12    3^1 · 2^2
18    3^2 · 2^1
24    3^1 · 2^3
36    3^2 · 2^2
72    3^2 · 2^3
</code>```

When sorted in ascending order by the exponents on the prime factors, with
larger primes taking priority, this becomes

```<code>1     3^0 · 2^0
2     3^0 · 2^1
4     3^0 · 2^2
8     3^0 · 2^3
3     3^1 · 2^0
6     3^1 · 2^1
12    3^1 · 2^2
24    3^1 · 2^3
9     3^2 · 2^0
18    3^2 · 2^1
36    3^2 · 2^2
72    3^2 · 2^3
</code>```

Note that the list is sorted first by the order of the exponent of 3, and then
by the exponent of 2. You can also think of this as reading from left to right
and top to bottom across the following grid:

```<code>        2^0  2^1  2^2  2^3

3^0     1    2    4    8
3^1     3    6    12   24
3^2     9    18   36   72
</code>```

Test cases:

```<code>2 => 1 2
72 => 1 2 4 8 3 6 12 24 9 18 36 72
101 => 1 101
360 => 1 2 4 8 3 6 12 24 9 18 36 72 5 10 20 40 15 30 60 120 45 90 180 360
3780 => 1 2 4 3 6 12 9 18 36 27 54 108 5 10 20 15 30 60 45 90 180 135 270 540 7 14 28 21 42 84 63 126 252 189 378 756 35 70 140 105 210 420 315 630 1260 945 1890 3780
30030 => 1 2 3 6 5 10 15 30 7 14 21 42 35 70 105 210 11 22 33 66 55 110 165 330 77 154 231 462 385 770 1155 2310 13 26 39 78 65 130 195 390 91 182 273 546 455 910 1365 2730 143 286 429 858 715 1430 2145 4290 1001 2002 3003 6006 5005 10010 15015 30030
65536 => 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536
74088 => 1 2 4 8 3 6 12 24 9 18 36 72 27 54 108 216 7 14 28 56 21 42 84 168 63 126 252 504 189 378 756 1512 49 98 196 392 147 294 588 1176 441 882 1764 3528 1323 2646 5292 10584 343 686 1372 2744 1029 2058 4116 8232 3087 6174 12348 24696 9261 18522 37044 74088
</code>```

Since this is code-golf, the shortest code in bytes wins.

Body:
R, 196 bytes

n=scan()
if(n<4)c(1,n)else{
r=2:n
d=NULL
while(n>1){i=r[min(which(n%%r==0))];d=c(d,i);n=n/i}
m=unique(d)
b=table(d)
l=list()
for(i in 1:length(m))l[[i]]=m[i]^(0:b[i])
apply(expand.grid(l),1,prod)}

This is going to be inefficient as heck because I hardly resisted the temptation of using library(primes). It creates a vector d of all prime factors of the input, computes their frequency (number of occurreces),  and then computes the cartesian product of all possible powers (from 0 to the respective frequency b[i]), to which the prod function is applied. Dang it, special cases of 2 and 3! Otherwise, this is a nice showcase of R dataframe handling and vector functions / by-row operations (and even the purely statistical table function!).

Of course, its efficiency can be improved at the cost of 15 bytes using r=2:ceiling(sqrt(n)), if someone cares. Here is a nicer ungolfed version:

factorise <- function(n){
  if (n<4) c(1,n) else { # Now that all special cases have been handled
    r=2:ceiling(sqrt(n)) # We check all divisors smaller than the square root
    d=NULL # Initiate the variable for divisors
    while (n>1) {
      i=r[min(which(n%%r==0))] # Check the first divisor with a zero remainder
      d=c(d,i) # Append it to the list of divisors
      n=n/i   # Divide by it and check again
    }
    m=unique(d) # Get unique divisors, and they are already sorted
    b=table(d) # Count their frequencies
    l=list() # Initiate a list of all possible powers of unique factors
    for(i in 1:length(m)) l[[i]]=m[i]^(0:b[i]) # Calculate powers
    apply(expand.grid(l),1,prod) # Make a cartesian dataframe and row-multiply
  }
}


答:
Haskell, 25 bytes

f 99=0;f n=1+f(n+1)/n;f 0
```

<p>26 bytes:</p>

<pre class="lang-haskell prettyprint-override"><code>foldr(\x y->1+y/x)0[1..99]
</code>```

Title: Calculate the number e

Body:
From Wikipedia:

The number e is an important mathematical constant that is the base of the natural logarithm. It is approximately equal to 2.71828, and is the limit of (1 + 1/n)n as n approaches infinity.

Challenge

Calculate the number e to 15 digits after the decimal point.

This means that your output must start with 2.718281828459045 or equivalent.

Your program can output digits after the required output - these may be accurate or inaccurate, inaccuracy after 15 digits does not disqualify you from the challenge. Your program may also output nothing after the required 15 digits.

This is code-golf, shortest implementation in bytes wins.

Constraints

You may not use built in constants or hardcode the number.

Standard loopholes and rules apply.

Reference Implementation (Ruby)

```<code>def e(i)
  e = 1.0                        # make it floating point
  i.times { |n|                  # loop repeats n times
    e += 1.0/(1..n+1).reduce(:*) # factorial - no factorial function
  }                              # in the Ruby standard library
  return e
end
e(200)                           # Almost certainly will return e
</code>```

Body:
Haskell, 25 bytes

f 99=0;f n=1+f(n+1)/n;f 0

26 bytes:

foldr(\x y->1+y/x)0[1..99]


问:
Approximation of e
We all know that the Euler's number, denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \$x\$ equal \$1\$, we obtain

$$\sum_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

Challenge

Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.

Scoring

Program with least amount of bytes wins.

答:
Dyalog APL, 6 bytes

```<code>+/÷!⍳⎕
</code>```

+/ sum of

÷ the reciprocals of

! the factorials of

⍳ the numbers from 0 to

⎕ numerical input

Assumes ⎕IO←0, which is default on many systems.

TryAPL!

Title: Approximation of e

Body:
Dyalog APL, 6 bytes

+/÷!⍳⎕

+/ sum of

÷ the reciprocals of

! the factorials of

⍳ the numbers from 0 to

⎕ numerical input

Assumes ⎕IO←0, which is default on many systems.

TryAPL!


答:
Idris, 88 bytes

```<code>q:String;main:IO();main=putStr$q++show q;q="q:String;main:IO();main=putStr$q++show q;q="
</code>```

It’s like Haskell with more enforced top-level type signatures. I had to put q’s type first, because Idris’s type checker is a little weird? I dunno.

Title: Golf you a quine for great good!

Body:
Using your language of choice, golf a quine.

A quine is a non-empty computer program which takes no input and produces a copy of its own source code as its only output.

No cheating -- that means that you can't just read the source file and print it. Also, in many languages, an empty file is also a quine: that isn't considered a legit quine either.

No error quines -- there is already a separate challenge for error quines.

Points for:

Smallest code (in bytes)

Most obfuscated/obscure solution

Using esoteric/obscure languages

Successfully using languages that are difficult to golf in

The following Stack Snippet can be used to get a quick view of the current score in each language, and thus to know which languages have existing answers and what sort of target you have to beat:

var QUESTION_ID=69;
var OVERRIDE_USER=98;

var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(index){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}
function commentUrl(index,answers){return"https://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}
function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=!1;comment_page=1;getComments()}})}
function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}
getAnswers();var SCORE_REG=(function(){var headerTag=String.raw `h\d`
var score=String.raw `\-?\d+\.?\d*`
var normalText=String.raw `[^\n<>]*`
var strikethrough=String.raw `<s>${normalText}</s>|<strike>${normalText}</strike>|<del>${normalText}</del>`
var noDigitText=String.raw `[^\n\d<>]*`
var htmlTag=String.raw `<[^\n<>]+>`
return new RegExp(String.raw `<${headerTag}>`+String.raw `\s*([^\n,]*[^\s,]),.*?`+String.raw `(${score})`+String.raw `(?=`+String.raw `${noDigitText}`+String.raw `(?:(?:${strikethrough}|${htmlTag})${noDigitText})*`+String.raw `</${headerTag}>`+String.raw `)`)})();var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}
function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))
body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)
valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,})});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)
lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+a.language+'').text().toLowerCase();languages[lang]=languages[lang]||{lang:a.language,user:a.user,size:a.size,link:a.link,uniq:lang}});var langs=[];for(var lang in languages)
if(languages.hasOwnProperty(lang))
langs.push(languages[lang]);langs.sort(function(a,b){if(a.uniq>b.uniq)return 1;if(a.uniq<b.uniq)return-1;return 0});for(var i=0;i<langs.length;++i)
{var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

  <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654">

Winners by Language

Language	User	Score

Leaderboard

	Author	Language	Size

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}

{{LANGUAGE}}	{{NAME}}	{{SIZE}}

 ```

Body:
Idris, 88 bytes

q:String;main:IO();main=putStr$q++show q;q="q:String;main:IO();main=putStr$q++show q;q="

It’s like Haskell with more enforced top-level type signatures. I had to put q’s type first, because Idris’s type checker is a little weird? I dunno.


答:
Perl 44

```<code>$l=$_;print join"",grep{$l=~/$_.*$_/}split""
</code>```

Execution:

```<code>perl -lane '$l=$_;print join"",grep{$l=~/$_.*$_/}split""' <<< helloworld
llool
</code>```

Title: Removing unique elements from string

Body:
Perl 44

$l=$_;print join"",grep{$l=~/$_.*$_/}split""

Execution:

perl -lane '$l=$_;print join"",grep{$l=~/$_.*$_/}split""' <<< helloworld
llool


答:
R, 17 bytes

```<code>sum(1/gamma(1:n))
</code>```

Quite straightforward, although numerical precision issues are bound to arise at some point in time.

Title: Approximation of e

Body:
We all know that the Euler's number, denoted by \$e\$, to the power of some variable \$x\$, can be approximated by using the Maclaurin Series expansion:

$$e^x=\sum_{k=0}^{\infty}{\frac{x^k}{k!}}=1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\dots$$

By letting \$x\$ equal \$1\$, we obtain

$$\sum_{k=0}^{\infty}{\frac{1}{k!}{=\frac{1}{0!}+\frac{1}{1!}+\frac{1}{2!}+\frac{1}{3!}+\frac{1}{4!}+\dots\\=1+1+\frac{1}{2}+\frac{1}{6}+\frac{1}{24}+\dots}}$$

Challenge

Write a program in any language which approximates Euler's number by taking in an input \$n\$ and calculates the series to the \$n\$th term. Note that the first term has denominator \$0!\$, not \$1!\$, i.e. \$n=1\$ corresponds to \$\frac{1}{0!}\$.

Scoring

Program with least amount of bytes wins.

Body:
R, 17 bytes

sum(1/gamma(1:n))

Quite straightforward, although numerical precision issues are bound to arise at some point in time.


问:
Remove all occurrences of the first letter of a string from the entire string
Given an input string only containing the characters A-Z, a-z, and spaces, remove all occurrences of the uppercase and lowercase versions of the first character of the string (if the first character is A remove all As and as, if the first character is (space) remove all spaces), and print the output.

Example cases:

Testing Testing One Two Three -> esing esing One wo hree

Programming Puzzles and Code Golf -> rogramming uzzles and Code Golf

How much wood would a woodchuck chuck if a woodchuck could chuck wood -> ow muc wood would a woodcuck cuck if a woodcuck could cuck wood

{space}hello world -> helloworld

welcome to WATER WORLD -> elcome to ATER ORLD

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

Notes:

Input will always be 2 or more valid characters.

Output will never be an empty string.

答:
Vim, 30 Keystrokes

Sorry to unearth, but i don't see any Vim answer D:

```<code>If<Right>xh@x.<Esc>"xy07|@x2|~0"xd7|@x0x
</code>```

Explanation:

If<Right>xh@x.<Esc>

Write a (recursive) macro around the first character

Moving left (h) is needed to stay at the left of the next unread character

Adding any character (.) at the end is needed in case the second must be removed

"xy0 Copy the macro in the register x

7| Move to the 7th char

@x Run the macro from x

2|~ Switch the case of the first char (actually at the 2nd position)

0"xd7| Cut the macro in the register x

@x Run the macro from x

0x Remove the place-holder .

Body:
Vim, 30 Keystrokes

Sorry to unearth, but i don't see any Vim answer D:

If<Right>xh@x.<Esc>"xy07|@x2|~0"xd7|@x0x

Explanation:

If<Right>xh@x.<Esc>

Write a (recursive) macro around the first character

Moving left (h) is needed to stay at the left of the next unread character

Adding any character (.) at the end is needed in case the second must be removed

"xy0 Copy the macro in the register x

7| Move to the 7th char

@x Run the macro from x

2|~ Switch the case of the first char (actually at the 2nd position)

0"xd7| Cut the macro in the register x

@x Run the macro from x

0x Remove the place-holder .


答:
C# <s>314</s> <s>305</s> <s>299</s> <s>249</s> <s>232</s> 223 Bytes

```<code>using System.Linq;string f(int d,int m,int y){Func<int,string>r=i=>string.Concat((""+i).PadLeft(2,'0').Reverse());Func<string,int,string>x=(j,k)=>int.Parse(j)>k?""+k:j;return x(r(d),m==11?30:31)+"-"+x(r(m),12)+"-"+r(y);}
</code>```

Thanks to @KevinCruijssen for pointing out that I could shorten my variable declaration, which also made aliasing string able to save some bytes.

Saved 50 bytes storing the reversing function for reuse and another 13 by doing the same for the rounding and removing the variable declarations.

Last update makes aliasing string no longer a byte saver.

Ungolfed Version:

```<code>using System.Linq;
    string dateReverse(int day, int month, int year)
{
    //setup a resuable function to reverse
    Func<int, string> reverse = intToReverse => string.Concat((""+intToReverse).PadLeft(2, '0').Reverse());

    //another function for rounding
    Func<string, int, string> round = (strToRound, maxVal) => int.Parse(strToRound) > maxVal ? "" + maxVal : strToRound;

    //Join the strings into the "dd-mm-yyyy" date format
    return
        //Round down the day value, if november cap to 30 otherwise cap to 31
        round(reverse(day), month == 11 ? 30 : 31) + "-" +

        //Round the month down
        round(reverse(month), 12) + "-" +

        //we can use the reverse function here too and pad left just won't do anything
        reverse(year);
}
</code>```

Test it here

Title: Legalize Reversed Date

Body:
Input:

A Date (containing dd, MM and yyyy). A date-object, or three separate integers are also valid as input.

Output:

Each part (dd, MM and yyyy) individually reverted and than rounded to the nearest valid date.

For example (in the format dd-MM-yyyy):

21-10-2016 becomes 12-01-6102

Challenge rules:

Only dd, MM, yyyy is valid, but the order and which separate-symbols you use is your own choice.

So these are some valid format examples: dd-MM-yyyy; MM/dd/yyyy; yyyy MM dd; ddMMyyyy, etc.

And these are some invalid format examples: dd MMM yyyy; dd-MM-'yy; etc.

You can also choose to just input a Date-object if your language supports it or three separate integer parameters, instead of the string representing a date.

Please state which date-format you've used! (And the input and output must be in the same format.) It is also allowed to output a Date-object, as long as it can handle all test cases and the challenge rule below.

The Julian to Gregorian Calendar transition is ignored for this challenge. So 1582 is just a valid reversed year for 2851.

See Challenge info / tips for all valid years, months and days.

Since you cannot have February as reversed of any other month, you don't have to worry about leap years.

All reversed years, months and days:

The year can always be reversed without a problem, reaching from 0001 (reversed of 1000) to 9999 (remains 9999). (So 0000 isn't a valid input, and there are also no test cases for it.)

The only months you'll have reversed are: January (reversed from October / 10); October (reversed from January / 01); November (remains November / 11); and December (reversed from every other month / 02-09, 12).

The only days you'll have reversed are: 01 (reversed from 10), 02 (reversed from 20), 03 (reversed from 30), 10 (reversed from 01), 11 (remains 11), 12 (reversed from 21), 13 (reversed from 31), 20 (reversed from 02), 21 (reversed from 12), 22 (remains 22), 30 (reversed from 03 or the same as 31 for November!), 31 (reversed from 04-09 / 13-19 / 23-29).

General rules:

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

Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return statements/output, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases (dd-MM-yyyy as format):

```<code>21-07-2016   ->   12-12-6102
12-11-1991   ->   21-11-1991
01-01-2000   ->   10-10-0002
27-08-1875   ->   31-12-5781
18-12-2010   ->   31-12-0102
13-01-1981   ->   31-10-1891
04-11-1671   ->   30-11-1761  // Semi-tricky case, since November has 30 days
28-11-2036   ->   30-11-6302  // Semi-tricky case, since November has 30 days
14-06-1855   ->   31-12-5581
30-10-9999   ->   03-01-9999
01-01-2851   ->   10-10-1582
</code>```

Body:
C# <s>314</s> <s>305</s> <s>299</s> <s>249</s> <s>232</s> 223 Bytes

using System.Linq;string f(int d,int m,int y){Func<int,string>r=i=>string.Concat((""+i).PadLeft(2,'0').Reverse());Func<string,int,string>x=(j,k)=>int.Parse(j)>k?""+k:j;return x(r(d),m==11?30:31)+"-"+x(r(m),12)+"-"+r(y);}

Thanks to @KevinCruijssen for pointing out that I could shorten my variable declaration, which also made aliasing string able to save some bytes.

Saved 50 bytes storing the reversing function for reuse and another 13 by doing the same for the rounding and removing the variable declarations.

Last update makes aliasing string no longer a byte saver.

Ungolfed Version:

using System.Linq;
    string dateReverse(int day, int month, int year)
{
    //setup a resuable function to reverse
    Func<int, string> reverse = intToReverse => string.Concat((""+intToReverse).PadLeft(2, '0').Reverse());

    //another function for rounding
    Func<string, int, string> round = (strToRound, maxVal) => int.Parse(strToRound) > maxVal ? "" + maxVal : strToRound;

    //Join the strings into the "dd-mm-yyyy" date format
    return
        //Round down the day value, if november cap to 30 otherwise cap to 31
        round(reverse(day), month == 11 ? 30 : 31) + "-" +

        //Round the month down
        round(reverse(month), 12) + "-" +

        //we can use the reverse function here too and pad left just won't do anything
        reverse(year);
}

Test it here