答:
R, 115 bytes

So... I'm posting my solution because I find the question pretty interesting. I did my best with R's capacities to deal with roman numbers without packages :  you can only input numbers between 1 and 3899, as the as.roman's documentation explains.

That's why I cheated a bit by giving range between 1 to <s>11</s> 14 in the for loop : <s>it's the lenght of as.roman(3899)'s output (MMMDCCCXCIX)</s>.

In fact, according to this website, the longest roman number is MMDCCCLXXXVIII (14 characters), which corresponds to 2888.

Furthermore, you can't compute the length of the output of this function.

```<code>a=scan();v=0;for(i in 1:14){v=c(v,as.numeric(charToRaw(substring(as.character(as.roman(a)),1:14,1:14)[i])))};sum(v)
</code>```

If anyone sees a solution to deal with the above problems, please feel free to comment.

Title: Integer goes back and forth through time

Body:
Input:

An integer.

Output:

First convert the integer to it's equivalent Roman Numeral.

Then convert each capital letter of that Roman Numeral to their ASCII/UNICODE decimal value.

And output the sum of those.

Example:

```<code>1991 -> MCMXCI -> 77+67+77+88+67+73 -> 449
^ input                                ^ output
</code>```

Roman Numerals:

Here is a perhaps useful Roman Numeral Converter.

Challenge rules:

Standard Roman Numeral rules are applied, so no alternative forms like IIII or VIIII instead of IV and IX.*

The Macron lines above the Roman Numerals past 1,000 are ¯ (UNICODE nr. 175). So one line counts as +175 and two as +350.

You are allowed to use any kind of input and output type, as long as it represents the integers.

The test cases will be in the range of 1 - 2,147,483,647.

* Roman Numeral rules (quote from Wikipedia):

Numbers are formed by combining symbols and adding the values, so II is two (two ones) and XIII is thirteen (a ten and three ones). Because each numeral has a fixed value rather than representing multiples of ten, one hundred and so on, according to position, there is no need for "place keeping" zeros, as in numbers like 207 or 1066; those numbers are written as CCVII (two hundreds, a five and two ones) and MLXVI (a thousand, a fifty, a ten, a five and a one).

Symbols are placed from left to right in order of value, starting with the largest. However, in a few specific cases, to avoid four characters being repeated in succession (such as IIII or XXXX), subtractive notation is often used as follows:

I placed before V or X indicates one less, so four is IV (one less than five) and nine is IX (one less than ten)

X placed before L or C indicates ten less, so forty is XL (ten less than fifty) and ninety is XC (ten less than a hundred)

C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand)

  For example, MCMIV is one thousand nine hundred and four, 1904 (M is a thousand, CM is nine hundred and IV is four).

Some examples of the modern use of Roman numerals include:

  1954 as MCMLIV; 1990 as MCMXC; 2014 as MMXIV

  SOURCE

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, 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:

```<code>100          ->   67
1            ->   73
4            ->   159
22           ->   322
5000         ->   261
2016         ->   401
1000000000   ->   427
1991         ->   449
9999         ->   800
1111111111   ->   2344
2147483647   ->   5362
</code>```

Body:
R, 115 bytes

So... I'm posting my solution because I find the question pretty interesting. I did my best with R's capacities to deal with roman numbers without packages :  you can only input numbers between 1 and 3899, as the as.roman's documentation explains.

That's why I cheated a bit by giving range between 1 to <s>11</s> 14 in the for loop : <s>it's the lenght of as.roman(3899)'s output (MMMDCCCXCIX)</s>.

In fact, according to this website, the longest roman number is MMDCCCLXXXVIII (14 characters), which corresponds to 2888.

Furthermore, you can't compute the length of the output of this function.

a=scan();v=0;for(i in 1:14){v=c(v,as.numeric(charToRaw(substring(as.character(as.roman(a)),1:14,1:14)[i])))};sum(v)

If anyone sees a solution to deal with the above problems, please feel free to comment.


问:
"Add one" to every color in an image
You would simply take this image and make every color added one to every hexadecimal digit. For example, #49de5f would become #5aef60 (with the 9 looping to an a, and the f looping to a 0.)

This would also mean that all white (#ffffff) would become black (#000000) because all f loops back to 0, but all black will become a lighter shade of black (#111111).

Scoring is based on the least number of bytes used, as this is a code-golf question.

Use the below image as the input image for your code, and put the output image of your code into your answer.

If you want to, you can also use this other rainbow image:

答:
Java 142 bytes

```<code>public BufferedImage translateColor(BufferedImage image){
  for(int i=-1;++i<image.getWidth();)
    for(int j=-1;++<image.getHeight();)
      image.setRGB(i,j,image.getRGB(i,j)+1118481);
  return image;
}
</code>```

Golfed:

```<code>BufferedImage t(BufferedImage i){for(int x=-1;++x<i.getWidth();)for(int y=-1;++y<i.getHeight();)i.setRGB(x,y,i.getRGB(x,y)+1118481);return i;}
</code>```

ContentLicense: CC BY-SA 3.0

Title: "Add one" to every color in an image

Body:
Java 142 bytes

public BufferedImage translateColor(BufferedImage image){
  for(int i=-1;++i<image.getWidth();)
    for(int j=-1;++<image.getHeight();)
      image.setRGB(i,j,image.getRGB(i,j)+1118481);
  return image;
}

Golfed:

BufferedImage t(BufferedImage i){for(int x=-1;++x<i.getWidth();)for(int y=-1;++y<i.getHeight();)i.setRGB(x,y,i.getRGB(x,y)+1118481);return i;}


问:
Snakes all around

Challenge

The challenge is simple: print a snake.

You will get the length of the snake as input.

A snake of length 2 looks like this:

```<code>==(:)-
</code>```

A snake of length 7 looks like this:

```<code>=======(:)-
</code>```

In other words, the length of a snake is how many equal signs are before the head.

Usage

Let's say I made a C++ implementation and compiled it to ./getsnake.

I could run it like so:

```<code>$ ./getsnake 10
==========(:)-
</code>```

Clarifications

Standard loopholes are disallowed.

You can get input and output in any acceptable way.

You can assume all inputs given are positive integers.

You may write a function instead of a regular program.

答:
Kotlin, 34 bytes

```<code>{String(ByteArray(it){61})+"(:)-"}
</code>```

This assumes that a function of (Int)->String type is requested (in such case, it is assumed to be an Int). Version with explicit typing (40 bytes):

```<code>{n:Int->String(ByteArray(n){61})+"(:)-"}
</code>```

Try it out on the JVM target:

```<code>fun main(args: Array<String>) {
    val f: (Int)->String = {String(ByteArray(it){61})+"(:)-"}
    println(f(5))
}
</code>```

Title: Snakes all around

Body:
Kotlin, 34 bytes

{String(ByteArray(it){61})+"(:)-"}

This assumes that a function of (Int)->String type is requested (in such case, it is assumed to be an Int). Version with explicit typing (40 bytes):

{n:Int->String(ByteArray(n){61})+"(:)-"}

Try it out on the JVM target:

fun main(args: Array<String>) {
    val f: (Int)->String = {String(ByteArray(it){61})+"(:)-"}
    println(f(5))
}


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

Definition

The infinite spiral used in this question has 0 on the position (0,0), and continues like this:

```<code>16-15-14-13-12
 |           |
17  4--3--2 11
 |  |     |  |
18  5  0--1 10
 |  |        |
19  6--7--8--9
 |
20--21...
</code>```

It is to be interpreted as a Cartesian plane.

For example, 1 is on the position (1,0), and 2 is on the position (1,1).

Task

Given a non-negative integer, output its position in the spiral.

Specs

Your spiral can start with 1 instead of 0. If it starts with 1, please indicate so in your answer.

Output the two numbers in any sensible format.

Testcases

The testcases are 0-indexed but you can use 1-indexed as well.

```<code>input output
0     (0,0)
1     (1,0)
2     (1,1)
3     (0,1)
4     (-1,1)
5     (-1,0)
6     (-1,-1)
7     (0,-1)
8     (1,-1)
9     (2,-1)
100   (-5,5)
</code>```

答:
JavaScript (ES7), 75 bytes

```<code>n=>[0,0].map(_=>((a+2>>2)-a%2*n)*(a--&2?1:-1),a=(n*4+1)**.5|0,n-=a*a>>2)
</code>```

Who needs complex arithmetic? Note: returns -0 instead of 0 in some cases.

Body:
JavaScript (ES7), 75 bytes

n=>[0,0].map(_=>((a+2>>2)-a%2*n)*(a--&2?1:-1),a=(n*4+1)**.5|0,n-=a*a>>2)

Who needs complex arithmetic? Note: returns -0 instead of 0 in some cases.


问:
Hofstadter H-sequence

Definition

\$a(0) = 0\$

\$a(n) = n-a(a(a(n-1)))\$ for integer \$n > 0\$

Task

Given non-negative integer \$n\$, output \$a(n)\$.

Testcases

```<code>n     a(n)
0     0
1     1
2     1
3     2
4     3
5     4
6     4
7     5
8     5
9     6
10    7
11    7
12    8
13    9
14    10
15    10
16    11
17    12
18    13
19    13
20    14
10000 6823
</code>```

References

WolframMathWorld

OEIS A005374

答:
Ruby, 27 bytes

The obvious implementation.

a=->n{n<1?0:n-a[a[a[n-1]]]}
```

<p>This is a longer, faster answer that caches previous entries in the sequence.
Both answers only work for versions after 1.9, as that was when <code>-></code>, the stabby lambda, was introduced to Ruby.</p>

<pre class="lang-ruby prettyprint-override"><code>->n{r=[0];i=0;(i+=1;r<<i-r[r[r[i-1]]])while i<n;r[n]}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Hofstadter H-sequence

Body:
Ruby, 27 bytes

The obvious implementation.

a=->n{n<1?0:n-a[a[a[n-1]]]}

This is a longer, faster answer that caches previous entries in the sequence.
Both answers only work for versions after 1.9, as that was when ->, the stabby lambda, was introduced to Ruby.

->n{r=[0];i=0;(i+=1;r<<i-r[r[r[i-1]]])while i<n;r[n]}


Title: Hofstadter H-sequence

Body:
Definition

\$a(0) = 0\$

\$a(n) = n-a(a(a(n-1)))\$ for integer \$n > 0\$

Task

Given non-negative integer \$n\$, output \$a(n)\$.

Testcases

```<code>n     a(n)
0     0
1     1
2     1
3     2
4     3
5     4
6     4
7     5
8     5
9     6
10    7
11    7
12    8
13    9
14    10
15    10
16    11
17    12
18    13
19    13
20    14
10000 6823
</code>```

References

WolframMathWorld

OEIS A005374

Body:
C#, 35 bytes

int a(int n)=>n>0?n-a(a(a(n-1))):0;


问:
How Many Rectangles in the Grid?

Well, although this challenge turned out to be a huge success, it also turned out to be very trivial to solve. Therefore, for those of looking for more of a challenge, I created a sequel to this challenge in which you must now count the number of unique rectangles. Check it out!

Now, for those of you looking to solve this challenge, here it comes.

Well, we don't really have a challenge like this yet, so here we go.

Consider this 3 x 3 grid of rectangles:

How many rectangles are there? Well, counting visually, we can see that there are actually 36 rectangles, including the entire plane itself, which are all shown in the animated GIF below:

The Task

The counting of rectangles as shown above is the task. In other words, given 2 integers greater than or equal to 0, m and n, where m represents the width and n represents the height, output the total number of rectangles in that m x n grid of rectangles.

Rules

The use of any built-ins that directly solve this problem is explicitly disallowed.

This challenge is not about finding the shortest answer, but finding the shortest answer in every language. Therefore, no answer will be accepted.

Standard loopholes are prohibited.

Test Cases

Presented in the format Array of Integers Input -> Integer Output:

```<code>[0,0] -> 0
[1,1] -> 1
[3,3] -> 36 (Visualized above)
[4,4] -> 100
[6,7] -> 588
</code>```

References

http://oeis.org/A096948

Remember, this is code-golf, so shortest code wins!

答:
C#, 19 bytes

```<code>(n,m)=>m*n*~m*~n/4;
</code>```

An anonymous function based off of @xnor's answer.

Title: How Many Rectangles in the Grid?

Body:
C#, 19 bytes

(n,m)=>m*n*~m*~n/4;

An anonymous function based off of @xnor's answer.


答:
Batch, 135 bytes

```<code>@set/an=%1,x=y=f=l=d=0,e=-1
:l
@set/ac=-e,e=d,d=c,n-=l+=f^^=1,x+=d*l,y+=e*l
@if %n% gtr 0 goto l
@set/ax+=d*n,y+=e*n
@echo %x%,%y%
</code>```

Explanation: Follows the spiral out from the centre. Each pass through the loop rotates the current direction d,e by 90° anticlockwise, then the length of the arm l is incremented on alternate passes via the flag f and the next corner is calculated in x,y, until we overshoot the total length n, at which point we backtrack and print the resulting co-ordinates.

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

Body:
Definition

The infinite spiral used in this question has 0 on the position (0,0), and continues like this:

```<code>16-15-14-13-12
 |           |
17  4--3--2 11
 |  |     |  |
18  5  0--1 10
 |  |        |
19  6--7--8--9
 |
20--21...
</code>```

It is to be interpreted as a Cartesian plane.

For example, 1 is on the position (1,0), and 2 is on the position (1,1).

Task

Given a non-negative integer, output its position in the spiral.

Specs

Your spiral can start with 1 instead of 0. If it starts with 1, please indicate so in your answer.

Output the two numbers in any sensible format.

Testcases

The testcases are 0-indexed but you can use 1-indexed as well.

```<code>input output
0     (0,0)
1     (1,0)
2     (1,1)
3     (0,1)
4     (-1,1)
5     (-1,0)
6     (-1,-1)
7     (0,-1)
8     (1,-1)
9     (2,-1)
100   (-5,5)
</code>```

Body:
Batch, 135 bytes

@set/an=%1,x=y=f=l=d=0,e=-1
:l
@set/ac=-e,e=d,d=c,n-=l+=f^^=1,x+=d*l,y+=e*l
@if %n% gtr 0 goto l
@set/ax+=d*n,y+=e*n
@echo %x%,%y%

Explanation: Follows the spiral out from the centre. Each pass through the loop rotates the current direction d,e by 90° anticlockwise, then the length of the arm l is incremented on alternate passes via the flag f and the next corner is calculated in x,y, until we overshoot the total length n, at which point we backtrack and print the resulting co-ordinates.


问:
My Squiggly Lamp
While moving, I broke my lamp. Now, I need a new one. It's your job to make me a lamp! I'm not sure what size I want, though I know I want a squiggly one.

Your program/function must take in a number input, and print out a lamp with that many squiggles/bumps.

Examples:

Input:2

Output:

```
/--\
 ()
 ()
/__\
```

Input:3

Output:

```
/--\
 ()
 ()
 ()
/__\
```

Input:5

Output:

```
/--\
 ()
 ()
 ()
 ()
 ()
/__\
```

Rules:

0 & negative numbers don't matter

To give the lamps (an this challenge) more of a variety, you must change the lamp shade.

They must be 4 characters wide and 1 character high.

They can be in any shape, including non-lamp-shade shapes.

They must not contain whitespace.

The base must stay the same.

You must show an example input & output with your lamp shade.

Shortest code wins!

答:
R, <s>54</s> <s>52</s> 46 bytes

```<code>cat("RRRR",rep(" ()",scan()),"/__\\",sep="\n")
</code>```

In this version, input and output are almost mixed together :

{in/out}PUT :

```<code>> cat("RRRR",rep(" ()",scan()),"/__\\",sep="\n")
1: 4
2:
Read 1 item
RRRR
 ()
 ()
 ()
 ()
/__\
</code>```

EDIT 1 : -2 bytes thanks to @manatwork comment.

EDIT 2 : -6 bytes. Full credit goes to @manatwork again

Title: My Squiggly Lamp

Body:
R, <s>54</s> <s>52</s> 46 bytes

cat("RRRR",rep(" ()",scan()),"/__\\",sep="\n")

In this version, input and output are almost mixed together :

{in/out}PUT :

> cat("RRRR",rep(" ()",scan()),"/__\\",sep="\n")
1: 4
2:
Read 1 item
RRRR
 ()
 ()
 ()
 ()
/__\

EDIT 1 : -2 bytes thanks to @manatwork comment.

EDIT 2 : -6 bytes. Full credit goes to @manatwork again


问:
Power modulo golf.
Write a function f(a,b,c) that calculates a^b (mod c) in less than 10 seconds.

a, b < 10^100

c < 10000.

examples:

```<code>f(10^50, 10^50, 54123) = 46555
f(5^99, 10^99, 777) = 1
</code>```

ContentLicense: CC BY-SA 2.5

Title: Power modulo golf.

Body:
Python - 5 chars

f=pow

Test

>>> f(10**50, 10**50, 54123)
46555L
>>> f(5**99, 10**99, 777)
1L


问:
Balance chemical equations!
Bernd is a high school student who has some problems in chemistry. In class he has to design chemical equations for some experiments they are doing, such as the combustion of heptane C7H16:

C7H16 + 11O2 → 7CO2 + 8H2O

Since mathematics isn't exactly Bernd's strongest subject, he often has a hard time finding the exact ratios between the pro- and educts of the reaction. Since you are Bernd's tutor, it is your job to help him! Write a program, that calculates the amount of each substance needed to get a valid chemical equation.

Input

The input is a chemical equation without amounts. In order to make this possible in pure ASCII, we write any subscriptions as ordinary numbers. Element names always start with a capital letter and may be followed by a minuscule. The molecules are separated with + signs, an ASCII-art arrow -> is inserted between both sides of the equation:

```<code>Al+Fe2O4->Fe+Al2O3
</code>```

The input is terminated with a newline and won't contain any spaces. If the input is invalid, your program may do whatever you like.

You may assume, that the input is never longer than 1024 characters. Your program may either read the input from standard input, from the first argument or in an implementation defined way at runtime if neither is possible.

Output

The output of your program is the input equation augmented with extra numbers. The number of atoms for each element must be the same on both sides of the arrow. For the example above, a valid output is:

```<code>2Al+Fe2O3->2Fe+Al2O3
</code>```

If the number for a molecule is 1, drop it. A number must always be a positive integer. Your program must yield numbers such that their sum is minimal. For instance, the following is illegal:

```<code>40Al+20Fe2O3->40Fe+20Al2O3
</code>```

If there is no solution, print

```<code>Nope!
</code>```

instead. A sample input that has no solution is

```<code>Pb->Au
</code>```

Testcases

Input->Output

```<code>C7H16+O2->CO2+H2O
C7H16+11O2->7CO2+8H2O

Al+Fe2O3->Fe+Al2O3
2Al+Fe2O3->2Fe+Al2O3

Pb->Au
Nope!
</code>```

This is code-golf, so shortest code wins!

Your program must terminate in reasonable time for all reasonable inputs

答:
Python 2, 879 bytes

import sys,re
from sympy.solvers import solve
from sympy import Symbol
from fractions import gcd
from collections import defaultdict

Ls=list('abcdefghijklmnopqrstuvwxyz')
eq=sys.argv[1]
Ss,Os,Es,a,i=defaultdict(list),Ls[:],[],1,1
for p in eq.split('->'):
 for k in p.split('+'):
  c = [Ls.pop(0), 1]
  for e,m in re.findall('([A-Z][a-z]?)([0-9]*)',k):
   m=1 if m=='' else int(m)
   a*=m
   d=[c[0],c[1]*m*i]
   Ss[e][:0],Es[:0]=[d],[[e,d]]
 i=-1
Ys=dict((s,eval('Symbol("'+s+'")')) for s in Os if s not in Ls)
Qs=[eval('+'.join('%d*%s'%(c[1],c[0]) for c in Ss[s]),{},Ys) for s in Ss]+[Ys['a']-a]
k=solve(Qs,*Ys)
if k:
 N=[k[Ys[s]] for s in sorted(Ys)]
 g=N[0]
 for a1, a2 in zip(N[0::2],N[1::2]):g=gcd(g,a2)
 N=[i/g for i in N]
 pM=lambda c: str(c) if c!=1 else ''
 print '->'.join('+'.join(pM(N.pop(0))+str(t) for t in p.split('+')) for p in eq.split('->'))
else:print 'Nope!'
```

Try it online!

Could be much less than 880, but my eyes are killing me already...

Title: Balance chemical equations!

Body:
Python 2, 879 bytes

import sys,re
from sympy.solvers import solve
from sympy import Symbol
from fractions import gcd
from collections import defaultdict

Ls=list('abcdefghijklmnopqrstuvwxyz')
eq=sys.argv[1]
Ss,Os,Es,a,i=defaultdict(list),Ls[:],[],1,1
for p in eq.split('->'):
 for k in p.split('+'):
  c = [Ls.pop(0), 1]
  for e,m in re.findall('([A-Z][a-z]?)([0-9]*)',k):
   m=1 if m=='' else int(m)
   a*=m
   d=[c[0],c[1]*m*i]
   Ss[e][:0],Es[:0]=[d],[[e,d]]
 i=-1
Ys=dict((s,eval('Symbol("'+s+'")')) for s in Os if s not in Ls)
Qs=[eval('+'.join('%d*%s'%(c[1],c[0]) for c in Ss[s]),{},Ys) for s in Ss]+[Ys['a']-a]
k=solve(Qs,*Ys)
if k:
 N=[k[Ys[s]] for s in sorted(Ys)]
 g=N[0]
 for a1, a2 in zip(N[0::2],N[1::2]):g=gcd(g,a2)
 N=[i/g for i in N]
 pM=lambda c: str(c) if c!=1 else ''
 print '->'.join('+'.join(pM(N.pop(0))+str(t) for t in p.split('+')) for p in eq.split('->'))
else:print 'Nope!'

<a href="https://tio.run/##bVLBbtswDL37K9QChaRYzmofNsyAOgxFgR7SBEVOnaCDaiuuGttyTTdbWuzbM8putm7YiTbfe@SjyG4/PPg2Oxxc0/l@ILAH0dto0/sGv5tuPwdf72wP5EgIv@/wY369b@59PQGb3hSD8@1vUVWUE1L4urZ/Y6XdmOd6KF0xRNECZO1gYNTcFwhUD@5xWzet7556GJ5333/sXyiP7JNEn3PTVzuV6mgNYgXiCoQRTr4rx0IpLhagci2UFqlIo43vSUdcS@zTHLraYavkgvI8IgHZBqQ7AvGYJwWRRC1g3vmOnXNBsCMZ2VY0gd/b@ca1palrRpn6mnzTyiQv@gtn6jz5rGeciu1YiDQyJW6DQVJKbA0W5QNreMDMTDYhllIV6lyLAiebNTMXmpE1KKtVjukrCEGqEidSVpQacSeTNLoDOc7MQNidQSvTQtgpjSGmp5xyPpqGYHkFwQeQ1g/hdwE8ugWpJmFM54/etYyelbMzoGcsWBHB1FShCBJ0BJqL15/iDt4VXoOO1R0oaqhOjI62crwXdgtihsQIu27xKZZSbQMNtP6jBbwGWzKk4UyVXGLDaSsmFcRkgfLiOob5PM@0WKo0RJ5XEs@LVcJkfKzsPlSjzAXFEmt0N7I2zX1pSJETGHpW8DB@cYLrGLdAKZJ63AUJx/A2/fEZuhu2fNs9j4N6mOYd/r2VKf2f48KDxS75W4el7@wJPRwOl5@u04/xKksuLldZfJ2tfgE" rel="nofollow noreferrer" title="Python 2 – Try It Online">Try it online!

Could be much less than 880, but my eyes are killing me already...


问:
Generate Linus Sequence

Definition

From the description on OEIS A006345:

To find a(n), consider either a 1 or a 2. For each, find the longest repeated suffix, that is, for each of a(n)=1,2, find the longest sequence s with the property that the sequence a(1),...,a(n) ends with ss. Use the digit that results in the shorter such suffix. a(1) = 1.

Worked-out Example

a(1)=1.

If a(2)=1, we will have the sequence 1 1 where the longest doubled substring from the end is 1. If a(2)=2 instead, then it would be the empty substring. Therefore a(2)=2.

When n=6, we choose between 1 2 1 1 2 1 and 1 2 1 1 2 2. In the first choice, 1 2 1 is doubled consecutively from the end. In the second choice, it is 2 instead. Therefore, a(6)=2.

When n=9, we choose between 1 2 1 1 2 2 1 2 1  and 1 2 1 1 2 2 1 2 2. In the first choice, the longest doubled consecutive substring is 2 1, while in the second choice 1 2 2 is doubled consecutively at the end. Therefore a(9)=1.

Task

Given n, return a(n).

Specs

n will be positive.

You can use 0-indexed instead of 1-indexed. In that case, please state so in your answer. Also, in that case, n can be 0 also.

Testcases

The testcases are 1-indexed. However, you can use 0-indexed.

```<code>n  a(n)
1  1
2  2
3  1
4  1
5  2
6  2
7  1
8  2
9  1
10 1
11 2
12 1
13 2
14 2
15 1
16 1
17 2
18 1
19 1
20 1
</code>```

References

WolframMathWorld

Obligatory OEIS A006345

Title: Generate Linus Sequence

Body:
JavaScript (ES6), 84

Index base 0

n=>eval("s='1';for(r=d=>(s+d).match(/(.*)\\1$/)[0].length;n--;s+=c)c=r(1)>r(2)?2:1")

Less golfed

n=>{
  r = d => (s+d).match(/(.*)\1$/)[0].length;
  c = '1';
  for(s = c; n--; s += c)
    c = r(1) > r(2) ? 2 : 1;
  return c;
}

Test

F=
n=>eval("s='1';for(r=d=>(s+d).match(/(.*)\\1$/)[0].length;n--;s+=c)c=r(1)>r(2)?2:1")

for(n=0;n<20;n++)console.log(n,F(n))


问:
Leo's Pokerface

Pokerface

Introduction

Leo enjoys playing poker, but his job at Tech Inc. is too demanding for him to learn how to play well. Leo, being a computer scientist, is not discouraged. He decides to take more time than it would have taken to just learn poker, and use it to write a poker bot to help him play better. But now Leo has a problem: in order to understand how to play a bit better, Leo needs to observe multiple games of multiple "people," but the "people" need different play styles to improve the quality and reality of the game.

The Challenge

Leo recalls that there is actually a website dedicated to programming challenges, and is enlisting your help! Your job is to write a program which plays "Pokerface" a modified version of 5-card poker. The program will take input as a 5-card hand in whatever format you wish, after which the program will output:

Exactly (case-sensitive) "true" "1" or "t" if the player wishes to exchange cards, any other non-empty output otherwise.

If true, list of indices of cards and/or card names the player wishes to exchange.

A single number between 0 and 3, which specifies how many additional cards the player wants.

Print out the hand the player wishes to use.

(See formatting below)

Pokerface rules

Since pokerface is a text-based adventure game, cards must be presented in a consistent way. Cards are represented by two character codes, the first character is the suit, and the second is the name of the card.

Cards:

2-9 = 2-9

10 = T

Jack = J

Queen = Q

King = K

Ace = A

Suits:

Spades = S

Clubs = C

Hearts = H

Diamond = D

So the ace of spades would be SA, the 10 of hearts is HT, the 4th of diamonds is D4, etc.

A single round of Pokerface consists of four steps:

The deck is reshuffled and a five card hand is dealt to each player.

Each player is given the chance to exchange as many cards as they want.

Each player is given the chance to gain up to three more cards.

Each player must reveal their best hand.

The best hand wins, and gains that player a point. In the event of a tie, both players get a point.

In a single game, ten rounds are played and the player with the most points wins and gains a single "win point." In the event of a tie, both players gain a win point.

Leo doesn't really have a large amount of money, so your bot can assume that this is a perfect world with no betting.

Hands

Hands are exactly 5 cards in length (initial input and final output).

Hands are ranked consistent with the rules described here.

Input / Output

Leo only knows Java, so your program must be executable via the Process API (command line), and use STDIN and STDOUT for input and output, respectively.

For each step of input and output detailed above, the input and output must each exist on one line.

There must be at least one trailing new line after the final output. (This is due to the way input is read from STDIN)

No extraneous input/output is allowed, other than trailing and leading spaces. The parser simply does not understand things like final_hand=... or draw 0.

When drawing, output is a single integer, when exchanging output is a list of integers and/or cards defined below, and when being dealt the original hand, output is a list of cards defined below.

All input/output numbers must be positive integers in base 10.

You may define the format for card input (see post format below).

True is defined as exactly "true," "1" or "t" and false is any other non-empty value.

During the exchange step:

Card indices must be output with at least one space between them (e.g. 3  4    0)

Card names must be output with at least one space between them (e.g. H4 S8)

Card names and indices may be mixed in the output (e.g. 0 H7 3 D3)

Trailing and leading spaces are allowed.

The input as a result of the player outputting the above will be formatted as specified by the bot.jlsc file, in the same order as requested

The number of cards a player wants to add to their hand can have leading and trailing spaces.

Hands must be output with at least one space between them (e.g. H4 D5  CA), trailing spaces and leading spaces are allowed.

Hands do not need to be output in proper order (e.g. H4 D4 C4 DA SA and H4 DA D4 SA C4 both represent 4, 4, 4, Ace, Ace, which is a full house).

If you wish to build a strategy by analyzing opponents hands, you may store data in a <botname>/data directory.

After competing bots have displayed their hands, they will be written to every bots data directory, in hands.txt, with each hand on a new line (separated by \n). The file will be encoded in US_ASCII.

After your bot requests new cards or exchange cards, the cards will be input depending on what format you specify in the bot.jlsc file.

Post Format

Every post must include two things:

The source code of your bot, or a link to a public facing repository.

A zip file containing:

The compiled/executable version of your bot (If the file is a .exe or other non-de-compilable file, please just include compilation instructions in your post).

A bot.jlsc file, see below (side note: the .jlsc extension is just because of a side project of mine, a configuration format. The file below matches the proper syntax, so don't worry).

The .zip file must be named the same as your bot.

If you don't have access to windows or some other zipping utility, or can't make a .zip for whatever reason, just include the text of the bot.jlsc file in your post

bot.jlsc file:

```<code>name= "Botty"
link= "example.com"
cmd= "java -jar Botty.jar"
input_hand= "${0} ${1} ${2} ${3} ${4}"
input_1= "${0}"
input_2= "${0} ${1}"
input_3= "${0} ${1} ${2}"
input_4= "${0} ${1} ${2} ${3}"
</code>```

Where:

"cmd" is the windows command line command to run your bot. Note that your bot will be in directory <botname>, so adjust the command accordingly.

"name" is the name of your bot.

"link" is the link to your answer, you'll have to edit this in after posting.

"input_hand" is how you want the original dealing to be formatted (with ${#} representing cards 0-4).

"input_1" is how you want the input of one additional card to be formatted.

"input_2" is how you want the input of two additional cards to be formatted.

"input_3" is how you want the input of three additional cards to be formatted.

"input_4" is how you want the input of four additional cards to be formatted.

Specifics

These loopholes are disallowed (see 'common pitfalls')

You may not write a bot the will always output the best hand possible, every time, within the rule set. (i.e. no long-running brute-force bots, nothing should be quite as 'good' as LeoBot)

Your bot should run in ~100 ms or less (Lenient on this point, max of ~1 second)

Any output of the bot after its chosen hand will be ignored.

Standard loopholes are disallowed.

Yes, I know linux is better, but I have a windows PC, so be sure the compiled/executable version of your program can be run from the windows command line.

I already have python and java installed on my computer, but I'm willing to update to new versions and install other environments, so please specify what type of environment your program requires.

You may not write a bot which does the same thing as another bot in every case. Spam bots are allowed, but discouraged.

Your bot may only use cards it has. Cards lost through exchange or not dealt to begin with are invalid output in the final hand.

Input and output may only contain ASCII characters.

Tournaments

Tournaments will be run when I get the time (my schedule is nearly as packed as Leo's, so this my be a little infrequent. Sorry for the inconvenience.).

Bots will be pit against eachother in 4 person games, and there will be one game for each possible subset of bots (i.e. lots of games).

This process will be repeated five times.

Due to the way the tournament handler makes the groups of bots, up to three filler bots will be added to make the number of bots divisible by 4. These bots will simply return the hand they were originally dealt.

After every round and game is run, the scores of the bots will be computed based on the number games they won.

Multiple bots can share a position (ties for first won by first posted).

After a tournament finishes, the scores will be appended to the bottom of this post.

Scoring

Normal KoTH rules. The bot(s) that win the most games win the challenge.

LeoBot

Leo's bot is pretty smart. It doesn't exchange any cards, that's too hard, but it does request the maximum number of additional cards, and it determines the best possible hand it can make, and plays that hand. The main logic of leobot is below.

```<code>package com.gmail.socraticphoenix.pokerface.leobot;

import com.gmail.socraticphoenix.pokerface.lib.card.Card;
import com.gmail.socraticphoenix.pokerface.lib.card.Deck;
import com.gmail.socraticphoenix.pokerface.lib.rule.HandRegistry;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class LeoBot {

    public static void main(String[] args) {
        List<Card> hand = new ArrayList<>();

        Scanner scanner = new Scanner(System.in);
        hand.addAll(Card.parseHand(scanner.nextLine()));
        System.out.println(false);

        System.out.println(3);
        hand.addAll(Card.parseHand(scanner.nextLine()));

        List<List<Card>> possibleHands = LeoBot.getSubsets(hand, 5);
        System.out.println(Deck.toString(possibleHands.stream().sorted((a, b) -> HandRegistry.determineWinner(b, a).comparable()).findFirst().get()));
    }

    private static <T> void getSubsets(List<T> superSet, int k, int idx, List<T> current, List<List<T>> solution) {
        if (current.size() == k) {
            solution.add(new ArrayList<>(current));
            return;
        }
        if (idx == superSet.size()) return;
        T x = superSet.get(idx);
        if (!current.contains(x)) {
            current.add(x);
        }
        getSubsets(superSet, k, idx + 1, current, solution);
        current.remove(x);
        getSubsets(superSet, k, idx + 1, current, solution);
    }

    public static <T> List<List<T>> getSubsets(List<T> superSet, int k) {
        List<List<T>> res = new ArrayList<>();
        getSubsets(superSet, k, 0, new ArrayList<T>(), res);
        return res;
    }

}
</code>```

Note that if LeoBot consistently wins the tournaments, and there are a good amount of entries, I'll stop including him in the running.

Important Links

Tournament bot and library

Leo's bot

Disclaimer

Leo and Tech Inc. are story elements and any resemblance to real-life companies or people is purely unintentional. (However, when Leo's 'situation' adds or subtracts conditions from the question, those are actually part of the question...)

答:
Plumber, Python

Plumber is all about flushes. Plumber also prioritises higher value cards (meaning he can sometimes get straight flushes, especially royal ones (should they occur).) Plumber is pretty much messed if he doesn't get a flush, except that he might be lucky enough for a straight. Plumber will get flushes about 20% of the time, if calculations by Sherlock9 are correct

```<code>hand=input().split()
suit_in_hand={"S":0,"C":0,"D":0,"H":0}
card_values={"2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8,
             "9":9, "T":10, "J":11, "Q":12, "K":13, "A":14,}
def value_sort(x):
    return card_values[x[1]]
def suit_sort(x):
    return suit_in_hand[x[0]]

for card in hand:
    suit_in_hand[card[0]]+=1

hand.sort(key=suit_sort, reverse=True)

print(" ".join(hand[suit_in_hand[hand[0][0]]:]))
hand=hand[:suit_in_hand[hand[0][0]]]

for new_card in input().split():
    hand+=[new_card]
    suit_in_hand[new_card[0]]+=1

print(3)

for new_card in input().split():
    hand+=[new_card]
    suit_in_hand[new_card[0]]+=1
hand.sort(key=value_sort, reverse=True)
hand.sort(key=suit_sort, reverse=True)
print(" ".join(hand[:5]))
</code>```

Also takes input separated by spaces like other my two bots

Title: Leo's Pokerface

Body:
Plumber, Python

Plumber is all about flushes. Plumber also prioritises higher value cards (meaning he can sometimes get straight flushes, especially royal ones (should they occur).) Plumber is pretty much messed if he doesn't get a flush, except that he might be lucky enough for a straight. Plumber will get flushes about 20% of the time, if calculations by Sherlock9 are correct

hand=input().split()
suit_in_hand={"S":0,"C":0,"D":0,"H":0}
card_values={"2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8,
             "9":9, "T":10, "J":11, "Q":12, "K":13, "A":14,}
def value_sort(x):
    return card_values[x[1]]
def suit_sort(x):
    return suit_in_hand[x[0]]

for card in hand:
    suit_in_hand[card[0]]+=1

hand.sort(key=suit_sort, reverse=True)

print(" ".join(hand[suit_in_hand[hand[0][0]]:]))
hand=hand[:suit_in_hand[hand[0][0]]]

for new_card in input().split():
    hand+=[new_card]
    suit_in_hand[new_card[0]]+=1

print(3)

for new_card in input().split():
    hand+=[new_card]
    suit_in_hand[new_card[0]]+=1
hand.sort(key=value_sort, reverse=True)
hand.sort(key=suit_sort, reverse=True)
print(" ".join(hand[:5]))

Also takes input separated by spaces like other my two bots


问:
Forecast Palindromic Dates
Palindromic dates are dates that appear as palindromes: the string of digits can be read the same way backwards as forwards. For the North American date format (MM/DD/YYYY), the next few palindromic dates are:

02/02/2020

12/02/2021

03/02/2030

The Challenge

Create a function that returns all palindromic dates in a consistent, common date format (of your choosing) that fall within a range of dates (edit: including the range itself).

Rules

To qualify as a palindrome, only the numeric characters of the date should be
checked.

The date can be in any common format (MM/DD/YYYY, DD-MM-YYYY), as
long as it uses two digits for both the month and day and four for
the year, and it uses a character to separate parts of the date. The output must preserve seperating characters (/, -, etc.). Your function only needs to handle one distinct date format. Please include the format in your answer.

If there are more than one dates returned, they should be comma or
new-line separated.

Shortest answer wins!

Example

```<code>date_palindrome('05/02/2050', '12/12/2060')
>>>['05/02/2050', '06/02/2060']
</code>```

答:
VBA, 240 193 bytes

```<code>Function f(a, b)
Dim j, g()
For i = CDate(a) To CDate(b)
    If Format(i, "yyyy") = StrReverse(Format(i, "mmdd")) Then
        ReDim Preserve g(j)
        g(j) = Format(i, "yyyy-mm-dd")
        j = j + 1
    End If
Next
f = g()
End Function
</code>```

That's it in a comprehensible format. Test case:

```<code>Sub e()
MsgBox Join(f("5/2/2050", "6/2/2060"), ", ")
End Sub
</code>```

Without that much redundancy:

```<code>Function f(a,b)
Dim j, g()
For i=CDate(a) To CDate(b)
If Format(i,"yyyy")=StrReverse(Format(i,"mmdd")) Then
ReDim Preserve g(j)
g(j)=Format(i,"yyyy-mm-dd")
j=j+1
End If
Next
f=g()
End Function
</code>```

Title: Forecast Palindromic Dates

Body:
VBA, 240 193 bytes

Function f(a, b)
Dim j, g()
For i = CDate(a) To CDate(b)
    If Format(i, "yyyy") = StrReverse(Format(i, "mmdd")) Then
        ReDim Preserve g(j)
        g(j) = Format(i, "yyyy-mm-dd")
        j = j + 1
    End If
Next
f = g()
End Function

That's it in a comprehensible format. Test case:

Sub e()
MsgBox Join(f("5/2/2050", "6/2/2060"), ", ")
End Sub

Without that much redundancy:

Function f(a,b)
Dim j, g()
For i=CDate(a) To CDate(b)
If Format(i,"yyyy")=StrReverse(Format(i,"mmdd")) Then
ReDim Preserve g(j)
g(j)=Format(i,"yyyy-mm-dd")
j=j+1
End If
Next
f=g()
End Function


Title: Hofstadter H-sequence

Body:
Retina, <s>49</s> 43 bytes

.+
$*1:
{`^1(1*):
$1:::-1$1
}`^:*(1*)-\1

1

Try it online!


问:
Create and write to a file

Challenge

Create a new file and write the string Hello World to it.

Restrictions

Your challenge must write to a file on disk, in the file system.

The file may not be a log file generated during normal operation of the interpreter.

The file must contain only the string Hello World. It is allowed to contain a trailing newline or minimal whitespace. No other content.

No command-line flags/pipes (etc) allowed, except when necessary to run the program. (e.g. perl -p)

Notes

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

Follow the spirit, not the letter, of the rules.

答:
C#, 50 bytes

```<code>s=>System.IO.File.WriteAllText("f","Hello World");
</code>```

An anonymous function that takes in an unused argument and outputs the file.

Alternatively and cheating slightly this one:

```<code>s=>System.IO.File.WriteAllText("f",s);
</code>```

That takes in a string and works assuming the string contains the text: Hello World, for 38 bytes.

Title: Create and write to a file

Body:
C#, 50 bytes

s=>System.IO.File.WriteAllText("f","Hello World");

An anonymous function that takes in an unused argument and outputs the file.

Alternatively and cheating slightly this one:

s=>System.IO.File.WriteAllText("f",s);

That takes in a string and works assuming the string contains the text: Hello World, for 38 bytes.


答:
Lua, 28 Bytes

Takes input in the form of a command-line argument and outputs via its return value. Even if it uses a return statement, it is still a full program :).

return("="):rep(...).."(:)-"
```

Title: Snakes all around

Body:
Challenge

The challenge is simple: print a snake.

You will get the length of the snake as input.

A snake of length 2 looks like this:

```<code>==(:)-
</code>```

A snake of length 7 looks like this:

```<code>=======(:)-
</code>```

In other words, the length of a snake is how many equal signs are before the head.

Usage

Let's say I made a C++ implementation and compiled it to ./getsnake.

I could run it like so:

```<code>$ ./getsnake 10
==========(:)-
</code>```

Clarifications

Standard loopholes are disallowed.

You can get input and output in any acceptable way.

You can assume all inputs given are positive integers.

You may write a function instead of a regular program.


Title: Hofstadter H-sequence

Body:
Golfscript, <s>26</s> 25 bytes

<s>~[0]{....,(===\.,@-+}@*)\;</s>
~[0]{...)\;==\.,@-+}@*)\;

Try it online!

Locally 10000 takes less than half a second.


问:
Print this diamond
This question has been spreading like a virus in my office. There are quite a variety of approaches:

Print the following:

```<code>        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1
</code>```

Answers are scored in characters with fewer characters being better.

答:
Perl, 43+1

adding +1 for -E which is required for say

say$"x(9-$_).(1x$_)**2for 1..9,reverse 1..8

edit: shortened a bit

Title: Print this diamond


Title: Snakes all around

Body:
LiveScript, 15 bytes

->'='*it+'(:)-'


答:
BASIC, 30 bytes

Let's keep it simple in BASIC.  QB64 and TRS-80 Extended Color BASIC both tie, since TRS-80 needs a line number but doesn't need the space after INPUT, and it won't let you use INPUT in immediate mode.  One liners are rare on a 32x16 screen.

TRS-80: (should also work on Microsoft GW-BASIC/BASICA)

```<code>0INPUTL:?STRING$(L,"=");"(:)-"
</code>```

QB64:

```<code>INPUT L:?STRING$(L,"=");"(:)-"
</code>```

Title: Snakes all around

Body:
BASIC, 30 bytes

Let's keep it simple in BASIC.  QB64 and TRS-80 Extended Color BASIC both tie, since TRS-80 needs a line number but doesn't need the space after INPUT, and it won't let you use INPUT in immediate mode.  One liners are rare on a 32x16 screen.

TRS-80: (should also work on Microsoft GW-BASIC/BASICA)

0INPUTL:?STRING$(L,"=");"(:)-"

QB64:

INPUT L:?STRING$(L,"=");"(:)-"


问:
Number of cycles of a permutation
Consider a permutation of the integers 1, ..., n, such as this one for n = 6:

```<code>[5,2,4,3,6,1]
</code>```

If you view the permutation as a mapping from [1,2,3,4,5,6] to [5,2,4,3,6,1], the permutation can be decomponsed into disjoint cycles. A cycle is a subset of elements that map to each other. For example, 1 gets mapped to 5, which gets mapped to 6, which gets mapped back to 1. So one cycle is [1,5,6]. The other cycles are [2] and [3,4]. Thus the number of cycles for this permutation is 3.

In general, the cycles of a permutation are unique (up to order), and the number of cycles for a permutation of size n varies from 1 to n.

The challenge

Given a non-empty permutation, output its number of cycles.

Input is an array formed by the n integers 1, 2, ..., n, where n > 0. Each integer occurs exactly once. The order in which they appear defines the permutation, as in the example above.

Instead of an array you can use a list, a string with a separator between the numbers, a separate input for each number, or anything that's reasonable.

For a permutation of size n, instead of the 1-based set of integers 1, ..., n you can consistently use the 0-based set 0, ..., n-1. If so, please indicate it in your answer.

The code should work for n up to 20 in a reasonable time, say less than one minute.

Code golf. All builtins allowed.

Test cases

This assumes 1-based, array input.

```<code> [1] -> 1
 [3,2,1] -> 2
 [2,3,4,5,1] -> 1
 [5,2,4,3,6,1] -> 3
 [8,6,4,5,2,1,7,3] -> 2
 [4,5,11,12,7,1,3,9,10,6,8,2] -> 1
 [4,2,5,11,12,7,1,3,9,10,6,8] -> 5
 [5,8,6,18,16,9,14,10,11,12,4,20,15,19,2,17,1,13,7,3] -> 3
 [14,5,17,15,10,18,1,3,4,13,11,16,2,12,9,7,20,6,19,8] -> 7
</code>```

Related

This related challenge asks for the actual cycles of the permutation, not the number of them. Requiring only the number of cycles can lead to shorter algorithms that sidestep generating the actual cycles.

答:
JavaScript (ES6), 49 bytes

```<code>a=>a.reduce(g=(c,e,i)=>e<i?g(c,a[e],i):c+=e==i,0)
</code>```

Uses zero-based indexing. Explanation: reduce is used to invoke the inner function g on each element of the array. c is the count of cycles, e is the array element, i is the array index. If the element is less than the index, then it's a potential cycle - the element is used to index into the array to find the next element in the cycle recursively. If we started out or end up with the original index then this is a new cycle and we increment the cycle count. If at any point we find a value larger than the index then we'll count that cycle later.

Title: Number of cycles of a permutation

Body:
JavaScript (ES6), 49 bytes

a=>a.reduce(g=(c,e,i)=>e<i?g(c,a[e],i):c+=e==i,0)

Uses zero-based indexing. Explanation: reduce is used to invoke the inner function g on each element of the array. c is the count of cycles, e is the array element, i is the array index. If the element is less than the index, then it's a potential cycle - the element is used to index into the array to find the next element in the cycle recursively. If we started out or end up with the original index then this is a new cycle and we increment the cycle count. If at any point we find a value larger than the index then we'll count that cycle later.


答:
C, 90 bytes

Call f() with a mutable int array, 1 based indexing. The second parameter is the size of the array. The function returns the number of cycles.

```<code>i,j,c;f(a,n)int*a;{for(c=i=0;i<n;++i)for(j=0,c+=!!a[i];a[i];a[i]=0,i=j-1)j=a[i];return c;}
</code>```

Try it on ideone.

The algorithm:

```<code>For each index
    If index is non-zero
        Increment counter
        Traverse the cycle, replacing each index in it with 0.
</code>```

Title: Number of cycles of a permutation

Body:
Consider a permutation of the integers 1, ..., n, such as this one for n = 6:

```<code>[5,2,4,3,6,1]
</code>```

If you view the permutation as a mapping from [1,2,3,4,5,6] to [5,2,4,3,6,1], the permutation can be decomponsed into disjoint cycles. A cycle is a subset of elements that map to each other. For example, 1 gets mapped to 5, which gets mapped to 6, which gets mapped back to 1. So one cycle is [1,5,6]. The other cycles are [2] and [3,4]. Thus the number of cycles for this permutation is 3.

In general, the cycles of a permutation are unique (up to order), and the number of cycles for a permutation of size n varies from 1 to n.

The challenge

Given a non-empty permutation, output its number of cycles.

Input is an array formed by the n integers 1, 2, ..., n, where n > 0. Each integer occurs exactly once. The order in which they appear defines the permutation, as in the example above.

Instead of an array you can use a list, a string with a separator between the numbers, a separate input for each number, or anything that's reasonable.

For a permutation of size n, instead of the 1-based set of integers 1, ..., n you can consistently use the 0-based set 0, ..., n-1. If so, please indicate it in your answer.

The code should work for n up to 20 in a reasonable time, say less than one minute.

Code golf. All builtins allowed.

Test cases

This assumes 1-based, array input.

```<code> [1] -> 1
 [3,2,1] -> 2
 [2,3,4,5,1] -> 1
 [5,2,4,3,6,1] -> 3
 [8,6,4,5,2,1,7,3] -> 2
 [4,5,11,12,7,1,3,9,10,6,8,2] -> 1
 [4,2,5,11,12,7,1,3,9,10,6,8] -> 5
 [5,8,6,18,16,9,14,10,11,12,4,20,15,19,2,17,1,13,7,3] -> 3
 [14,5,17,15,10,18,1,3,4,13,11,16,2,12,9,7,20,6,19,8] -> 7
</code>```

Related

This related challenge asks for the actual cycles of the permutation, not the number of them. Requiring only the number of cycles can lead to shorter algorithms that sidestep generating the actual cycles.

Body:
C, 90 bytes

Call f() with a mutable int array, 1 based indexing. The second parameter is the size of the array. The function returns the number of cycles.

i,j,c;f(a,n)int*a;{for(c=i=0;i<n;++i)for(j=0,c+=!!a[i];a[i];a[i]=0,i=j-1)j=a[i];return c;}

Try it on ideone.

The algorithm:

For each index
    If index is non-zero
        Increment counter
        Traverse the cycle, replacing each index in it with 0.


问:
Which finite abelian group is this?

Description

Write a function f(m, G) that accepts as its arguments a mapping m, and a set/list of distinct, non-negative integers G.

m should map pairs of integers in G to new integers in G. (G, m) is guaranteed to form a finite abelian group, but any element of G may be the identity.

There is an important theorem that says:

[Each finite abelian group] is isomorphic to a direct product of cyclic groups of prime power order.

f must return a list of prime powers [p1, ... pn] in ascending order such that

Examples

f((a, b) → (a+b) mod 4, [0, 1, 2, 3]) should return [4], as the parameters describe the group Z4.

f((a, b) → a xor b, [0, 1, 2, 3]) should return [2, 2], as the parameters describe a group isomorphic to Z2 × Z2.

f((a, b) → a, [9]) should return [], as the parameters describe the trivial group; i.e., the product of zero cyclic groups.

Define m as follows:

```<code>(a, b) → (a mod 3 + b mod 3) mod 3
       + ((floor(a / 3) + floor(b / 3)) mod 3) * 3
       + ((floor(a / 9) + floor(b / 9)) mod 9) * 9
</code>```

Then f(m, [0, 1, ..., 80]) should return [3, 3, 9], as this group is isomorphic to Z3 × Z3 × Z9

Rules

m may either be a function (or function pointer to some function) Int × Int → Int, or a dictionary mapping pairs in G × G to new elements of G.

f may take its parameters in the opposite order, i.e. you may also implement f(G, m).

Your implementation should theoretically work for arbitrarily large inputs, but need not actually be efficient.

There is no limitation on using built-ins of any kind.

Standard code-golf rules apply. Shortest code in bytes wins.

Leaderboard

For your score to appear on the board, it should be in this format:

```<code># Language, Bytes
</code>```

var QUESTION_ID=67252,OVERRIDE_USER=3852;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

```

答:
GAP, <s>159</s> 111 bytes

GAP allows us to simply construct a group by a multiplication table and compute its abelian invariants:

```<code>ai:=    # the golfed version states the function w/o assigning it
function(m,G)
  local t;
  t:=List(G,a->List(G,b->Position(G,m(a,b))));
  # t is inlined in the golfed version
  return AbelianInvariants(GroupByMultiplicationTable(t));
end;
</code>```

The old version

The finitely presented group with generators G and relations a*b=m(a,b) (for all a, b from G) is the group (G,m) we started with. We can create it and compute its abelian invariants with GAP:

```<code>ai:=    # the golfed version states the function w/o assigning it
function(m,G)
  local F,n,rels;
  n:=Size(G);
  F:=FreeGroup(n);
  rels:=Union(Set([1..n],i->
                Set([1..n],j->
                  F.(i)*F.(j)/F.(Position(G,m(G[i],G[j]))) ) ));
  # rels is inlined in the golfed version
  return AbelianInvariants(F/rels);
end;
</code>```

Examples

```<code>m1:=function(a,b) return (a+b) mod 4; end;
# I don't feel like implementing xor
m3:=function(a,b) return 9; end;
m4:=function(a,b)
  return (a+b) mod 3 # no need for inner mod
         + ((QuoInt(a,3)+QuoInt(b,3)) mod 3) * 3
         + ((QuoInt(a,9)+QuoInt(b,9)) mod 9) * 9;
  end;
</code>```

Now we can do:

```<code>gap> ai(m1,[0..3]);
[ 4 ]
</code>```

Actually, we are not restricted to using lists of integers. Using the correct domain, we can just use the general plus:

```<code>ai(\+,List(Integers mod 4));
[ 4 ]
</code>```

So I can essentially do the second example using that its group is isomorphic to the additive group of the 2 dimensional vector space over the field with 2 elements:

```<code>gap> ai(\+,List(GF(2)^2));
[ 2, 2 ]
</code>```

And the remaining examples:

```<code>gap> ai(m3,[9]);
[  ]
gap> ai(m4,[0..80]);
[ 3, 3, 9 ]
</code>```

Additional remarks

In the old version, m did not need to define a group composition for G. If m(a,b)=m(a,c), that just says that b=c. So we could do ai(m1,[0..5]) and ai(m3,[5..15]). The new version will fail horrible in these cases, as will both versions if m returns values that are not in G.

If (G,m) is not abelian, we get a description of the abelianized version of it, that is its biggest abelian factor group:

```<code>gap> ai(\*,List(SymmetricGroup(4)));
[ 2 ]
</code>```

This is what AbelianInvariants is usually used for, we would normally just call AbelianInvariants(SymmetricGroup(4)).

The golfed version

```<code>function(m,G)return AbelianInvariants(GroupByMultiplicationTable(List(G,a->List(G,b->Position(G,m(a,b))))));end
</code>```

Title: Which finite abelian group is this?

Body:
GAP, <s>159</s> 111 bytes

GAP allows us to simply construct a group by a multiplication table and compute its abelian invariants:

ai:=    # the golfed version states the function w/o assigning it
function(m,G)
  local t;
  t:=List(G,a->List(G,b->Position(G,m(a,b))));
  # t is inlined in the golfed version
  return AbelianInvariants(GroupByMultiplicationTable(t));
end;

The old version

The finitely presented group with generators G and relations a*b=m(a,b) (for all a, b from G) is the group (G,m) we started with. We can create it and compute its abelian invariants with GAP:

ai:=    # the golfed version states the function w/o assigning it
function(m,G)
  local F,n,rels;
  n:=Size(G);
  F:=FreeGroup(n);
  rels:=Union(Set([1..n],i->
                Set([1..n],j->
                  F.(i)*F.(j)/F.(Position(G,m(G[i],G[j]))) ) ));
  # rels is inlined in the golfed version
  return AbelianInvariants(F/rels);
end;

Examples

m1:=function(a,b) return (a+b) mod 4; end;
# I don't feel like implementing xor
m3:=function(a,b) return 9; end;
m4:=function(a,b)
  return (a+b) mod 3 # no need for inner mod
         + ((QuoInt(a,3)+QuoInt(b,3)) mod 3) * 3
         + ((QuoInt(a,9)+QuoInt(b,9)) mod 9) * 9;
  end;

Now we can do:

gap> ai(m1,[0..3]);
[ 4 ]

Actually, we are not restricted to using lists of integers. Using the correct domain, we can just use the general plus:

ai(\+,List(Integers mod 4));
[ 4 ]

So I can essentially do the second example using that its group is isomorphic to the additive group of the 2 dimensional vector space over the field with 2 elements:

gap> ai(\+,List(GF(2)^2));
[ 2, 2 ]

And the remaining examples:

gap> ai(m3,[9]);
[  ]
gap> ai(m4,[0..80]);
[ 3, 3, 9 ]

Additional remarks

In the old version, m did not need to define a group composition for G. If m(a,b)=m(a,c), that just says that b=c. So we could do ai(m1,[0..5]) and ai(m3,[5..15]). The new version will fail horrible in these cases, as will both versions if m returns values that are not in G.

If (G,m) is not abelian, we get a description of the abelianized version of it, that is its biggest abelian factor group:

gap> ai(\*,List(SymmetricGroup(4)));
[ 2 ]

This is what AbelianInvariants is usually used for, we would normally just call AbelianInvariants(SymmetricGroup(4)).

The golfed version

function(m,G)return AbelianInvariants(GroupByMultiplicationTable(List(G,a->List(G,b->Position(G,m(a,b))))));end


答:
PowerShell v2+, 56 bytes

```<code>$a={$n=$args[0];if($n){$n-(&$a(&$a(&$a($n-1))))}else{0}}
</code>```

The PowerShell equivalent of a lambda to form the recursive definition. Execute it via the & call operator, e.g. &$a(5). Takes a long time to execute -- even 50 on my machine (a recent i5 with 8GB RAM) takes around 90 seconds.

Faster iterative solution, 59 bytes

```<code>param($n)$o=,0;1..$n|%{$o+=$_-$o[$o[$o[$_-1]]]};$o[-1]*!!$n
</code>```

Longer only because we need to account for input 0 (that's the *!!$n at the end). Otherwise we just iteratively construct the array up to $n, adding a new element each time, and output the last one at the end $o[-1]. Super-speedy -- calculating 10000 on my machine takes about 5 seconds.

Title: Hofstadter H-sequence

Body:
Definition

\$a(0) = 0\$

\$a(n) = n-a(a(a(n-1)))\$ for integer \$n > 0\$

Task

Given non-negative integer \$n\$, output \$a(n)\$.

Testcases

```<code>n     a(n)
0     0
1     1
2     1
3     2
4     3
5     4
6     4
7     5
8     5
9     6
10    7
11    7
12    8
13    9
14    10
15    10
16    11
17    12
18    13
19    13
20    14
10000 6823
</code>```

References

WolframMathWorld

OEIS A005374

Body:
PowerShell v2+, 56 bytes

$a={$n=$args[0];if($n){$n-(&$a(&$a(&$a($n-1))))}else{0}}

The PowerShell equivalent of a lambda to form the recursive definition. Execute it via the & call operator, e.g. &$a(5). Takes a long time to execute -- even 50 on my machine (a recent i5 with 8GB RAM) takes around 90 seconds.

Faster iterative solution, 59 bytes

param($n)$o=,0;1..$n|%{$o+=$_-$o[$o[$o[$_-1]]]};$o[-1]*!!$n

Longer only because we need to account for input 0 (that's the *!!$n at the end). Otherwise we just iteratively construct the array up to $n, adding a new element each time, and output the last one at the end $o[-1]. Super-speedy -- calculating 10000 on my machine takes about 5 seconds.


问:
Print numbers from 1 to 10
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

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

Leaderboard

var QUESTION_ID=86075,OVERRIDE_USER=42570;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+)(?=[^\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

```

Title: Print numbers from 1 to 10

Body:
K,  5 Bytes

    1+!10
1 2 3 4 5 6 7 8 9 10

Explanation;

!2    --> 0 1
!5    --> 0 1 2 3 4
!10   --> 0 1 2 3 4 5 6 7 8 9
1+!10 --> 1 2 3 4 5 6 7 8 9 10


答:
><>, 55+2 = 57 bytes

```<code>^~n;
.~-]{:0$
v>1-}32[
v/  /:1-32[
>$:?/$~]{:0$.
/30@2[
</code>```

The input is expected to be present on the stack at program start, so +2 bytes for the -v flag. Try it online!

This is hecka slow, as it uses recursion to calculate the result. Using TIO, h(50) takes over a minute. It returns the correct results <= 30, so I'm confident it would work for h(10000), I just haven't run it to find out!

Title: Hofstadter H-sequence

Body:
><>, 55+2 = 57 bytes

^~n;
.~-]{:0$
v>1-}32[
v/  /:1-32[
>$:?/$~]{:0$.
/30@2[

The input is expected to be present on the stack at program start, so +2 bytes for the -v flag. Try it online!

This is hecka slow, as it uses recursion to calculate the result. Using TIO, h(50) takes over a minute. It returns the correct results <= 30, so I'm confident it would work for h(10000), I just haven't run it to find out!


答:
C#, 54 bytes

```<code>n=>{for(int i=1;i<11;)System.Console.Write(i+++" ");};
</code>```

Title: Print numbers from 1 to 10

Body:
This might be a very simple challenge, but I am surprised it hasn't been done on code-golf yet:

Print all Integers from 1 to 10 inclusive in ascending order to standard output.

Your output format can be whatever your language supports. This includes arbitrary separators (commas, semicolons, newlines, combinations of those, etc., but no digits), and prefixes and postfixes (like [...]). However, you may not output any other numbers than 1 through 10. Your program may not take any input. Standard loopholes are disallowed.

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

Leaderboard

var QUESTION_ID=86075,OVERRIDE_USER=42570;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+)(?=[^\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:
C#, 54 bytes

n=>{for(int i=1;i<11;)System.Console.Write(i+++" ");};


答:
Javascript, <s>129</s>* 126

```<code>for(i=1;i<18;i++){s="";a=Math.abs(9-i);for(j=0;j<a;j++)s+=" ";for(k=a+1;k<=9;k++)s+=k-a;for(l=8;l>a;l--)s+=l-a;console.log(s)}
</code>```

Includes suggestion from Shmiddty in comments. Original preserved below:

```<code>for(i=1;i<18;i++){s="";a=Math.abs(9-i);for(j=0;j<a;j++){s+=" "}for(k=a+1;k<=9;k++){s+=k-a}for(l=8;l>a;l--){s+=l-a}console.log(s)}
</code>```

I'm sure this could be condensed further, but darned if I know how. :P

Title: Print this diamond

Body:
This question has been spreading like a virus in my office. There are quite a variety of approaches:

Print the following:

```<code>        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1
</code>```

Answers are scored in characters with fewer characters being better.

Body:
Javascript, <s>129</s>* 126

for(i=1;i<18;i++){s="";a=Math.abs(9-i);for(j=0;j<a;j++)s+=" ";for(k=a+1;k<=9;k++)s+=k-a;for(l=8;l>a;l--)s+=l-a;console.log(s)}

Includes suggestion from Shmiddty in comments. Original preserved below:

for(i=1;i<18;i++){s="";a=Math.abs(9-i);for(j=0;j<a;j++){s+=" "}for(k=a+1;k<=9;k++){s+=k-a}for(l=8;l>a;l--){s+=l-a}console.log(s)}

I'm sure this could be condensed further, but darned if I know how. :P


问:
Szekeres's sequence

Definition

\$a(1) = 1\$

\$a(2) = 2\$

\$a(n)\$ is smallest number \$k>a(n-1)\$ which avoids any 3-term arithmetic progression in \$a(1), a(2), ..., a(n-1), k\$.

In other words, \$a(n)\$ is the smallest number \$k>a(n-1)\$ such that there does not exist \$x, y\$ where \$0<x<y<n\$ and \$a(y)-a(x) = k-a(y)\$.

Worked out example

For \$n=5\$:

We have \$a(1), a(2), a(3), a(4) = 1, 2, 4, 5\$

If \$a(5)=6\$, then \$2, 4, 6\$ form an arithmetic progression.

If \$a(5)=7\$, then \$1, 4, 7\$ form an arithmetic progression.

If \$a(5)=8\$, then \$2, 5, 8\$ form an arithmetic progression.

If \$a(5)=9\$, then \$1, 5, 9\$ form an arithmetic progression.

If \$a(5)=10\$, no arithmetic progression can be found.

Therefore \$a(5)=10\$.

Task

Given \$n\$, output \$a(n)\$.

Specs

\$n\$ will be a positive integer.

You can use 0-indexed instead of 1-indexed, in which case \$n\$ can be \$0\$. Please state it in your answer if you are using 0-indexed.

Scoring

Since we are trying to avoid 3-term arithmetic progression, and 3 is a small number, your code should be as small (i.e. short) as possible, in terms of byte-count.

Testcases

The testcases are 1-indexed. You can use 0-indexed, but please specify it in your answer if you do so.

```<code>1     1
2     2
3     4
4     5
5     10
6     11
7     13
8     14
9     28
10    29
11    31
12    32
13    37
14    38
15    40
16    41
17    82
18    83
19    85
20    86
10000 1679657
</code>```

References

WolframMathWorld

OEIS A003278

答:
Python 3, 113 bytes

def f(n):
 i=1;a=[]
 for _ in range(n):
  while any(i+x in[y*2for y in a]for x in a):i+=1
  a+=[i]
 return a[n-1]
```

Ideone it!

Title: Szekeres's sequence

Body:
Python 3, 113 bytes

def f(n):
 i=1;a=[]
 for _ in range(n):
  while any(i+x in[y*2for y in a]for x in a):i+=1
  a+=[i]
 return a[n-1]

Ideone it!


问:
Sum It Up with a Digital Triangle
Well, sum it down really.

Write a program or function that takes in a nonempty list of decimal integers (0-9) and outputs a downward pointing "triangle" of digits with the input list at the top where every digit after the first line is the sum of the two digits above it modulo 10.

For example, the input [7, 5, 0, 9] has output

```<code>7 5 0 9
 2 5 9
  7 4
   1
</code>```

because 2 is (7 + 5) mod 10, 5 is (5 + 0) mod 10, 9 is (0 + 9) mod 10, etc. all the way to 1 being (7 + 4) mod 10.

If the list has only one item, then the output matches the input; e.g. an input of [4] will yield

```<code>4
</code>```

Here are some additional examples:

```<code>[0]

0

[1, 2]

1 2
 3

[8, 7]

8 7
 5

[0, 0]

0 0
 0

[1, 4, 2]

1 4 2
 5 6
  1

[0, 1, 0]

0 1 0
 1 1
  2

[1, 0, 0, 0]

1 0 0 0
 1 0 0
  1 0
   1

[1, 2, 3, 4]

1 2 3 4
 3 5 7
  8 2
   0

[1, 2, 3, 5, 8]

1 2 3 5 8
 3 5 8 3
  8 3 1
   1 4
    5

[9, 2, 4, 5, 3, 2, 2]

9 2 4 5 3 2 2
 1 6 9 8 5 4
  7 5 7 3 9
   2 2 0 2
    4 2 2
     6 4
      0
</code>```

Note that in the output:

The first line does not have leading spaces.

Each subsequent line has one more leading space than the line previous.

Digits are separated by a single space.

Each line is allowed to have up to one trailing space.

There may be a single optional trailing newline.

You must use the characters for normal decimal digits (0 through 9).

The shortest code in bytes wins. Tiebreaker is earlier answer.

答:
Javascript (using external library) (198 bytes)

```<code>n=>{a=_.From(n);b=a.Write(" ");c=1;while(++c){a=a.BatchAccumulate(2).Where(y=>y.Count()==2).Select(z=>z.Sum()%10);if(a.Count()==0){break;}b+="\r\n"+_.Range(0,c).Write(" ",x=>"")+a.Write(" ")}return b}
</code>```

Link to lib: https://github.com/mvegh1/Enumerable/

Code explanation: This was easy using the library! Doesn't win in bytes, but the code isn't too verbose and easy to read. So, the input "n' is an array of integers. Load it up into the library, stored in variable "a". "b" is the return string, store the joined string with " " as delimiter into b. c is the current iteration, use this to determine the number of spaces to insert. NOTE: This only seems to work nicely when the input is from 0-9. Then, while true, repeat a certain set of code. That code is to create adjacent batch sets of the current enumerable "a", i.e if we have [1,2,3,4,5,6] we get [1,2],[2,3],[3,4],...[6] ... then filter that so we only have the batches of size 2. Then we map that to a collection of the sums of the batches % 10. If a is empty, we are done, else we add the new line to our return. Finally return...

Picture coming in a few min.

Title: Sum It Up with a Digital Triangle

Body:
Javascript (using external library) (198 bytes)

n=>{a=_.From(n);b=a.Write(" ");c=1;while(++c){a=a.BatchAccumulate(2).Where(y=>y.Count()==2).Select(z=>z.Sum()%10);if(a.Count()==0){break;}b+="\r\n"+_.Range(0,c).Write(" ",x=>"")+a.Write(" ")}return b}

Link to lib: https://github.com/mvegh1/Enumerable/

Code explanation: This was easy using the library! Doesn't win in bytes, but the code isn't too verbose and easy to read. So, the input "n' is an array of integers. Load it up into the library, stored in variable "a". "b" is the return string, store the joined string with " " as delimiter into b. c is the current iteration, use this to determine the number of spaces to insert. NOTE: This only seems to work nicely when the input is from 0-9. Then, while true, repeat a certain set of code. That code is to create adjacent batch sets of the current enumerable "a", i.e if we have [1,2,3,4,5,6] we get [1,2],[2,3],[3,4],...[6] ... then filter that so we only have the batches of size 2. Then we map that to a collection of the sums of the batches % 10. If a is empty, we are done, else we add the new line to our return. Finally return...

Picture coming in a few min.


答:
Haskell, <s>37 36</s> 32 bytes

Using the given formula in the OEIS entry, using 0-based indices. Thanks @nimi for 4 bytes!

```<code>a 0=1;a m=3*a(div m 2)-2+mod m 2
</code>```

Title: Szekeres's sequence

Body:
Definition

\$a(1) = 1\$

\$a(2) = 2\$

\$a(n)\$ is smallest number \$k>a(n-1)\$ which avoids any 3-term arithmetic progression in \$a(1), a(2), ..., a(n-1), k\$.

In other words, \$a(n)\$ is the smallest number \$k>a(n-1)\$ such that there does not exist \$x, y\$ where \$0<x<y<n\$ and \$a(y)-a(x) = k-a(y)\$.

Worked out example

For \$n=5\$:

We have \$a(1), a(2), a(3), a(4) = 1, 2, 4, 5\$

If \$a(5)=6\$, then \$2, 4, 6\$ form an arithmetic progression.

If \$a(5)=7\$, then \$1, 4, 7\$ form an arithmetic progression.

If \$a(5)=8\$, then \$2, 5, 8\$ form an arithmetic progression.

If \$a(5)=9\$, then \$1, 5, 9\$ form an arithmetic progression.

If \$a(5)=10\$, no arithmetic progression can be found.

Therefore \$a(5)=10\$.

Task

Given \$n\$, output \$a(n)\$.

Specs

\$n\$ will be a positive integer.

You can use 0-indexed instead of 1-indexed, in which case \$n\$ can be \$0\$. Please state it in your answer if you are using 0-indexed.

Scoring

Since we are trying to avoid 3-term arithmetic progression, and 3 is a small number, your code should be as small (i.e. short) as possible, in terms of byte-count.

Testcases

The testcases are 1-indexed. You can use 0-indexed, but please specify it in your answer if you do so.

```<code>1     1
2     2
3     4
4     5
5     10
6     11
7     13
8     14
9     28
10    29
11    31
12    32
13    37
14    38
15    40
16    41
17    82
18    83
19    85
20    86
10000 1679657
</code>```

References

WolframMathWorld

OEIS A003278

Body:
Haskell, <s>37 36</s> 32 bytes

Using the given formula in the OEIS entry, using 0-based indices. Thanks @nimi for 4 bytes!

a 0=1;a m=3*a(div m 2)-2+mod m 2


答:
RETURN, 7 bytes

```<code>1{11
}.
</code>```

Try it here.

Title: Print numbers from 1 to 10

Body:
RETURN, 7 bytes

1{11
}.

Try it here.


答:
Jelly, 4 bytes

```<code>Bḅ3‘
</code>```

Try it online! or verify all test cases.

How it works

This uses 0-based indexing and the primary definition from OEIS:

Szekeres's sequence: a(n)-1 in ternary = n-1 in binary

```<code>Bḅ3‘  Main link. Argument: n

B     Convert n to binary.
 ḅ3   Convert from ternary to integer.
   ‘  Increment the result.
</code>```

Title: Szekeres's sequence

Body:
Jelly, 4 bytes

Bḅ3‘

Try it online! or verify all test cases.

How it works

This uses 0-based indexing and the primary definition from OEIS:

Szekeres's sequence: a(n)-1 in ternary = n-1 in binary

Bḅ3‘  Main link. Argument: n

B     Convert n to binary.
 ḅ3   Convert from ternary to integer.
   ‘  Increment the result.


答:
ShadyAsFuck, <s>10</s> 9 bytes

```<code>PPPPPz_G]
</code>```

This is basically ++++++++++[>+.<-] in BrainFuck and outputs the numerical values as character codes.

Try It Online!

Title: Print numbers from 1 to 10

Body:
ShadyAsFuck, <s>10</s> 9 bytes

PPPPPz_G]

This is basically ++++++++++[>+.<-] in BrainFuck and outputs the numerical values as character codes.

Try It Online!


问:
RPN calculator without pointers
Me and some other students were at a bar discussing programming languages, in particular the C programming language. At some point a first year student said he didn't need no damn pointers. Another student said that he couldn't use arrays either since "they're basically pointers".

This led to a programming challenge:

Implement a reverse polish notation calculator in C without using arrays and pointers.

Description

You must implement a RPN calculator that

operates on integers,

supports addition (+),

supports multiplication (*).

Your implementation

must not use pointers or arrays

you may use structs

the input is read from stdin

your lexer may use pointers and arrays (but it shouldn't be needed)

when EOF is read then print the top of the stack

the behavior can be as undefined as you want for malformed input

should be in a language sufficiently c-like that the "no-pointers and no-arrays" restriction has a sensible interpretation (please elaborate if you think people may not get it)

The lexer could have a signature a la thisNote: this is not taken from my own code. Please tell me if there's an error or it looks unreasonable

```<code>typedef enum {
  val,
  op,
  eof
} TYPE;

typedef enum {
  add,
  mul
} OPERATION;

typedef struct {
  TYPE type;
  union {
    int val;
    OPERATION op;
  } dat;
} token;

token next();
</code>```

A solution using a stack with push() and pop() could look something like this:

```<code>token t;
while ((t = next()).type != eof) {
  switch (t.type) {
    case val:
      push(t.dat.val);
    case op:
      switch (t.dat.op) {
        case add:
          int v1 = pop();
          int v2 = pop();
          push(v1+v2);
        case mult:
          int v1 = pop();
          int v2 = pop();
          push(v1*v2);
      }
    case eof:
      printf("Result: %d\n", pop());
  }
}
</code>```

Other languages than C are also accepted, but the constraints should be comparable. It is hard to state the constraints in a way that fits all languages, but something like »all used data structures must have fixed size and fixed "depth"«. If there's any doubt please ask in the comments.

I have a solution that I can post. After cleaning up the code a bit. I wrote it the morning after while hungover.

答:
This is a stand-alone C version, it doesnt require any external lexer. It works recursivly, like ratchet freaks solution.

All characters that are not +, *, - or numbers are treated as spaces. A - is treated as a space if it is not directly followed by a number.

```<code>#include <stdio.h>

int rpn(int n1, int n2) {
        int c, sign = 1, skip = 0;
        if(n1 < 0) sign = -1;
        do {
                c = getchar();
                if(c == '+') return n1+n2;
                if(c == '*') return n1*n2;
                if(c >= 48 && c <= 57) {
                        if(!skip) n1 = n1 * 10 + sign * (c - 48);
                        else n1 = rpn(sign * (c - 48), n1);
                } else {
                        skip = 1;
                        sign = 1;
                }
                if(c == '-') sign = -1;
        } while(c != EOF);
        return n1;
}

void main() {
        printf("%d\n", rpn(0, 0));
}
</code>```

Title: RPN calculator without pointers

Body:
This is a stand-alone C version, it doesnt require any external lexer. It works recursivly, like ratchet freaks solution.

All characters that are not +, *, - or numbers are treated as spaces. A - is treated as a space if it is not directly followed by a number.

#include <stdio.h>

int rpn(int n1, int n2) {
        int c, sign = 1, skip = 0;
        if(n1 < 0) sign = -1;
        do {
                c = getchar();
                if(c == '+') return n1+n2;
                if(c == '*') return n1*n2;
                if(c >= 48 && c <= 57) {
                        if(!skip) n1 = n1 * 10 + sign * (c - 48);
                        else n1 = rpn(sign * (c - 48), n1);
                } else {
                        skip = 1;
                        sign = 1;
                }
                if(c == '-') sign = -1;
        } while(c != EOF);
        return n1;
}

void main() {
        printf("%d\n", rpn(0, 0));
}


问:
Simulate a sock drawer

Background

I have a collection of "weekday socks", which are seven pairs of socks labeled by the days of the week.
When I wash my socks, they end up in a pile, and I must arrange them into the correct pairs before putting them into the closet.
My strategy is to pull one random sock from the pile at a time and put it on a drawer.
Whenever there's a matching pair of socks on the drawer, I tie them together and put them in the closet.
Your task is to simulate this random process and return the number of draws required to find the first matching pair.

Input

Your input is an integer N ≥ 1.
It represents the "number of days in a week": there are N pairs of socks in the pile, and each pair has a distinct label.
If necessary, you may also take a PRNG seed as input.

Output

Your output is the number of socks I have to draw before the first matching pair is found.
For example, if the first two socks already form a matching pair, the output is 2.

Of course, the output is random, and depends on the drawing order.
We assume that all drawing orders are equally likely, so that each time a sock is drawn, the choice is uniform and independent from all other choices.

Example

Let N = 3, so that we have 6 socks in total, labeled A A B B C C.
One possible run of the "sock-drawing protocol" is as follows:

```<code>       | Pile   | Drawer | Pairs
Begin  | AABBCC | -      | -
Draw B | AABCC  | B      | -
Draw C | AABC   | BC     | -
Draw B | AAC    | C      | BB
Draw A | AC     | AC     | BB
Draw A | C      | C      | AA BB
Draw C | -      | -      | AA BB CC
</code>```

The first matching pair was found after drawing the second B, which was the third sock to be drawn, so the correct output is 3.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Input and output can be in any reasonable format, including unary (string of 1s).

You may assume that your language's built-in RNG is perfect.
You don't have to actually simulate the sock-drawing protocol, as long as your outputs have the correct probability distribution.

"Test cases"

Here are the approximate probabilities of all outputs for the input N = 7:

```<code>Output       2     3     4     5     6     7     8
Probability  0.077 0.154 0.210 0.224 0.186 0.112 0.037
</code>```

To test your solution, you can run it for, say, 40 000 times and see whether the output distribution is reasonably close to this.

答:
Python 3, <s>142</s> <s>105</s> 104 bytes

Thanks to Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ for saving one byte!

My first answer:

```<code>import random
i=[x/2 for x in range(int(2*input()))]
d=[]
a=0
random.shuffle(i)
while 1:
 b=i.pop()
 if b in d:
  print(a)
  s
 d=d+[b]
 a+=1
</code>```

My new answer:

```<code>from random import*
i=range(int(input()))*2
shuffle(i)
j=0
for x in i:
 if x in i[:j]:print(1+j)+s
 j+=1
</code>```

Both exit with a NameError on s.

Title: Simulate a sock drawer

Body:
Python 3, <s>142</s> <s>105</s> 104 bytes

Thanks to Eʀɪᴋ ᴛʜᴇ Gᴏʟғᴇʀ for saving one byte!

My first answer:

import random
i=[x/2 for x in range(int(2*input()))]
d=[]
a=0
random.shuffle(i)
while 1:
 b=i.pop()
 if b in d:
  print(a)
  s
 d=d+[b]
 a+=1

My new answer:

from random import*
i=range(int(input()))*2
shuffle(i)
j=0
for x in i:
 if x in i[:j]:print(1+j)+s
 j+=1

Both exit with a NameError on s.


答:
Jelly, 8 bytes

```<code>Rx2ẊĠṪ€Ṃ
</code>```

Try it online!

```<code>R    generate [1, 2, ..., n]
x2   duplicate every element (two socks of each pair)
Ẋ    shuffle the list, to represent the order in which socks are drawn
Ġ    group indices by value. this will produce a list of pairs of indices;
       each pair represents the point in time at which each of the corresponding
       socks were drawn
Ṫ€   take the last element of each pair. this returns an array of n integers
       which represent the points in time at which a matching sock was drawn
Ṃ    minimum, find the first point at which a matching sock was drawn
</code>```

To verify, here is a version that displays both the desired output and the result of the "shuffle list" operation (to see what order socks were drawn in).

Title: Simulate a sock drawer

Body:
Background

I have a collection of "weekday socks", which are seven pairs of socks labeled by the days of the week.
When I wash my socks, they end up in a pile, and I must arrange them into the correct pairs before putting them into the closet.
My strategy is to pull one random sock from the pile at a time and put it on a drawer.
Whenever there's a matching pair of socks on the drawer, I tie them together and put them in the closet.
Your task is to simulate this random process and return the number of draws required to find the first matching pair.

Input

Your input is an integer N ≥ 1.
It represents the "number of days in a week": there are N pairs of socks in the pile, and each pair has a distinct label.
If necessary, you may also take a PRNG seed as input.

Output

Your output is the number of socks I have to draw before the first matching pair is found.
For example, if the first two socks already form a matching pair, the output is 2.

Of course, the output is random, and depends on the drawing order.
We assume that all drawing orders are equally likely, so that each time a sock is drawn, the choice is uniform and independent from all other choices.

Example

Let N = 3, so that we have 6 socks in total, labeled A A B B C C.
One possible run of the "sock-drawing protocol" is as follows:

```<code>       | Pile   | Drawer | Pairs
Begin  | AABBCC | -      | -
Draw B | AABCC  | B      | -
Draw C | AABC   | BC     | -
Draw B | AAC    | C      | BB
Draw A | AC     | AC     | BB
Draw A | C      | C      | AA BB
Draw C | -      | -      | AA BB CC
</code>```

The first matching pair was found after drawing the second B, which was the third sock to be drawn, so the correct output is 3.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Input and output can be in any reasonable format, including unary (string of 1s).

You may assume that your language's built-in RNG is perfect.
You don't have to actually simulate the sock-drawing protocol, as long as your outputs have the correct probability distribution.

"Test cases"

Here are the approximate probabilities of all outputs for the input N = 7:

```<code>Output       2     3     4     5     6     7     8
Probability  0.077 0.154 0.210 0.224 0.186 0.112 0.037
</code>```

To test your solution, you can run it for, say, 40 000 times and see whether the output distribution is reasonably close to this.

Body:
Jelly, 8 bytes

Rx2ẊĠṪ€Ṃ

Try it online!

R    generate [1, 2, ..., n]
x2   duplicate every element (two socks of each pair)
Ẋ    shuffle the list, to represent the order in which socks are drawn
Ġ    group indices by value. this will produce a list of pairs of indices;
       each pair represents the point in time at which each of the corresponding
       socks were drawn
Ṫ€   take the last element of each pair. this returns an array of n integers
       which represent the points in time at which a matching sock was drawn
Ṃ    minimum, find the first point at which a matching sock was drawn

To verify, here is a version that displays both the desired output and the result of the "shuffle list" operation (to see what order socks were drawn in).


答:
Jellyfish, 16 bytes

```<code>p|%/**+1
  4  Ei
</code>```

Input format is [x y], output is just the result.

Try it online!

Alternative solution, same byte count:

```<code>pm%/*[*i
  4  +1
</code>```

Explanation

Time to give Jellyfish the introduction it deserves! :)

Jellyfish is Zgarb's language based on his 2D syntax challenge. The semantics are largely inspired by J, but the syntax is a work of art. All functions are single characters and laid out on a grid. Functions take their arguments from the next token south and east of them and return the result north and west. This let's you create an interesting web of function calls where you reuse values by passing them into several functions from multiple directions.

If we ignore the fact that some of tokens in the above program are special operators (higher-level functions), the above program would be written something like this in a sane language:

```<code>p(|( /*(i*(i+1)) % 4 ))
</code>```

Let's go through the code bottom-up. Input gets fed in by the i, which therefore evaluates to [x y].

The + on top of it receives this input together with the literal 1 and therefore increments both elements to give [(x+1) (y+1)] (most operations are threaded automatically over lists).

The other value of i is sent left, but the E splits is eastern argument north and west. That means the inputs to the right * are actually [x y] and [(x+1) (y+1)] so this computes [x*(x+1) y*(y+1)].

The next * up is actually modified by the preceding / which turns it into a fold operation. Folding * over a pair simply multiplies it, so that we get x*(x+1)*y*(y+1).

Now % is just division so it computes x*(x+1)*y*(y+1)/4. Unfortunately, this results in a float so we need to round it with the unary |. Finally, this value is fed to p which prints the final result.

Title: How Many Rectangles in the Grid?

Body:
Well, although this challenge turned out to be a huge success, it also turned out to be very trivial to solve. Therefore, for those of looking for more of a challenge, I created a sequel to this challenge in which you must now count the number of unique rectangles. Check it out!

Now, for those of you looking to solve this challenge, here it comes.

Well, we don't really have a challenge like this yet, so here we go.

Consider this 3 x 3 grid of rectangles:

How many rectangles are there? Well, counting visually, we can see that there are actually 36 rectangles, including the entire plane itself, which are all shown in the animated GIF below:

The Task

The counting of rectangles as shown above is the task. In other words, given 2 integers greater than or equal to 0, m and n, where m represents the width and n represents the height, output the total number of rectangles in that m x n grid of rectangles.

Rules

The use of any built-ins that directly solve this problem is explicitly disallowed.

This challenge is not about finding the shortest answer, but finding the shortest answer in every language. Therefore, no answer will be accepted.

Standard loopholes are prohibited.

Test Cases

Presented in the format Array of Integers Input -> Integer Output:

```<code>[0,0] -> 0
[1,1] -> 1
[3,3] -> 36 (Visualized above)
[4,4] -> 100
[6,7] -> 588
</code>```

References

http://oeis.org/A096948

Remember, this is code-golf, so shortest code wins!

Body:
Jellyfish, 16 bytes

p|%/**+1
  4  Ei

Input format is [x y], output is just the result.

Try it online!

Alternative solution, same byte count:

pm%/*[*i
  4  +1

Explanation

Time to give Jellyfish the introduction it deserves! :)

Jellyfish is Zgarb's language based on his 2D syntax challenge. The semantics are largely inspired by J, but the syntax is a work of art. All functions are single characters and laid out on a grid. Functions take their arguments from the next token south and east of them and return the result north and west. This let's you create an interesting web of function calls where you reuse values by passing them into several functions from multiple directions.

If we ignore the fact that some of tokens in the above program are special operators (higher-level functions), the above program would be written something like this in a sane language:

p(|( /*(i*(i+1)) % 4 ))

Let's go through the code bottom-up. Input gets fed in by the i, which therefore evaluates to [x y].

The + on top of it receives this input together with the literal 1 and therefore increments both elements to give [(x+1) (y+1)] (most operations are threaded automatically over lists).

The other value of i is sent left, but the E splits is eastern argument north and west. That means the inputs to the right * are actually [x y] and [(x+1) (y+1)] so this computes [x*(x+1) y*(y+1)].

The next * up is actually modified by the preceding / which turns it into a fold operation. Folding * over a pair simply multiplies it, so that we get x*(x+1)*y*(y+1).

Now % is just division so it computes x*(x+1)*y*(y+1)/4. Unfortunately, this results in a float so we need to round it with the unary |. Finally, this value is fed to p which prints the final result.


答:
Python 2, 101 bytes

from random import*
d=[]
p=range(input())*2
shuffle(p)
while list(set(d))==d:d+=p.pop(),
print len(d)
```

Title: Simulate a sock drawer


答:
MATL, <s>14</s> 13 bytes

```<code>EZ@G\&=XRafX<
</code>```

Try it online! Or observe the empirical distribution for 4000 samples in the N=7 case (it takes a while).

```<code>E      % Input N implicitly. Multiply by 2
Z@     % Random permutation of [1 2 ... 2*N]
G\     % Modulo N: random permutation of [0 0 1 1 ... N-1 N-1]
&=     % Compare all pairs for equality. Gives an N×N matrix
XR     % Upper triangular part excluding the diagonal
a      % True for each column if it contains at least one true entry
f      % Get indices of true values
X<     % Take minimum. Implicitly display
</code>```

Title: Simulate a sock drawer

Body:
MATL, <s>14</s> 13 bytes

EZ@G\&=XRafX<

Try it online! Or observe the empirical distribution for 4000 samples in the N=7 case (it takes a while).

E      % Input N implicitly. Multiply by 2
Z@     % Random permutation of [1 2 ... 2*N]
G\     % Modulo N: random permutation of [0 0 1 1 ... N-1 N-1]
&=     % Compare all pairs for equality. Gives an N×N matrix
XR     % Upper triangular part excluding the diagonal
a      % True for each column if it contains at least one true entry
f      % Get indices of true values
X<     % Take minimum. Implicitly display