答:
Retina, <s>150</s> <s>122</s> 118 bytes

The output to this challenge looks awesome, by the way!

Input is in unary. The output contains a trailing linefeed. The code uses ISO 8859-1 encoding. Note the trailing space on the penultimate line.

```<code>(?=_\\¶.*1)
_\/__\
(?=/_/\\¶.*1)
/_/\/
(^|__)(?=/\\¶.*1)
$1/\ \__
ms}`(.*1*)1
/\¶/_/\¶/__\_\¶$1
m`^(?=(.*¶)*.)
$#1$*
</code>```

Try it online

Explanation

If you want a more in-depth explanation, comment or message me in chat.

```<code>(?=_\\¶.*1)                     # Matches the start of the 3rd line of every triangle
/__\_\                          #   and prepends another layer if needed
(?=/_/\\¶.*1)                   # 2nd line of each triangle
/_/\/
(^|__)(?=/\\¶.*1)               # 1st line of each triangle
$1/\ \__
ms}`(.*1*)1                 # This and above in a multi-single-line loop.
/\¶/_/\¶/__\_\¶$1               #   This stage adds a flattened triangle on top
m`^(?=(.*¶)*.)                  # Prepend a space for every line following -1
$#1$*
</code>```

Thanks to Martin for golfing 32 bytes off.

Title: Build a triangle without any triangles

Body:
As a little kid, I liked to play with these toys a lot:

They probably intended for these to be used for art, but I always used them for math! Fractals, patterns, etc. One time, I was given this challenge:

Build a triangle without using any of the green triangle tiles.

This challenge stumped me for the longest time, until I stumbled upon a really beautiful and simple way to do it with just 3 trapezoids:

```<code>  /\
 /_/\
/__\_\
</code>```

Now, take this triangle, and rotate it:

```<code>______
\ \__/
 \/ /
  \/
</code>```

Using these two triangles, we can construct larger triangles out of them. Here is a triangle of height 2:

```<code>     /\
    /_/\
   /__\_\
  /\ \__/\
 /_/\/ /_/\
/__\_\/__\_\
</code>```

And here are triangles of height 3-7:

```<code>#3
        /\
       /_/\
      /__\_\
     /\ \__/\
    /_/\/ /_/\
   /__\_\/__\_\
  /\ \__/\ \__/\
 /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\

#4
           /\
          /_/\
         /__\_\
        /\ \__/\
       /_/\/ /_/\
      /__\_\/__\_\
     /\ \__/\ \__/\
    /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\

#5
              /\
             /_/\
            /__\_\
           /\ \__/\
          /_/\/ /_/\
         /__\_\/__\_\
        /\ \__/\ \__/\
       /_/\/ /_/\/ /_/\
      /__\_\/__\_\/__\_\
     /\ \__/\ \__/\ \__/\
    /_/\/ /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\/__\_\

#6
                 /\
                /_/\
               /__\_\
              /\ \__/\
             /_/\/ /_/\
            /__\_\/__\_\
           /\ \__/\ \__/\
          /_/\/ /_/\/ /_/\
         /__\_\/__\_\/__\_\
        /\ \__/\ \__/\ \__/\
       /_/\/ /_/\/ /_/\/ /_/\
      /__\_\/__\_\/__\_\/__\_\
     /\ \__/\ \__/\ \__/\ \__/\
    /_/\/ /_/\/ /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\/__\_\/__\_\

#7
                    /\
                   /_/\
                  /__\_\
                 /\ \__/\
                /_/\/ /_/\
               /__\_\/__\_\
              /\ \__/\ \__/\
             /_/\/ /_/\/ /_/\
            /__\_\/__\_\/__\_\
           /\ \__/\ \__/\ \__/\
          /_/\/ /_/\/ /_/\/ /_/\
         /__\_\/__\_\/__\_\/__\_\
        /\ \__/\ \__/\ \__/\ \__/\
       /_/\/ /_/\/ /_/\/ /_/\/ /_/\
      /__\_\/__\_\/__\_\/__\_\/__\_\
     /\ \__/\ \__/\ \__/\ \__/\ \__/\
    /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\/__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\/__\_\/__\_\/__\_\
</code>```

The Challenge

Write a program or function that takes a number n and prints a triangle-less triangle of height n. Trailing spaces on each line is acceptable, and up to one trailing or leading newline is also acceptable. IO can be in any reasonable format. The input is guarenteed to be a positive integer, so you don't have to worry about negative numbers, decimals, non-numbers etc.

Shortest answer in bytes wins!

Body:
Retina, <s>150</s> <s>122</s> 118 bytes

The output to this challenge looks awesome, by the way!

Input is in unary. The output contains a trailing linefeed. The code uses ISO 8859-1 encoding. Note the trailing space on the penultimate line.

(?=_\\¶.*1)
_\/__\
(?=/_/\\¶.*1)
/_/\/
(^|__)(?=/\\¶.*1)
$1/\ \__
ms}`(.*1*)1
/\¶/_/\¶/__\_\¶$1
m`^(?=(.*¶)*.)
$#1$*

Try it online

Explanation

If you want a more in-depth explanation, comment or message me in chat.

(?=_\\¶.*1)                     # Matches the start of the 3rd line of every triangle
/__\_\                          #   and prepends another layer if needed
(?=/_/\\¶.*1)                   # 2nd line of each triangle
/_/\/
(^|__)(?=/\\¶.*1)               # 1st line of each triangle
$1/\ \__
ms}`(.*1*)1                 # This and above in a multi-single-line loop.
/\¶/_/\¶/__\_\¶$1               #   This stage adds a flattened triangle on top
m`^(?=(.*¶)*.)                  # Prepend a space for every line following -1
$#1$*

Thanks to Martin for golfing 32 bytes off.


答:
ruby, 207 bytes

```<code>->a{r=[];(r<<a;a=(0...a.size).map{|i|(0...a[i].size).map{|j|n=0;(-1..1).map{|u|(-1..1).map{|v|n+=a[(i+u)%a.size][(j+v)%a[i].size]}};[n==3,n>2&&n<5][a[i][j]]?1:0}})while(!r.index(a));(a==r[-1])?r.index(a):-1}
</code>```

I keep a history of each board, so if I get a board I have seen before I know one of two thing happened. first it could be that we have found a stable position, in which case it will be the most resent in our history. the other possibility is that we have a loop.

ContentLicense: CC BY-SA 3.0

Title: Stable Game of Life

Body:
Challenge:

Given a matrix (or 2d array) of 0s and 1s, output the number of steps it takes for Conway's game of life to reach a stable state, or -1 if it never reaches one.  A stable state is a state in which no cells are turned on or off each step.  The game must run in the  given matrix, with the top and bottom connected, and the sides connected. (i.e. given a 4x3 matrix it should run on a 4x3 torus)  The input matrix will not be larger than 15x15.

Note: If the matrix starts in a stable state, the output should be 0.

Samples:

Input:

```<code>[[0,0,0],
 [0,1,1],
 [0,1,0]]
</code>```

Output:

2

Process: (this does not need to be displayed)

```<code>[[0,0,0],
 [0,1,1],
 [0,1,0]]

[[1,1,1],
 [1,1,1],
 [1,1,1]]

[[0,0,0],
 [0,0,0],
 [0,0,0]]
</code>```

Input:

```<code>[[0,0,1,1],
 [0,1,1,1],
 [0,1,0,0],
 [0,1,1,1]]
</code>```

Output:

2

Process:

```<code>[[0,0,1,1],
 [0,1,1,1],
 [0,1,0,0],
 [0,1,1,1]]

[[0,0,0,0],
 [0,1,0,1],
 [0,0,0,0],
 [0,1,0,1]]

[[0,0,0,0],
 [0,0,0,0],
 [0,0,0,0],
 [0,0,0,0]]
</code>```

Input:

```<code>[[0,1,0,0],
 [0,1,0,0],
 [0,1,0,0],
 [0,0,0,0]]
</code>```

Output:

-1

Process:

```<code>[[0,1,0,0],
 [0,1,0,0],
 [0,1,0,0],
 [0,0,0,0]]

[[0,0,0,0],
 [1,1,1,0],
 [0,0,0,0],
 [0,0,0,0]]

[[0,1,0,0],
 [0,1,0,0],
 [0,1,0,0],
 [0,0,0,0]]
</code>```

repeating forever

Input:

```<code>[[0,0,0,0],
 [0,0,0,1],
 [0,1,1,1],
 [0,0,1,0]]
</code>```

Output:

4

Process:

```<code>[[0,0,0,0],
 [0,0,0,1],
 [0,1,1,1],
 [0,0,1,0]]

[[0,0,0,0],
 [1,0,0,1],
 [1,1,0,1],
 [0,1,1,1]]

[[0,1,0,0],
 [0,1,1,1],
 [0,0,0,0],
 [0,1,0,1]]

[[0,1,0,1],
 [1,1,1,0],
 [0,1,0,1],
 [1,0,1,0]]

[[0,0,0,0],
 [0,0,0,0],
 [0,0,0,0],
 [0,0,0,0]]
</code>```

Input:

```<code>[[0,0,0,0],
 [0,1,1,0],
 [0,1,1,0],
 [0,0,0,0]]
</code>```

Output:

0

Process:

The beginning state is stable.

Rules of the Game of Life

If a cell that is off (0) is next to exactly three on (1) cells, it is turned on. Otherwise, it is left off. If a cell that is on is next to 2 or 3 on squares, it says on.  Otherwise, it is turned off.

Body:
ruby, 207 bytes

->a{r=[];(r<<a;a=(0...a.size).map{|i|(0...a[i].size).map{|j|n=0;(-1..1).map{|u|(-1..1).map{|v|n+=a[(i+u)%a.size][(j+v)%a[i].size]}};[n==3,n>2&&n<5][a[i][j]]?1:0}})while(!r.index(a));(a==r[-1])?r.index(a):-1}

I keep a history of each board, so if I get a board I have seen before I know one of two thing happened. first it could be that we have found a stable position, in which case it will be the most resent in our history. the other possibility is that we have a loop.


问:
How can I shorten this python code analyzing a 3d grid?
My Python 3 function golf(...) should take a list of lists of lists of strings representing a solid cube and return whether there are any places in which two equal strings are directly next to each other on the x, y or z axis (not diagonally).

If there are no adjacent duplicates, True shall be returned, else False.

The input list and all of its sublists have the same length as they represent a cube, and their length is greater than 1 but lower than or equal to 5. The only possible values for the Strings inside the nested lists are "X" and "Z".

The maximum code length should be less than 200 bytes.

This is an example test case:

```<code>golf([[["X", "Z"],
       ["Z", "X"]],
      [["Z", "X"],
       ["X", "Z"]]]) == True
golf([[["X", "Z"],
       ["Z", "X"]],
      [["X", "Z"],
       ["Z", "X"]]]) == False
</code>```

My current solution has 234 bytes:

```<code>def golf(c):
 r=range(len(c));R=[(a,b)for a in r for b in r];j="".join
 return all("XX"not in l and"ZZ"not in l for l in[j(c[x][y][z]for x in r)for y,z in R]+[j(c[x][y][z]for y in r)for x,z in R]+[j(c[x][y][z]for z in r)for x,y in R])
</code>```

How can I golf this code any further to save another 35 bytes?

答:
Python 3, <s>108</s> 107 bytes

Since the cube only contains the strings "X" and "Z", there are only two valid cube patterns. The one that starts with XZXZX... and the one that starts with ZXZXZ....

My solutions generates these 2 cubes and checks if the inputted cube is one of them.

def golf(l):L=len(l);r=range(L);return l in[[[list("XZ"*L)[(i+j+k)%2:][:L]for j in r]for k in r]for i in r]

i iterates over the possible cubes. Since the dimension is at least 2, we can reuse r instead of writing for i in(0,1).


问:
Generate the minimal remainder sequence
Every number can be represented using an infinitely long remainder sequence.  For example, if we take the number 7, and perform 7mod2, then 7mod3, then 7mod4, and so on, we get 1,1,3,2,1,0,7,7,7,7,.....

However, we need the shortest possible remainder subsequence that can still be used to distinguish it from all lower numbers.  Using 7 again, [1,1,3] is the shortest subsequence, because all of the previous subsequences don't start with [1,1,3]:

```<code>0: 0,0,0,0...
1: 1,1,1,1...
2: 0,2,2,2...
3: 1,0,3,3...
4: 0,1,0,4...
5: 1,2,1,0...
6: 0,0,2,1...
</code>```

Note that [1,1] doesn't work to represent 7, because it can also be used to represent 1.  However, you should output [1] with an input of 1.

Input/Output

Your input is a non-negative integer.  You must output a sequence or list of the minimal-length sequence of remainders as defined above.

Test cases:

```<code>0: 0
1: 1
2: 0,2
3: 1,0
4: 0,1
5: 1,2
6: 0,0,2
7: 1,1,3
8: 0,2,0
9: 1,0,1
10: 0,1,2
11: 1,2,3
12: 0,0,0,2
30: 0,0,2,0
42: 0,0,2,2
59: 1,2,3,4
60: 0,0,0,0,0,4
257: 1,2,1,2,5,5
566: 0,2,2,1,2,6,6
1000: 0,1,0,0,4,6,0,1
9998: 0,2,2,3,2,2,6,8,8,10
9999: 1,0,3,4,3,3,7,0,9,0
</code>```

Here are the first 10,000 sequences, in case you are interested (the line numbers are off by 1).

This is a code-golf, so make it as short as you can in your favorite language.  Fake bonus points for any answers that are fast!

答:
Pyth, <s>51 Bytes</s> 66 Bytes

```<code>IqQZ[Z).q)IqQ1[1))IqQ2,0 1))FdhhQJu/*GHiGHtUd1I>JQVQ aY%QhN)<tYd.q
</code>```

Try it out!

Much higher speed 39 byte version (does not work for 0-2):

```<code>FdhhQJu/*GHiGHtUd1I>JQVtd aY%QhN)<tYd.q
</code>```

It seems to work for absurdly large numbers like 10103

<s>Note: this answer does not work for 0, 1, and 2.</s>  Fixed!

Title: Generate the minimal remainder sequence

Body:
Pyth, <s>51 Bytes</s> 66 Bytes

IqQZ[Z).q)IqQ1[1))IqQ2,0 1))FdhhQJu/*GHiGHtUd1I>JQVQ aY%QhN)<tYd.q

Try it out!

Much higher speed 39 byte version (does not work for 0-2):

FdhhQJu/*GHiGHtUd1I>JQVtd aY%QhN)<tYd.q

It seems to work for absurdly large numbers like 10103

<s>Note: this answer does not work for 0, 1, and 2.</s>  Fixed!


问:
Box-256 Assembly - BIG SQUARE II
I'd like to start a series of challenges for http://box-256.com/ starting with the first challenge, “BIG SQUARE II”. After this one I'll add another for "CHECKERBOARD" and so on.

Rules:

Complete the BIG SQAURE II challenge in the Box-256 emulator (either on the website or download the program if you run Windows)

Post back here a screenshot of your working answer

You MUST include the code in plain text so that others can easily copy and very it’s operation.

Scoring:

The winner will be the least amount of instructions used (just the instruction calls, either by name or opcode, the arguments to them are not counted as JMP takes one argument but MOD can take three).

I think in the future contests we can add some additional bonus points for use of coding tricks and we could include the argument count too. I wanted to start basic to get the ball rolling.

Winning

I think we should put a stake in the ground and say two weeks from today we announce the winner(s, there maybe be mutliple entries with the same instruction count).

Title: Box-256 Assembly - BIG SQUARE II

Body:
1 instruction

This solution is to illustrate that counting instructions is not a proper way of scoring for BOX-256.

JMP 002 072 00C
002 000 013 00C
001 00C 055 002
010 000 000 000
011 012 013 014
015 016 017 018
019 01A 01B 01C
01D 01E 021 022
023 024 025 026
027 028 029 02A
02B 02C 02D 02E
0D1 0D2 0D3 0D4
0D5 0D6 0D7 0D8
0D9 0DA 0DB 0DC
0DD 0DE 0E1 0E2
0E3 0E4 0E5 0E6
0E7 0E8 0E9 0EA
0EB 0EC 0ED 0EE
031 041 051 061
071 081 091 0A1
0B1 0C1 032 042
052 062 072 082
092 0A2 0B2 0C2
03D 04D 05D 06D
07D 08D 09D 0AD
0BD 0CD 0ED 03E
04E 05E 06E 07E
08E 09E 0AE 0BE
0CE 000 000 000


问:
Print cos(2π/17) exactly
One way to construct a regular heptadecagon starts with drawing a horizontal line of length 1 from the center to a vertex. Then the distance along that line from the center to the second vertex is cos(2π/17). All other vertices are easy to get.

The goal of this challenge is to print (or produce in any other conventional way) an ASCII math expression involving the operations +, -, *, /, sqrt() and the natural numbers, which gives cos(2π/17) when evaluated. The power operator is not allowed: e.g. sqrt(17) cannot be written as 17^(1/2).

For example (formula taken from Wikipedia):

```<code>1/16*(
    -1+
    sqrt(17)+
    sqrt(34-2*sqrt(17))+
    2*sqrt(
        17+
        3*sqrt(17)-
        sqrt(34-2*sqrt(17))-
        2*sqrt(34+2*sqrt(17))
    )
)
</code>```

Whitespace doesn't matter. The length and complexity of the expression doesn't matter, as long as it's syntactically correct (as defined above) and numerically equivalent to cos(2π/17).

Built-in functions are allowed.

答:
Ruby, 71

I think this could be shorter in another language.

```<code>'(s/2)+s-s*2))+s*2+s*72)-4*s-s*2))-8*s+s*2)))-1)/16'.gsub(?s,'sqrt(34')
</code>```

The above string expression evaluates to the below string. The idea was to rearrange the expression so that a single substitution of s -> sqrt(34 would be the only operation needed to decompress it.

```<code>(sqrt(34/2)+sqrt(34-sqrt(34*2))+sqrt(34*2+sqrt(34*72)-4*sqrt(34-sqrt(34*2))-8*sqrt(34+sqrt(34*2)))-1)/16
</code>```

I assume "produce in any other conventional way" means an expression is enough. If this is not the case: Printing the string in quotation marks would need 2 extra bytes at the beginning of the source code: p . For 5 bytes it can be printed without quotation marks by adding puts. Enclosing it in ->{} yields an anonymous function for 4 extra bytes.

Title: Print cos(2π/17) exactly

Body:
Ruby, 71

I think this could be shorter in another language.

'(s/2)+s-s*2))+s*2+s*72)-4*s-s*2))-8*s+s*2)))-1)/16'.gsub(?s,'sqrt(34')

The above string expression evaluates to the below string. The idea was to rearrange the expression so that a single substitution of s -> sqrt(34 would be the only operation needed to decompress it.

(sqrt(34/2)+sqrt(34-sqrt(34*2))+sqrt(34*2+sqrt(34*72)-4*sqrt(34-sqrt(34*2))-8*sqrt(34+sqrt(34*2)))-1)/16

I assume "produce in any other conventional way" means an expression is enough. If this is not the case: Printing the string in quotation marks would need 2 extra bytes at the beginning of the source code: p . For 5 bytes it can be printed without quotation marks by adding puts. Enclosing it in ->{} yields an anonymous function for 4 extra bytes.


答:
Python 3.5, 117 95 78 bytes

```<code>import sympy
r=lambda n,m=2,M=1,*l:M>n and l or r(n,m+1,sympy.lcm(m,M),*l,n%m)
</code>```

Requires Python 3.5 and sympy (python3 -m pip install --user sympy). Credit to @Dennis to notify me that Python 3.5 allows the *l trick with default arguments.

Title: Generate the minimal remainder sequence

Body:
Every number can be represented using an infinitely long remainder sequence.  For example, if we take the number 7, and perform 7mod2, then 7mod3, then 7mod4, and so on, we get 1,1,3,2,1,0,7,7,7,7,.....

However, we need the shortest possible remainder subsequence that can still be used to distinguish it from all lower numbers.  Using 7 again, [1,1,3] is the shortest subsequence, because all of the previous subsequences don't start with [1,1,3]:

```<code>0: 0,0,0,0...
1: 1,1,1,1...
2: 0,2,2,2...
3: 1,0,3,3...
4: 0,1,0,4...
5: 1,2,1,0...
6: 0,0,2,1...
</code>```

Note that [1,1] doesn't work to represent 7, because it can also be used to represent 1.  However, you should output [1] with an input of 1.

Input/Output

Your input is a non-negative integer.  You must output a sequence or list of the minimal-length sequence of remainders as defined above.

Test cases:

```<code>0: 0
1: 1
2: 0,2
3: 1,0
4: 0,1
5: 1,2
6: 0,0,2
7: 1,1,3
8: 0,2,0
9: 1,0,1
10: 0,1,2
11: 1,2,3
12: 0,0,0,2
30: 0,0,2,0
42: 0,0,2,2
59: 1,2,3,4
60: 0,0,0,0,0,4
257: 1,2,1,2,5,5
566: 0,2,2,1,2,6,6
1000: 0,1,0,0,4,6,0,1
9998: 0,2,2,3,2,2,6,8,8,10
9999: 1,0,3,4,3,3,7,0,9,0
</code>```

Here are the first 10,000 sequences, in case you are interested (the line numbers are off by 1).

This is a code-golf, so make it as short as you can in your favorite language.  Fake bonus points for any answers that are fast!

Body:
Python 3.5, 117 95 78 bytes

import sympy
r=lambda n,m=2,M=1,*l:M>n and l or r(n,m+1,sympy.lcm(m,M),*l,n%m)

Requires Python 3.5 and sympy (python3 -m pip install --user sympy). Credit to @Dennis to notify me that Python 3.5 allows the *l trick with default arguments.


答:
JavaScript (ES6), <s>81</s> 77 bytes

```<code>f=(n,r=[n%2],l=i=2,g=(j,k)=>j?g(k%j,j):k)=>l>n?r:f(n,[...r,n%++i],i/g(i,l)*l)
</code>```

This recursively builds up the answer until the LCM exceeds the original number. The GCD is also calculated recursively, of course.

Edit: Saved 4 bytes thanks to @user81655.

Title: Generate the minimal remainder sequence

Body:
JavaScript (ES6), <s>81</s> 77 bytes

f=(n,r=[n%2],l=i=2,g=(j,k)=>j?g(k%j,j):k)=>l>n?r:f(n,[...r,n%++i],i/g(i,l)*l)

This recursively builds up the answer until the LCM exceeds the original number. The GCD is also calculated recursively, of course.

Edit: Saved 4 bytes thanks to @user81655.


答:
Bubblegum, 39 bytes

```<code>0000000: d3 35 d4 37 34 d3 2e 2e 2c 2a d1 30 34 d7 84 b3  .5.74...,*.04...
0000010: 75 8d b4 60 62 da c6 26 98 e2 a8 d2 ba 58 f4 00  u..`b..&.....X..
0000020: 31 82 0b 32 da 02 00                             1..2...
</code>```

Try it online!

Verification

```<code>$ base64 -d > exact-cos.bg <<< 0zXUNzTTLi4sKtEwNNeEs3WNtGBi2sYmmOKo0rpY9AAxggsy2gIA
$ wc -c exact-cos.bg
39 exact-cos.bg
$ bubblegum exact-cos.bg; echo
-1/16+sqrt(17)/16+sqrt(-2*sqrt(17)+34)/16+sqrt(-2*sqrt(2*sqrt(17)+34)-sqrt(-2*sqrt(17)+34)+3*sqrt(17)+17)/8
$ cat verify-cos
#!/usr/bin/python3

from sympy import *

print(Eq(S(input()), cos(2*pi/17)))
$ bubblegum exact-cos.bg | ./verify-cos
True
</code>```

Title: Print cos(2π/17) exactly

Body:
One way to construct a regular heptadecagon starts with drawing a horizontal line of length 1 from the center to a vertex. Then the distance along that line from the center to the second vertex is cos(2π/17). All other vertices are easy to get.

The goal of this challenge is to print (or produce in any other conventional way) an ASCII math expression involving the operations +, -, *, /, sqrt() and the natural numbers, which gives cos(2π/17) when evaluated. The power operator is not allowed: e.g. sqrt(17) cannot be written as 17^(1/2).

For example (formula taken from Wikipedia):

```<code>1/16*(
    -1+
    sqrt(17)+
    sqrt(34-2*sqrt(17))+
    2*sqrt(
        17+
        3*sqrt(17)-
        sqrt(34-2*sqrt(17))-
        2*sqrt(34+2*sqrt(17))
    )
)
</code>```

Whitespace doesn't matter. The length and complexity of the expression doesn't matter, as long as it's syntactically correct (as defined above) and numerically equivalent to cos(2π/17).

Built-in functions are allowed.

Body:
Bubblegum, 39 bytes

0000000: d3 35 d4 37 34 d3 2e 2e 2c 2a d1 30 34 d7 84 b3  .5.74...,*.04...
0000010: 75 8d b4 60 62 da c6 26 98 e2 a8 d2 ba 58 f4 00  u..`b..&.....X..
0000020: 31 82 0b 32 da 02 00                             1..2...

Try it online!

Verification

$ base64 -d > exact-cos.bg <<< 0zXUNzTTLi4sKtEwNNeEs3WNtGBi2sYmmOKo0rpY9AAxggsy2gIA
$ wc -c exact-cos.bg
39 exact-cos.bg
$ bubblegum exact-cos.bg; echo
-1/16+sqrt(17)/16+sqrt(-2*sqrt(17)+34)/16+sqrt(-2*sqrt(2*sqrt(17)+34)-sqrt(-2*sqrt(17)+34)+3*sqrt(17)+17)/8
$ cat verify-cos
#!/usr/bin/python3

from sympy import *

print(Eq(S(input()), cos(2*pi/17)))
$ bubblegum exact-cos.bg | ./verify-cos
True


答:
C89, 105 bytes

```<code>g(a,b){return b?g(b,a%b):a;}main(n,m,M){scanf("%d",&n);for(m=M=1;(M=++m*M/g(m,M))<=n;)printf("%d ",n%m);}
</code>```

Compiles (with warnings) using gcc -std=c89. Takes a single number on stdin, and outputs the sequence of remainders separated by spaces on stdout.

Title: Generate the minimal remainder sequence

Body:
C89, 105 bytes

g(a,b){return b?g(b,a%b):a;}main(n,m,M){scanf("%d",&n);for(m=M=1;(M=++m*M/g(m,M))<=n;)printf("%d ",n%m);}

Compiles (with warnings) using gcc -std=c89. Takes a single number on stdin, and outputs the sequence of remainders separated by spaces on stdout.


问:
Convert phrases to reverse style

The Challenge

Convert a phrase of two words to reverse style: candy bar -> bar le candy.

Specifications

There will be one word (only a-zA-Z0-9 + -), a space (), and then another word.

For equal length, score is used to determine winner.

Test cases:

```<code>candy bar -> bar le candy
code golf -> golf le code
programming puzzles -> puzzles le programming
</code>```

答:
Gawk, <s>17</s> 16 bytes

1 byte off thanks to muru

```<code>{$0=$2" le "$1}1
</code>```

Old

```<code>{print$2" le "$1}
</code>```

Title: Convert phrases to reverse style

Body:
Gawk, <s>17</s> 16 bytes

1 byte off thanks to muru

{$0=$2" le "$1}1

Old

{print$2" le "$1}


问:
Identify the Conic Section
Given 5 distinct points on a two-dimensional plane, determine the type of conic section formed by the points. The output shall be one of circle, hyperbola, ellipse, or parabola.

Rules

The points will be in general linear position, meaning that no three points are collinear, and thus the conic passing through them will be unique.

The coordinates of the 5 points will be decimal numbers between -10 and 10, inclusive.

The precision for the decimal/float values should be the precision of your language's native float/decimal type. If your language/data type is arbitrary-precision, you may use 12 digits after the decimal point as the maximum required precision, rounding toward zero (e.g. 1.0000000000005 == 1.000000000000).

Capitalization of the output does not matter.

Outputting ellipse when the conic section is actually a circle is not allowed. All circles are ellipses, but you must output the most specific one.

On floating point inaccuracies and precision:

I'm trying to make this as simple as possible, so that issues with floating point inaccuracies don't get in the way. The goal is, if the data type was "magical infinite precision value" instead of float/double, then everything would work perfectly. But, since "magical infinite precision value" doesn't exist, you write code that assumes that your values are infinite precision, and any issues that crop up as a result of floating point inaccuracies are features, not bugs.

Test Cases

```<code>(0, 0), (1, 5), (2, 3), (4, 8), (9, 2) => hyperbola
(1.2, 5.3), (4.1, 5.6), (9.1, 2.5), (0, 1), (4.2, 0) => ellipse
(5, 0), (4, 3), (3, 4), (0, 5), (0, -5) => circle
(1, 0), (0, 1), (2, 1), (3, 4), (4, 9) => parabola
</code>```

答:
Python - 234 bytes

```<code>import numpy as n
x=input()
d=[n.linalg.det(n.delete(n.array([[i*i,i*j,j*j,i,j,1]for i,j in x]),k,1))for k in range(6)]
t=d[1]**2-4*d[0]*d[2]
print"hyperbola"if t>0else"parabola"if t==0else"circle"if d[1]==0and d[0]==d[2]else"ellipse"
</code>```

I never print circle or parabola because t and d[1] never hit exactly 0, but OP said that was okay.

Title: Identify the Conic Section

Body:
Python - 234 bytes

import numpy as n
x=input()
d=[n.linalg.det(n.delete(n.array([[i*i,i*j,j*j,i,j,1]for i,j in x]),k,1))for k in range(6)]
t=d[1]**2-4*d[0]*d[2]
print"hyperbola"if t>0else"parabola"if t==0else"circle"if d[1]==0and d[0]==d[2]else"ellipse"

I never print circle or parabola because t and d[1] never hit exactly 0, but OP said that was okay.


答:
Matlab, 154 bytes

```<code>p=input();c=null([p.^2 prod(p,2) p 1+p(:,1)*0]),s={'circle' 'ellipse' 'parabola' 'hyperbola'};s{3+sign(c(3)^2-4*c(1)*c(2))-~max(abs(c(3)),abs(c(1)-c(2)))}
</code>```

Saved some bytes thanks to Suever's suggestions.

Takes input as [x1 y1;x2 y2;x3 y3; etc]. This used a Vandermonde matrix, and finds the basis of its null space, which will always be a single vector. Then it calculates the discriminant and uses it to make an index between 1 and 4 which is used to get the string.

Ungolfed:

```<code>p=input();
c=null([p.^2 prod(p')' p ones(length(p),1)]);
s={'circle' 'ellipse' 'parabola' 'hyperbola'};
s{3+sign(c(3)^2-4*c(1)*c(2))-~max(abs(c(3)),abs(c(1)-c(2)))}
</code>```

The sign(...) part calculates the discriminant, giving 1 if it's positive (hyperbola), -1 if it's negative (ellipse), and 0 if it's 0 (parabola). The max(...) subtracts 1 away if it is a circle. Matlab arrays are one-indexed, so add 3 to give values 1, 2, 3, 4, and use that to index the array of conic section names.

Title: Identify the Conic Section

Body:
Given 5 distinct points on a two-dimensional plane, determine the type of conic section formed by the points. The output shall be one of circle, hyperbola, ellipse, or parabola.

Rules

The points will be in general linear position, meaning that no three points are collinear, and thus the conic passing through them will be unique.

The coordinates of the 5 points will be decimal numbers between -10 and 10, inclusive.

The precision for the decimal/float values should be the precision of your language's native float/decimal type. If your language/data type is arbitrary-precision, you may use 12 digits after the decimal point as the maximum required precision, rounding toward zero (e.g. 1.0000000000005 == 1.000000000000).

Capitalization of the output does not matter.

Outputting ellipse when the conic section is actually a circle is not allowed. All circles are ellipses, but you must output the most specific one.

On floating point inaccuracies and precision:

I'm trying to make this as simple as possible, so that issues with floating point inaccuracies don't get in the way. The goal is, if the data type was "magical infinite precision value" instead of float/double, then everything would work perfectly. But, since "magical infinite precision value" doesn't exist, you write code that assumes that your values are infinite precision, and any issues that crop up as a result of floating point inaccuracies are features, not bugs.

Test Cases

```<code>(0, 0), (1, 5), (2, 3), (4, 8), (9, 2) => hyperbola
(1.2, 5.3), (4.1, 5.6), (9.1, 2.5), (0, 1), (4.2, 0) => ellipse
(5, 0), (4, 3), (3, 4), (0, 5), (0, -5) => circle
(1, 0), (0, 1), (2, 1), (3, 4), (4, 9) => parabola
</code>```

Body:
Matlab, 154 bytes

p=input();c=null([p.^2 prod(p,2) p 1+p(:,1)*0]),s={'circle' 'ellipse' 'parabola' 'hyperbola'};s{3+sign(c(3)^2-4*c(1)*c(2))-~max(abs(c(3)),abs(c(1)-c(2)))}

Saved some bytes thanks to Suever's suggestions.

Takes input as [x1 y1;x2 y2;x3 y3; etc]. This used a Vandermonde matrix, and finds the basis of its null space, which will always be a single vector. Then it calculates the discriminant and uses it to make an index between 1 and 4 which is used to get the string.

Ungolfed:

p=input();
c=null([p.^2 prod(p')' p ones(length(p),1)]);
s={'circle' 'ellipse' 'parabola' 'hyperbola'};
s{3+sign(c(3)^2-4*c(1)*c(2))-~max(abs(c(3)),abs(c(1)-c(2)))}

The sign(...) part calculates the discriminant, giving 1 if it's positive (hyperbola), -1 if it's negative (ellipse), and 0 if it's 0 (parabola). The max(...) subtracts 1 away if it is a circle. Matlab arrays are one-indexed, so add 3 to give values 1, 2, 3, 4, and use that to index the array of conic section names.


问:
Where will the cat go? (orbital mechanics)
A nearly massless cat is dropped in space (don't worry, with a space suit and everything) at the point (x, y, z) with velocity (vx, vy, vz). There is an fixed, infinitely dense planet (with volume of 0) at the point (0, 0, 0) and it attracts objects at distance r with acceleration 1/r^2. According to Newtonian gravity, where does the object go after time t?

Nearly massless in this case means you are outputting the value of lim (mass --> 0) <position of cat>. The mass is affected by the planet's gravity, but the planet is not affected by the cat's gravity. In other words, the central body is fixed.

This is somewhat similar to Code Golf: What is the spaceship's fate? [floating point version], but this is different because it is measuring accuracy.

You may implement a solution based on a simulation, which must run in less than 3 seconds, OR you may implement a program that gives an exact value (must also run in less than 3 seconds). See scoring details below. If you implement a simulation, it does not have to be exact, but your score will be lower because of the inaccuracy.

Input: x y z vx vy vz t, not necessarily integers representing x, y, z coordinates, velocity in the x, y, and z directions and time respectively. It is guaranteed that the speed of the cat is strictly less than the escape velocity at that altitude. Input may be taken from anywhere, including parameters to a function. The program must run in less than three seconds on my laptop for t < 2^30, which means, if you are running a simulation, you must adjust your timestep accordingly. If you are planning on hitting the 3 second limit for every test case, make sure there is a tuneable parameter that can make it more accurate/less accurate for speed gains, so that I can make it run in three seconds on my computer.

Output: x y z, the position after time t.

Since the two-body problem can be solved perfectly, it is in theory possible to get a perfect, correct answer.

Scoring: For any test case, the error is defined to be the distance between your output and the "true" output. The true output is defined to be the one that the test case snippet generates. If the error is less than 10^(-8), the error is rounded down to zero. Your score is the average error on 100 (or more) random test cases. If you write a perfectly accurate answer, you should get a score of 0; lowest score wins, and ties will be broken by code length.

Test cases:

```<code>1 0 0 0 -1 0 1000000000 --> 0.83789 -0.54584 0
</code>```

In this case , the orbit is perfectly circular with period 2*pi, so after circling 159154943 times, the cat ends up at approximately (0.83789, -0.54584). This isn't a test case your code will be tested on; if you submit a perfectly accurate answer, however, you may want to test it on this.

The snippet below generates random additional test cases and will be used to judge submissions; let me know if there is a bug with this:

var generateTestCase = function() {
  var periapsis = Math.random() * 10 + 0.5;
  var circularVelocity = Math.sqrt(1 / periapsis);
  var escapeVelocity = Math.sqrt(2) * circularVelocity;
  var v = Math.random() * (escapeVelocity - circularVelocity) + circularVelocity;
  var a = 1 / (2 / periapsis - v * v);
  var ecc = (a - periapsis) * (2 / periapsis - v * v);
  var semiLatus = a * (1 - ecc * ecc);
  var angM = Math.sqrt(semiLatus);
  var period = 2 * Math.PI * a * Math.sqrt(a);
  var getCoordAfterTime = function(t) {
    var meanAnomaly = t / (a * Math.sqrt(a));

    function E(e, M, n) {
      var result = M;
      for (var k = 1; k <= n; ++k) result = M + e * Math.sin(result);
      return result;
    }
    var eAnomaly = E(ecc, meanAnomaly, 10000);
    var radius = a * (1 - ecc * Math.cos(eAnomaly));
    var theta = Math.acos((semiLatus / radius - 1) / ecc);
    if (t > period / 2) theta = -theta;
    return {
      r: radius,
      t: theta,
      x: radius * Math.cos(theta),
      y: radius * Math.sin(theta)
    };
  }
  var t1 = Math.random() * period;
  var p1 = getCoordAfterTime(t1);
  var v1 = Math.sqrt(2 / p1.r - 1 / a);
  var velocityAngle1 = Math.acos(angM / p1.r / v1);
  var horizontal = Math.atan(-p1.x / p1.y);
  if (t1 < period / 2) {
    velocityAngle1 *= -1;
    horizontal += Math.PI;
  }
  var vx = v1 * Math.cos(horizontal + velocityAngle1);
  var vy = v1 * Math.sin(horizontal + velocityAngle1);
  var t2 = Math.random() * period;
  var p2 = getCoordAfterTime(t2);
  var v2 = Math.sqrt(2 / p2.r - 1 / a);
  var dummyPeriods = Math.floor(Math.random() * 100) * period + period;
  var rotate = function(x, y, z, th1, th2, th3) {
    var x1 = x * Math.cos(th1) - y * Math.sin(th1);
    var y1 = x * Math.sin(th1) + y * Math.cos(th1);
    var z1 = z;
    var x2 = x1 * Math.cos(th2) + z1 * Math.sin(th2);
    var y2 = y1;
    var z2 = -x1 * Math.sin(th2) + z1 * Math.cos(th2);
    var x3 = x2;
    var y3 = y2 * Math.cos(th3) - z2 * Math.sin(th3);
    var z3 = y2 * Math.sin(th3) + z2 * Math.cos(th3);
    return [x3, y3, z3];
  }
  var th1 = Math.random() * Math.PI * 2,
    th2 = Math.random() * 2 * Math.PI,
    th3 = Math.random() * 2 * Math.PI;
  var input = rotate(p1.x, p1.y, 0, th1, th2, th3)
    .concat(rotate(vx, vy, 0, th1, th2, th3))
    .concat([t2 - t1 + dummyPeriods]);
  var output = rotate(p2.x, p2.y, 0, th1, th2, th3);
  return input.join(" ") + " --> " + output.join(" ");
}
var $ = function(x) {
  return document.querySelector(x);
}
$("#onetestcase").onclick = function() {
  $("#result1").innerHTML = generateTestCase();
}
$("#huntestcases").onclick = function() {
  var result = [];
  for (var i = 0; i < 100; ++i) result.push(generateTestCase());
  $("#result100").innerHTML = result.join("\n");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <button id="onetestcase">Generate</button>
  <pre id="result1">```

  <button id="huntestcases">Generate 100 test cases</button>

```
</div></code>```

答:
Python 3.5 + NumPy, exact, 186 bytes

from math import*
def o(r,v,t):
 d=(r@r)**.5;W=2/d-v@v;U=W**1.5;b=[0,t*U+9]
 while 1:
  a=sum(b)/2;x=1-cos(a);y=sin(a)/U;k=r@v*x/W+d*y*W
  if a in b:return k*v-r*x/W/d+r
  b[k+a/U-y>t]=a
```

<p>This is an exact solution, using a formula I engineered based on Jesper Göranssonhis, “Symmetries of the Kepler problem”, 2015.  It uses a binary search to solve the transcendental equation Ax + B cos x + C sin x = D, which has no closed-form solution.</p>

<p>The function expects the position and velocity to be passed in as NumPy arrays:</p>

```>>> from numpy import array
>>> o(array([1,0,0]),array([0,-1,0]),1000000000)
array([ 0.83788718, -0.54584345,  0.        ])
>>> o(array([-1.1740058273269156,8.413493259550673,0.41996042044140003]),array([0.150014367067652,-0.09438816345868332,0.37294941703455975]),7999.348650387233)
array([-4.45269544,  6.93224929, -9.27292488])
```

Body:
Python 3.5 + NumPy, exact, 186 bytes

from math import*
def o(r,v,t):
 d=(r@r)**.5;W=2/d-v@v;U=W**1.5;b=[0,t*U+9]
 while 1:
  a=sum(b)/2;x=1-cos(a);y=sin(a)/U;k=r@v*x/W+d*y*W
  if a in b:return k*v-r*x/W/d+r
  b[k+a/U-y>t]=a

This is an exact solution, using a formula I engineered based on Jesper Göranssonhis, “Symmetries of the Kepler problem”, 2015.  It uses a binary search to solve the transcendental equation Ax + B cos x + C sin x = D, which has no closed-form solution.

The function expects the position and velocity to be passed in as NumPy arrays:

>>> from numpy import array
>>> o(array([1,0,0]),array([0,-1,0]),1000000000)
array([ 0.83788718, -0.54584345,  0.        ])
>>> o(array([-1.1740058273269156,8.413493259550673,0.41996042044140003]),array([0.150014367067652,-0.09438816345868332,0.37294941703455975]),7999.348650387233)
array([-4.45269544,  6.93224929, -9.27292488])


Title: Generate the minimal remainder sequence

Body:
Julia, <s>36</s> 33 bytes

\(n,k=2)=lcm(2:k)>n?n%(2:k):n\-~k

Try it online!


问:
In-between fractions

In-between fractions

The challenge:

You will need to create code that takes atleast 3 inputs; 2 integers and "a fraction representation" - whichever type suits your language for representing the fraction increments) ie. If you choose string the input would be "1/4" or you could choose 2 extra integer inputs or a tuple or w/e.

Input can be anywhere reasonable (STDIN, function arguments, from a file, etc.), and so can output (STDOUT, function return value, to a file, etc.)

Rules:

The input "fraction" will always be a valid fraction, less than 1; example "1/4"

The second input integer will always have a higher value than the first integer. I.E the first input integer will always have a lower value than the second.

The input integers can be negative.

Outputted fractions should be reduced as much as possible (simplified)

The code will need to output every "fraction step" between the 2 numbers in increments of the input fraction.

The code should be a program or function as stated here

Example 1:

Input: -2,3,"1/2"

Output:

```<code> -2
 -3/2
 -1
 -1/2
  0
  1/2
  1
  3/2
  2
  5/2
  3
</code>```

Example 2:

Input: 1,2,"2/3"

Output:

```<code>1
5/3
2
</code>```

or

```<code>1
4/3
2
</code>```

Note: Counting can start from either direction (thank you @Mego)

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

答:
Python 2, 81 bytes

from fractions import*
a,b,c=map(Fraction,input())
while a<b:print a;a+=c
print b
```

Try it online

Title: In-between fractions

Body:
Python 2, 81 bytes

from fractions import*
a,b,c=map(Fraction,input())
while a<b:print a;a+=c
print b

Try it online


答:
Mathematica, 16 bytes

```<code>Range@##⋃{#2}&
</code>```

An unnamed function that takes two integers and a rational number and returns a list of numbers, e.g.:

```<code>Range@##⋃{#2}&[-2, 3, 1/2]
(* {-2, -(3/2), -1, -(1/2), 0, 1/2, 1, 3/2, 2, 5/2, 3} *)
</code>```

Mathematica's Range does exactly what the challenge asks, except that it omits the upper bound if the difference between lower and upper bound isn't exactly a multiple of the step size. Therefore we take the Union (using ⋃) with the list containing only the upper bound which ensures that it appears exactly once. Note that Union will sort the result but we want it sorted anyway, since the step size is always positive. Also since we're working with rationals, they're automatically reduced as much as possible.

Title: In-between fractions

Body:
In-between fractions

The challenge:

You will need to create code that takes atleast 3 inputs; 2 integers and "a fraction representation" - whichever type suits your language for representing the fraction increments) ie. If you choose string the input would be "1/4" or you could choose 2 extra integer inputs or a tuple or w/e.

Input can be anywhere reasonable (STDIN, function arguments, from a file, etc.), and so can output (STDOUT, function return value, to a file, etc.)

Rules:

The input "fraction" will always be a valid fraction, less than 1; example "1/4"

The second input integer will always have a higher value than the first integer. I.E the first input integer will always have a lower value than the second.

The input integers can be negative.

Outputted fractions should be reduced as much as possible (simplified)

The code will need to output every "fraction step" between the 2 numbers in increments of the input fraction.

The code should be a program or function as stated here

Example 1:

Input: -2,3,"1/2"

Output:

```<code> -2
 -3/2
 -1
 -1/2
  0
  1/2
  1
  3/2
  2
  5/2
  3
</code>```

Example 2:

Input: 1,2,"2/3"

Output:

```<code>1
5/3
2
</code>```

or

```<code>1
4/3
2
</code>```

Note: Counting can start from either direction (thank you @Mego)

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

Body:
Mathematica, 16 bytes

Range@##⋃{#2}&

An unnamed function that takes two integers and a rational number and returns a list of numbers, e.g.:

Range@##⋃{#2}&[-2, 3, 1/2]
(* {-2, -(3/2), -1, -(1/2), 0, 1/2, 1, 3/2, 2, 5/2, 3} *)

Mathematica's Range does exactly what the challenge asks, except that it omits the upper bound if the difference between lower and upper bound isn't exactly a multiple of the step size. Therefore we take the Union (using ⋃) with the list containing only the upper bound which ensures that it appears exactly once. Note that Union will sort the result but we want it sorted anyway, since the step size is always positive. Also since we're working with rationals, they're automatically reduced as much as possible.


答:
Ruby, <s>32</s> <s>54</s> 48 bytes

->a,b,c{(a..b).step(c){|x|p x%1>0?x:x.to_i};p b}
```

<p>This solution is based on Mego's Python answer and assumes that <code>c</code> will always be a <code>Rational</code>, Ruby's fraction format. Try it online!</p>

<p><strong>Edit:</strong> Fixed a bug where integers weren't presented like integers. -6 bytes thanks to Not That Charles and MegaTom.</p>

<p>The functions are called in this way:</p>

<pre class="lang-ruby prettyprint-override"><code>> f=->a,b,c{(a..b).step(c){|x|p x%1>0?x:x.to_i};p b}
> f[1,4,Rational(2,3)]
1
(5/3)
(7/3)
3
(11/3)
4
</code>```

Title: In-between fractions

Body:
Ruby, <s>32</s> <s>54</s> 48 bytes

->a,b,c{(a..b).step(c){|x|p x%1>0?x:x.to_i};p b}

This solution is based on Mego's Python answer and assumes that c will always be a Rational, Ruby's fraction format. Try it online!

Edit: Fixed a bug where integers weren't presented like integers. -6 bytes thanks to Not That Charles and MegaTom.

The functions are called in this way:

> f=->a,b,c{(a..b).step(c){|x|p x%1>0?x:x.to_i};p b}
> f[1,4,Rational(2,3)]
1
(5/3)
(7/3)
3
(11/3)
4

ContentLicense: CC BY-SA 4.0


答:
Haskell, <s>31</s> 26 bytes

f a b c=min[b]$a:f(a+c)b c
```

<p>Lazy evaluation FTW!  Demo:</p>

```*Main> import Data.Ratio
*Main Data.Ratio> f (-2) 3 (1%2)
[(-2) % 1,(-3) % 2,(-1) % 1,(-1) % 2,0 % 1,1 % 2,1 % 1,3 % 2,2 % 1,5 % 2,3 % 1]
*Main Data.Ratio> f 1 2 (2%3)
[1 % 1,5 % 3,2 % 1]
```

(I was initially tempted by Haskell’s [a,a+c..b] notation, but it has some quirks that necessitate something like f a b c|l<-[a,a+c..b-c/2]=l++[b|last l<b] for 41 bytes or f a b c=[x|x<-[a,a+c..],x<b]++[b] for 33.)

Title: In-between fractions

Body:
Haskell, <s>31</s> 26 bytes

f a b c=min[b]$a:f(a+c)b c

Lazy evaluation FTW!  Demo:

*Main> import Data.Ratio
*Main Data.Ratio> f (-2) 3 (1%2)
[(-2) % 1,(-3) % 2,(-1) % 1,(-1) % 2,0 % 1,1 % 2,1 % 1,3 % 2,2 % 1,5 % 2,3 % 1]
*Main Data.Ratio> f 1 2 (2%3)
[1 % 1,5 % 3,2 % 1]

(I was initially tempted by Haskell’s [a,a+c..b] notation, but it has some quirks that necessitate something like f a b c|l<-[a,a+c..b-c/2]=l++[b|last l<b] for 41 bytes or f a b c=[x|x<-[a,a+c..],x<b]++[b] for 33.)


问:
Showcase of Languages

Notes

This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional showcase questions.

This is no longer a popularity-contest, nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

All answers should include the name of the programming language at the top of the post, prefixed by a #.

Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

The snippets do not need to be related. In fact, snippets that are too related may be redundant.

Since this is not a contest, all programming languages are welcome, whenever they were created.

Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul></code>```

答:
Octave

Note:

I got to say hello to a little earthling in the delivery room a few weeks back. Although she's lighter than a ball, she takes up quite a lot of my time. I'll redirect my focus to more important things (for instance showing of the awesomeness of Octave) when I have some spare time. Until then, please have some patience =)

Octave and MATLAB are very similar, and many of the nice features flawr has showcased would be good showcases for Octave as well. I will try to avoid reusing any of the material flawr has already used.

Snippet 1:

```<code>.
</code>```

A full stop punctuation is a very versatile operator, and helps solve a lot of tasks very elegant:

Element-wise operations: a.*b (equvalent to times(a,b))

Transpose: a.' (equivalent to transpose(a))

Using only ' gives the complex conjugated transpose (equivalent to ctranspose(a))

Short hand notation for creating and accessing structs: a.b (equvalent to struct(a,b)

Decimal point, of course: 314/100, 3.14, and .314e1 are all the same.

Snippet 2:

```<code>++
</code>```

Increment operators are one of the great features in Octave, that doesn't exist in MATLAB. It's known to most programmers as languages such as C++, Java, JavaScript, PHP and Perl all support it. Nevertheless, it's awesome when golfing, and often makes Octave submissions a bit more competitive than MATLAB. x++ is 2 bytes shorter than x=x+1.

Snippets 3:

Edit: 02.05.2016 - I'll get to this ASAP!

Snippet 4:

```<code>a+a'
</code>```

This is a great way to create a grid of values, similar to meshgrid in MATLAB.

```<code>a = 0:3;
a+a'
ans =
   0   1   2   3
   1   2   3   4
   2   3   4   5
   3   4   5   6
</code>```

You can of course use this with vectors of different lengths. a+b' produces the same result as:

```<code>bsxfun(@plus,a,b')
</code>```

Snippet 5:

```<code>a=b=1
</code>```

In Octave, you assign a value to several variables at the same time. The MATLAB equivalent is 7 bytes: a=1;b=1

Snippet 6:

Edit: 02.05.2016: Octave is way better than MATLAB for golfing. More snippets = More possibilities to demonstrate. I'll get to this ASAP!

Factoid:

Octave is known to most as a free alternative to Mathwork's MATLAB. Octave was originally conceived (in about 1988) to be companion software for an undergraduate-level textbook on chemical reactor design1

The name has nothing to do with music, but is actually the name of one of the author's former professors who wrote a famous textbook on chemical reaction engineering, and who was also well known for his ability to do quick "back of the envelope" calculations.2.

Title: Showcase of Languages

Body:
Octave

Note:

I got to say hello to a little earthling in the delivery room a few weeks back. Although she's lighter than a ball, she takes up quite a lot of my time. I'll redirect my focus to more important things (for instance showing of the awesomeness of Octave) when I have some spare time. Until then, please have some patience =)

Octave and MATLAB are very similar, and many of the nice features flawr has showcased would be good showcases for Octave as well. I will try to avoid reusing any of the material flawr has already used.

Snippet 1:

.

A full stop punctuation is a very versatile operator, and helps solve a lot of tasks very elegant:

Element-wise operations: a.*b (equvalent to times(a,b))

Transpose: a.' (equivalent to transpose(a))

Using only ' gives the complex conjugated transpose (equivalent to ctranspose(a))

Short hand notation for creating and accessing structs: a.b (equvalent to struct(a,b)

Decimal point, of course: 314/100, 3.14, and .314e1 are all the same.

Snippet 2:

++

Increment operators are one of the great features in Octave, that doesn't exist in MATLAB. It's known to most programmers as languages such as C++, Java, JavaScript, PHP and Perl all support it. Nevertheless, it's awesome when golfing, and often makes Octave submissions a bit more competitive than MATLAB. x++ is 2 bytes shorter than x=x+1.

Snippets 3:

Edit: 02.05.2016 - I'll get to this ASAP!

Snippet 4:

a+a'

This is a great way to create a grid of values, similar to meshgrid in MATLAB.

a = 0:3;
a+a'
ans =
   0   1   2   3
   1   2   3   4
   2   3   4   5
   3   4   5   6

You can of course use this with vectors of different lengths. a+b' produces the same result as:

bsxfun(@plus,a,b')

Snippet 5:

a=b=1

In Octave, you assign a value to several variables at the same time. The MATLAB equivalent is 7 bytes: a=1;b=1

Snippet 6:

Edit: 02.05.2016: Octave is way better than MATLAB for golfing. More snippets = More possibilities to demonstrate. I'll get to this ASAP!

Factoid:

Octave is known to most as a free alternative to Mathwork's MATLAB. Octave was originally conceived (in about 1988) to be companion software for an undergraduate-level textbook on chemical reactor design1

The name has nothing to do with music, but is actually the name of one of the author's former professors who wrote a famous textbook on chemical reaction engineering, and who was also well known for his ability to do quick "back of the envelope" calculations.2.


答:
C, 89 bytes

```<code>a,i=2;main(l,n){for(n=atoi(gets(n))?:!puts(n);n/l;printf("%d ",n%i++))for(a=l;l%i;l+=a);}
</code>```

Compile with gcc. Try it online: n=59, n=0.

Title: Generate the minimal remainder sequence

Body:
Every number can be represented using an infinitely long remainder sequence.  For example, if we take the number 7, and perform 7mod2, then 7mod3, then 7mod4, and so on, we get 1,1,3,2,1,0,7,7,7,7,.....

However, we need the shortest possible remainder subsequence that can still be used to distinguish it from all lower numbers.  Using 7 again, [1,1,3] is the shortest subsequence, because all of the previous subsequences don't start with [1,1,3]:

```<code>0: 0,0,0,0...
1: 1,1,1,1...
2: 0,2,2,2...
3: 1,0,3,3...
4: 0,1,0,4...
5: 1,2,1,0...
6: 0,0,2,1...
</code>```

Note that [1,1] doesn't work to represent 7, because it can also be used to represent 1.  However, you should output [1] with an input of 1.

Input/Output

Your input is a non-negative integer.  You must output a sequence or list of the minimal-length sequence of remainders as defined above.

Test cases:

```<code>0: 0
1: 1
2: 0,2
3: 1,0
4: 0,1
5: 1,2
6: 0,0,2
7: 1,1,3
8: 0,2,0
9: 1,0,1
10: 0,1,2
11: 1,2,3
12: 0,0,0,2
30: 0,0,2,0
42: 0,0,2,2
59: 1,2,3,4
60: 0,0,0,0,0,4
257: 1,2,1,2,5,5
566: 0,2,2,1,2,6,6
1000: 0,1,0,0,4,6,0,1
9998: 0,2,2,3,2,2,6,8,8,10
9999: 1,0,3,4,3,3,7,0,9,0
</code>```

Here are the first 10,000 sequences, in case you are interested (the line numbers are off by 1).

This is a code-golf, so make it as short as you can in your favorite language.  Fake bonus points for any answers that are fast!

Body:
C, 89 bytes

a,i=2;main(l,n){for(n=atoi(gets(n))?:!puts(n);n/l;printf("%d ",n%i++))for(a=l;l%i;l+=a);}

Compile with gcc. Try it online: n=59, n=0.


答:
Matlab with Symbolic Toolbox / Octave with SymPy, 27 bytes

Thanks to @sanchises for pointing out an error, now corrected

```<code>@(a,b,c)sym(union(a:c:b,b))
</code>```

This is an anonymous function. To call it, assign it to a variable or use ans.

Example:

```<code>>> @(a,b,c)sym(union(a:c:b,b))
ans =
    @(a,b,c)sym(union(a:c:b,b))
>> ans(-2,3,1/2)
ans =
[ -2, -3/2, -1, -1/2, 0, 1/2, 1, 3/2, 2, 5/2, 3]
</code>```

Title: In-between fractions

Body:
Matlab with Symbolic Toolbox / Octave with SymPy, 27 bytes

Thanks to @sanchises for pointing out an error, now corrected

@(a,b,c)sym(union(a:c:b,b))

This is an anonymous function. To call it, assign it to a variable or use ans.

Example:

>> @(a,b,c)sym(union(a:c:b,b))
ans =
    @(a,b,c)sym(union(a:c:b,b))
>> ans(-2,3,1/2)
ans =
[ -2, -3/2, -1, -1/2, 0, 1/2, 1, 3/2, 2, 5/2, 3]


答:
Python 2, 142 bytes

def f(n,m):return f(n-1,m+3)+[' '*(m+x)+(y*n)[x*2:]for x,y in((2,' \\__/\\'),(1,'/ /_/\\'),(0,'/__\\_\\'))]if n else[]
print '\n'.join(f(n,0))
```

The principle is very similar to other answers: take three repeated strings and then layer them in such a way that you only need to trim some of them to get the triangle, then pad them on the left.

Title: Build a triangle without any triangles

Body:
As a little kid, I liked to play with these toys a lot:

They probably intended for these to be used for art, but I always used them for math! Fractals, patterns, etc. One time, I was given this challenge:

Build a triangle without using any of the green triangle tiles.

This challenge stumped me for the longest time, until I stumbled upon a really beautiful and simple way to do it with just 3 trapezoids:

```<code>  /\
 /_/\
/__\_\
</code>```

Now, take this triangle, and rotate it:

```<code>______
\ \__/
 \/ /
  \/
</code>```

Using these two triangles, we can construct larger triangles out of them. Here is a triangle of height 2:

```<code>     /\
    /_/\
   /__\_\
  /\ \__/\
 /_/\/ /_/\
/__\_\/__\_\
</code>```

And here are triangles of height 3-7:

```<code>#3
        /\
       /_/\
      /__\_\
     /\ \__/\
    /_/\/ /_/\
   /__\_\/__\_\
  /\ \__/\ \__/\
 /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\

#4
           /\
          /_/\
         /__\_\
        /\ \__/\
       /_/\/ /_/\
      /__\_\/__\_\
     /\ \__/\ \__/\
    /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\

#5
              /\
             /_/\
            /__\_\
           /\ \__/\
          /_/\/ /_/\
         /__\_\/__\_\
        /\ \__/\ \__/\
       /_/\/ /_/\/ /_/\
      /__\_\/__\_\/__\_\
     /\ \__/\ \__/\ \__/\
    /_/\/ /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\/__\_\

#6
                 /\
                /_/\
               /__\_\
              /\ \__/\
             /_/\/ /_/\
            /__\_\/__\_\
           /\ \__/\ \__/\
          /_/\/ /_/\/ /_/\
         /__\_\/__\_\/__\_\
        /\ \__/\ \__/\ \__/\
       /_/\/ /_/\/ /_/\/ /_/\
      /__\_\/__\_\/__\_\/__\_\
     /\ \__/\ \__/\ \__/\ \__/\
    /_/\/ /_/\/ /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\/__\_\/__\_\

#7
                    /\
                   /_/\
                  /__\_\
                 /\ \__/\
                /_/\/ /_/\
               /__\_\/__\_\
              /\ \__/\ \__/\
             /_/\/ /_/\/ /_/\
            /__\_\/__\_\/__\_\
           /\ \__/\ \__/\ \__/\
          /_/\/ /_/\/ /_/\/ /_/\
         /__\_\/__\_\/__\_\/__\_\
        /\ \__/\ \__/\ \__/\ \__/\
       /_/\/ /_/\/ /_/\/ /_/\/ /_/\
      /__\_\/__\_\/__\_\/__\_\/__\_\
     /\ \__/\ \__/\ \__/\ \__/\ \__/\
    /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\
   /__\_\/__\_\/__\_\/__\_\/__\_\/__\_\
  /\ \__/\ \__/\ \__/\ \__/\ \__/\ \__/\
 /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\/ /_/\
/__\_\/__\_\/__\_\/__\_\/__\_\/__\_\/__\_\
</code>```

The Challenge

Write a program or function that takes a number n and prints a triangle-less triangle of height n. Trailing spaces on each line is acceptable, and up to one trailing or leading newline is also acceptable. IO can be in any reasonable format. The input is guarenteed to be a positive integer, so you don't have to worry about negative numbers, decimals, non-numbers etc.

Shortest answer in bytes wins!

Body:
Python 2, 142 bytes

def f(n,m):return f(n-1,m+3)+[' '*(m+x)+(y*n)[x*2:]for x,y in((2,' \\__/\\'),(1,'/ /_/\\'),(0,'/__\\_\\'))]if n else[]
print '\n'.join(f(n,0))

The principle is very similar to other answers: take three repeated strings and then layer them in such a way that you only need to trim some of them to get the triangle, then pad them on the left.


答:
Ruby, 52 bytes

->n{m=t=1;a=[];(a<<n%m)until n<t=t.lcm(m+=1);a<<n%m}
```

<p>This solution checks every possible <code>m</code> starting from 2 that be the remainder that makes the sequence unique. What makes the last <code>m</code> unique is not the remainder itself, but that the <code>m</code> is the last member of the smallest range <code>(2..m)</code> where the least common multiple (LCM) of that range is greater than <code>n</code>. This is due to the Chinese Remainder Theorem, where to uniquely determine what number <code>n</code> is with a number of remainders, the LCM of those remainders must be greater than <code>n</code> (if selecting <code>n</code> from <code>(1..n)</code>; if selecting <code>n</code> from <code>a..b</code>, the LCM needs only be greater than <code>b-a</code>)</p>

<p><strong>Note:</strong> I put <code>a<<n%m</code> at the end of the code because <code>until n<t=t.lcm(m+=1)</code> short-circuits before <code>a</code> has received the last element to make it unique.</p>

<p>If anyone has any golfing suggestions, please let me know in the comments or in PPCG chat.</p>

<p><strong>Ungolfing:</strong></p>

<pre class="lang-ruby prettyprint-override"><code>def remainder_sequence(num)
  # starting with 1, as the statements in the until loop immediately increments divisor
  divisor = 1
  # starts with 1 instead of 2, as the statements in the until loop
  # immediately change product to a new lcm
  product = 1
  remainders = []

  # this increments divisor first then checks the lcm of product and divisor
  # before checking if num is less than this lcm
  until num < (product = product.lcm(divisor = divisor + 1))
    remainders << num % divisor
  end

  # until always short circuits before the last element is entered
  # so this enters the last element and returns
  return remainders << num % divisor
end
</code>```

Title: Generate the minimal remainder sequence

Body:
Ruby, 52 bytes

->n{m=t=1;a=[];(a<<n%m)until n<t=t.lcm(m+=1);a<<n%m}

This solution checks every possible m starting from 2 that be the remainder that makes the sequence unique. What makes the last m unique is not the remainder itself, but that the m is the last member of the smallest range (2..m) where the least common multiple (LCM) of that range is greater than n. This is due to the Chinese Remainder Theorem, where to uniquely determine what number n is with a number of remainders, the LCM of those remainders must be greater than n (if selecting n from (1..n); if selecting n from a..b, the LCM needs only be greater than b-a)

Note: I put a<<n%m at the end of the code because until n<t=t.lcm(m+=1) short-circuits before a has received the last element to make it unique.

If anyone has any golfing suggestions, please let me know in the comments or in PPCG chat.

Ungolfing:

def remainder_sequence(num)
  # starting with 1, as the statements in the until loop immediately increments divisor
  divisor = 1
  # starts with 1 instead of 2, as the statements in the until loop
  # immediately change product to a new lcm
  product = 1
  remainders = []

  # this increments divisor first then checks the lcm of product and divisor
  # before checking if num is less than this lcm
  until num < (product = product.lcm(divisor = divisor + 1))
    remainders << num % divisor
  end

  # until always short circuits before the last element is entered
  # so this enters the last element and returns
  return remainders << num % divisor
end


答:
Python 2, 73 70 69 65 bytes

```<code>i=l=1
n=input()
while l<=n|1:
 i+=1;a=l;print n%i
 while l%i:l+=a
</code>```

A full program. @Dennis saved 4 bytes by improving the way zero is handled.

Title: Generate the minimal remainder sequence

Body:
Python 2, 73 70 69 65 bytes

i=l=1
n=input()
while l<=n|1:
 i+=1;a=l;print n%i
 while l%i:l+=a

A full program. @Dennis saved 4 bytes by improving the way zero is handled.


答:
T-SQL 2012+, <s>831</s> <s>535</s> <s>477</s> <s>270</s> <s>246</s> <s>240</s> 219 bytes

Please note this is a one liner - sql doesn't have build in function to reduce the fraction.
May not be the best language for this type of question. It is human readable(kind of - compared to some of the other languages).

DECLARE @f INT=-5,@t INT=3,@n INT=3,@ INT=8;

WITH C as(SELECT
top((@t*@-@f*@)/@n+1)ROW_NUMBER()OVER(ORDER BY @)M
FROM sys.messages)SELECT(SELECT
IIF(V%@=0,LEFT(V/@,9),CONCAT(V/MAX(M),'/',ABS(@)/MAX(M)))FROM c
WHERE V%M=0AND @%M=0)FROM(SELECT
@f*@+@n*~-M V FROM c)k
```

Try it online

Title: In-between fractions

Body:
T-SQL 2012+, <s>831</s> <s>535</s> <s>477</s> <s>270</s> <s>246</s> <s>240</s> 219 bytes

Please note this is a one liner - sql doesn't have build in function to reduce the fraction.
May not be the best language for this type of question. It is human readable(kind of - compared to some of the other languages).

DECLARE @f INT=-5,@t INT=3,@n INT=3,@ INT=8;

WITH C as(SELECT
top((@t*@-@f*@)/@n+1)ROW_NUMBER()OVER(ORDER BY @)M
FROM sys.messages)SELECT(SELECT
IIF(V%@=0,LEFT(V/@,9),CONCAT(V/MAX(M),'/',ABS(@)/MAX(M)))FROM c
WHERE V%M=0AND @%M=0)FROM(SELECT
@f*@+@n*~-M V FROM c)k

Try it online


问:
Minifying math statements

The Challenge

You are the owner of an amazing service called Coyote Beta, which magically answers math questions its users send to it over the internet.

But it turns out, bandwidth is expensive.  You have two choices, either create a "Coyote Beta Pro" or find some way to solve this.  Just recently, someone queried (x + 2). Couldn't the client send x+2, and the user would see no difference?

The Task

Your task is to "minify" math expressions.  Given an input expression, you must get rid of whitespace and parentheses until it gives a minimal representation of the same input.  The parentheses around associative operations need not be preserved.

The only operators given here are +, -, *, /, and ^ (exponentiation), with standard mathematical associativity and precedence.  The only whitespace given in the input will be actual space characters.

Sample Input/Output

```<code>Input       | Output
------------|--------------
(2+x) + 3   | 2+x+3
((4+5))*x   | (4+5)*x
z^(x+42)    | z^(x+42)
x - ((y)+2) | x-(y+2)
(z - y) - x | z-y-x
x^(y^2)     | x^y^2
x^2 / z     | x^2/z
- (x + 5)+3 | -(x+5)+3
</code>```

Scoring

Input/output can use any preferred method.  The smallest program in bytes wins.

Exact bits

Exponentiation is right associative and also follows standard math precedence (being the highest).  A valid numeric literal is /[0-9]+/, and a valid variable literal is /[a-z]+/.  A single variable literal represents a single value even when its character length is longer than 1.

What is meant by "the parentheses around associative operations need not be preserved" is that the output should consist of an expression that results in an identical parse tree, with the exception that associative operations can be rearranged.

答:
C++, 284 bytes

Golfed

#include<iostream>
#include<algorithm>
int main(){std::string e;std::getline(std::cin,e);e.erase(std::remove_if(e.begin(),e.end(),isspace),e.end());for(int x=0;x<e.length();x++){if(e[x]=='('&&e[x+1]=='('){e.erase(x,1);}if(e[x]==')'&&e[x+1]==')'){e.erase(x,1);}}std::cout<<e;return 0;}
```
<p><strong>Ungolfed</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include<iostream>
#include<algorithm>

int main()
{
    std::string e;
    std::getline(std::cin, e);
    e.erase(std::remove_if(e.begin(), e.end(), isspace), e.end());
    for(int x = 0; x < e.length(); x++) {
        if (e[x] == '(' && e[x+1] == '('){
            e.erase(x, 1);
        }
        if (e[x] == ')' && e[x+1] == ')'){
            e.erase(x, 1);
        }
    }
    std::cout<<e;
    return 0;
}
</code>```

Title: Minifying math statements

Body:
C++, 284 bytes

Golfed

#include<iostream>
#include<algorithm>
int main(){std::string e;std::getline(std::cin,e);e.erase(std::remove_if(e.begin(),e.end(),isspace),e.end());for(int x=0;x<e.length();x++){if(e[x]=='('&&e[x+1]=='('){e.erase(x,1);}if(e[x]==')'&&e[x+1]==')'){e.erase(x,1);}}std::cout<<e;return 0;}

Ungolfed

#include<iostream>
#include<algorithm>

int main()
{
    std::string e;
    std::getline(std::cin, e);
    e.erase(std::remove_if(e.begin(), e.end(), isspace), e.end());
    for(int x = 0; x < e.length(); x++) {
        if (e[x] == '(' && e[x+1] == '('){
            e.erase(x, 1);
        }
        if (e[x] == ')' && e[x+1] == ')'){
            e.erase(x, 1);
        }
    }
    std::cout<<e;
    return 0;
}


答:
Python 2, 118 bytes

```<code>def f(n,s=["/\\ \\__","/_/\\/ ","/__\\_\\"]):
 print'\n'.join(map(lambda x:' '*(n*3-x)+(n*s[x%3])[:x*2+2],range(n*3)))
</code>```

Similar approach to Level River St's Ruby answer.

Try it online

Title: Build a triangle without any triangles

Body:
Python 2, 118 bytes

def f(n,s=["/\\ \\__","/_/\\/ ","/__\\_\\"]):
 print'\n'.join(map(lambda x:' '*(n*3-x)+(n*s[x%3])[:x*2+2],range(n*3)))

Similar approach to Level River St's Ruby answer.

Try it online


问:
Sort an Integer List

The Challenge

It's quite simple really, sort a list of numbers.

Details

You must sort a list of numbers in ascending order, without using any built-in sorting functions/libraries/etc (i.e. list.sort() in Python).

Input/output can be done in any method you choose, as long as it is human readable.

Standard loopholes are disallowed as always.

Shortest code in bytes wins.

You must explain/list what sort method you used (Bubble, Insertion, Selection, etc.)

Input will not contain duplicates.

Sample Input/Output

Input: 99,-2,53,4,67,55,23,43,88,-22,36,45

Output: -22,-2,4,23,36,43,45,53,55,67,88,99

Note: A near direct opposite of Sort a List of Numbers

答:
Pyth - <s>15</s> <s>13</s> <s>11</s> 10 bytes

Two bytes saved thanks to @Jakube.

Bogosort.

```<code>f!s>VTtT.p
</code>```

Try it online here.

I don't need the h cuz we are guaranteed no duplicates.

Title: Sort an Integer List

Body:
Pyth - <s>15</s> <s>13</s> <s>11</s> 10 bytes

Two bytes saved thanks to @Jakube.

Bogosort.

f!s>VTtT.p

Try it online here.

I don't need the h cuz we are guaranteed no duplicates.


答:
Brachylog, <s>12</s> 7 bytes

```<code>p.'(s>)
</code>```

This uses permutation sort, which is obviously terrible, but hey it's shorter than Pyth!

Explanation

```<code>p.       Unifies the output with a permutation of the input
  '(  )  True if what's inside the parentheses cannot be proven, else backtrack and
         try with another permutation of the input.
    s    Take an ordered subset from the output
     >   True if the first element is bigger than the second (hence not sorted)
         We don't need to check that the subset is 2 elements long because > will be false
         for inputs that are not 2 elements long anyway
</code>```

Title: Sort an Integer List

Body:
The Challenge

It's quite simple really, sort a list of numbers.

Details

You must sort a list of numbers in ascending order, without using any built-in sorting functions/libraries/etc (i.e. list.sort() in Python).

Input/output can be done in any method you choose, as long as it is human readable.

Standard loopholes are disallowed as always.

Shortest code in bytes wins.

You must explain/list what sort method you used (Bubble, Insertion, Selection, etc.)

Input will not contain duplicates.

Sample Input/Output

Input: 99,-2,53,4,67,55,23,43,88,-22,36,45

Output: -22,-2,4,23,36,43,45,53,55,67,88,99

Note: A near direct opposite of Sort a List of Numbers

Body:
Brachylog, <s>12</s> 7 bytes

p.'(s>)

This uses permutation sort, which is obviously terrible, but hey it's shorter than Pyth!

Explanation

p.       Unifies the output with a permutation of the input
  '(  )  True if what's inside the parentheses cannot be proven, else backtrack and
         try with another permutation of the input.
    s    Take an ordered subset from the output
     >   True if the first element is bigger than the second (hence not sorted)
         We don't need to check that the subset is 2 elements long because > will be false
         for inputs that are not 2 elements long anyway


问:
Distinct subsets that sum to a given number
Write a function that gets as an input a sorted array of positive numbers A, and an additional number n. The Task is to print out all distinct subsets of A, that sum to n.

Example:

```<code>Input:
A = [1,2,2,4,4]
n = 9

Output:
[1,2,2,4]
[1,4,4]
</code>```

Bonus:
-50% if your code doesn't store duplicate subset (the same subset but in different order) intern. The function will not store more than one duplicate subset in memory at a time.

Shortest code in bytes wins.

答:
Mathematica, 33 bytes

```<code>Cases[{}⋃Subsets@#,s_/;Tr@s==#2]&
</code>```

Mathematica, 57 bytes (-50%) = 28.5 bytes

```<code>Cases[Fold[Append@@@Thread@{##}⋃#&,{{}},#],s_/;Tr@s==#2]&
</code>```

Body:
Mathematica, 33 bytes

Cases[{}⋃Subsets@#,s_/;Tr@s==#2]&

Mathematica, 57 bytes (-50%) = 28.5 bytes

Cases[Fold[Append@@@Thread@{##}⋃#&,{{}},#],s_/;Tr@s==#2]&


答:
Python 3, <s>91</s> <s>62</s> 47 bytes

def f(z):
 while z:m=min(z);z.remove(m);yield m
```

Thanks to wnnmaw and Seeq for golfing help.

The argument z should be a list. This is a variant of selection sort.

I'm not sure how min stacks up against built-in sorting functions, since I'm not sure how Python implements min. Hopefully, this solution is still okay. Any golfing suggestions in the comments or in PPCG chat are welcome.

Title: Sort an Integer List

Body:
Python 3, <s>91</s> <s>62</s> 47 bytes

def f(z):
 while z:m=min(z);z.remove(m);yield m

Thanks to wnnmaw and Seeq for golfing help.

The argument z should be a list. This is a variant of selection sort.

I'm not sure how min stacks up against built-in sorting functions, since I'm not sure how Python implements min. Hopefully, this solution is still okay. Any golfing suggestions in the comments or in PPCG chat are welcome.


答:
MATL, <s>11</s> 10 bytes

```<code>Y@t!d0>AY)
</code>```

Extremely inefficient examination of all permutations of the input.

Try it Online!

Explanation

```<code>        % Implicitly grab input array
Y@      % Compute all permutations (each permutation as a row)
t       % Duplicate this matrix
!d      % Transpose and take the differences between the values
0>A     % Find the rows where all differences are > 0
Y)      % Return only the row where this is true
        % Implicitly display the result
</code>```

Title: Sort an Integer List

Body:
MATL, <s>11</s> 10 bytes

Y@t!d0>AY)

Extremely inefficient examination of all permutations of the input.

Try it Online!

Explanation

        % Implicitly grab input array
Y@      % Compute all permutations (each permutation as a row)
t       % Duplicate this matrix
!d      % Transpose and take the differences between the values
0>A     % Find the rows where all differences are > 0
Y)      % Return only the row where this is true
        % Implicitly display the result


答:
Jelly, 3 bytes

```<code>Œ!Ṃ
</code>```

This generates all permutations of the input list, then selects the lexographically smallest permutation. Very efficient.

Credits to @Adnan who had the same idea independently.

Try it online!

Jelly, 4 bytes

```<code>ṂrṀf
</code>```

This builds the range from the minimum of the list to the maximum of the list, then discards the range elements not present in the original list. This is technically a bucket sort, with very small buckets. I'm not aware of a name for this specific variant.

Try it online!

How it works

```<code>ṂrṀf  Main link. Argument: A (list/comma-separated string)

Ṃ     Compute the minimum of A.
  Ṁ   Compute the maximum of A.
 r    Yield the inclusive range from the minimum to the maximum.
   f  Filter the range by presence in A.
</code>```

Title: Sort an Integer List

Body:
Jelly, 3 bytes

Œ!Ṃ

This generates all permutations of the input list, then selects the lexographically smallest permutation. Very efficient.

Credits to @Adnan who had the same idea independently.

Try it online!

Jelly, 4 bytes

ṂrṀf

This builds the range from the minimum of the list to the maximum of the list, then discards the range elements not present in the original list. This is technically a bucket sort, with very small buckets. I'm not aware of a name for this specific variant.

Try it online!

How it works

ṂrṀf  Main link. Argument: A (list/comma-separated string)

Ṃ     Compute the minimum of A.
  Ṁ   Compute the maximum of A.
 r    Yield the inclusive range from the minimum to the maximum.
   f  Filter the range by presence in A.


答:
05AB1E, 2 bytes

Code:

```<code>œß
</code>```

Same algorithm as the Jelly answer. Computes all permutations of the input and pops out the smallest one.

Try it online!

A more efficient method is:

```<code>E[ß,Ž
</code>```

Performs selection sort. Uses CP-1252 encoding.

Try it online!

Title: Sort an Integer List

Body:
05AB1E, 2 bytes

Code:

œß

Same algorithm as the Jelly answer. Computes all permutations of the input and pops out the smallest one.

Try it online!

A more efficient method is:

E[ß,Ž

Performs selection sort. Uses CP-1252 encoding.

Try it online!


答:
C#, <s>523</s> <s>519</s> 504 bytes

Check the in-code comments to see how it works!

Golfed

using System;using System.Collections.Generic;namespace n{class p{static void Main(string[]a){foreach(String s in a){String r=s.Replace(" ","");List<int>l=new List<int>();for(int i=0;i<r.Length;i++){if(r[i]=='('){l.Add(i);continue;}if(r[i]==')'){switch(r[Math.Max(l[l.Count-1]-1,0)]){case'+':case'(':switch(r[Math.Min(i+1,r.Length-1)]){case'+':case'-':case')':r=r.Remove(Math.Max(l[l.Count-1],0),1);r=r.Remove(Math.Min(i,r.Length)-1,1);i-=2;break;}break;}l.RemoveAt(l.Count-1);}}Console.WriteLine(r);}}}}
```

<hr>

<h2>Ungolfed</h2>

<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;

namespace n {
    class p {
        static void Main( string[] a ) {
            // Loop every String given for the program
            foreach (String s in a) {
                // Get rid of the spaces
                String r = s.Replace( " ", "" );

                // A little helper that will have the indexes of the '('
                List<int> l = new List<int>();

                // Begin the optimizatio process
                for (int i = 0; i < r.Length; i++) {
                    // If char is an '(', add the index to the helper list and continue
                    if (r[ i ] == '(') {
                        l.Add( i );
                        continue;
                    }

                    // If the char is an ')', validate the group
                    if (r[ i ] == ')') {
                        // If the char before the last '(' is an '+' or '(' ...
                        switch (r[ Math.Max( l[ l.Count - 1 ] - 1, 0 ) ]) {
                            case '+':
                            case '(':
                                // ... and the char after the ')' we're checking now is an '+', '-' or ')' ...
                                switch (r[ Math.Min( i + 1, r.Length - 1 ) ]) {
                                    case '+':
                                    case '-':
                                    case ')':
                                        // Remove the '()' since they're most likely desnecessary.
                                        r = r.Remove( Math.Max( l[ l.Count - 1 ], 0 ), 1 );
                                        r = r.Remove( Math.Min( i, r.Length ) - 1, 1 );

                                        // Go two steps back in the loop since we removed 2 chars from the String,
                                        //   otherwise we would miss some invalid inputs
                                        i -= 2;
                                        break;
                                }

                                break;
                        }

                        // Remove the last inserted index of '(' from the list,
                        //   since we matched an ')' for it.
                        l.RemoveAt( l.Count - 1 );
                    }
                }

                // Print the result
                Console.WriteLine( r );
            }
        }
    }
}
</code>```

Side notes

Fixed some typos and renamed some vars.

Nested an switch to get rid of an unnecessary variable. Also, fixed a bug that would render some solutions invalid, reported by Anders Kaseorg.

P.S.: If you have a tip or found a bug, please let me know in the comments and I'll try to fix it ( I'll then add a note about the bug fix with your name ;) )

Title: Minifying math statements

Body:
The Challenge

You are the owner of an amazing service called Coyote Beta, which magically answers math questions its users send to it over the internet.

But it turns out, bandwidth is expensive.  You have two choices, either create a "Coyote Beta Pro" or find some way to solve this.  Just recently, someone queried (x + 2). Couldn't the client send x+2, and the user would see no difference?

The Task

Your task is to "minify" math expressions.  Given an input expression, you must get rid of whitespace and parentheses until it gives a minimal representation of the same input.  The parentheses around associative operations need not be preserved.

The only operators given here are +, -, *, /, and ^ (exponentiation), with standard mathematical associativity and precedence.  The only whitespace given in the input will be actual space characters.

Sample Input/Output

```<code>Input       | Output
------------|--------------
(2+x) + 3   | 2+x+3
((4+5))*x   | (4+5)*x
z^(x+42)    | z^(x+42)
x - ((y)+2) | x-(y+2)
(z - y) - x | z-y-x
x^(y^2)     | x^y^2
x^2 / z     | x^2/z
- (x + 5)+3 | -(x+5)+3
</code>```

Scoring

Input/output can use any preferred method.  The smallest program in bytes wins.

Exact bits

Exponentiation is right associative and also follows standard math precedence (being the highest).  A valid numeric literal is /[0-9]+/, and a valid variable literal is /[a-z]+/.  A single variable literal represents a single value even when its character length is longer than 1.

What is meant by "the parentheses around associative operations need not be preserved" is that the output should consist of an expression that results in an identical parse tree, with the exception that associative operations can be rearranged.

Body:
C#, <s>523</s> <s>519</s> 504 bytes

Check the in-code comments to see how it works!

Golfed

using System;using System.Collections.Generic;namespace n{class p{static void Main(string[]a){foreach(String s in a){String r=s.Replace(" ","");List<int>l=new List<int>();for(int i=0;i<r.Length;i++){if(r[i]=='('){l.Add(i);continue;}if(r[i]==')'){switch(r[Math.Max(l[l.Count-1]-1,0)]){case'+':case'(':switch(r[Math.Min(i+1,r.Length-1)]){case'+':case'-':case')':r=r.Remove(Math.Max(l[l.Count-1],0),1);r=r.Remove(Math.Min(i,r.Length)-1,1);i-=2;break;}break;}l.RemoveAt(l.Count-1);}}Console.WriteLine(r);}}}}

Ungolfed

using System;
using System.Collections.Generic;

namespace n {
    class p {
        static void Main( string[] a ) {
            // Loop every String given for the program
            foreach (String s in a) {
                // Get rid of the spaces
                String r = s.Replace( " ", "" );

                // A little helper that will have the indexes of the '('
                List<int> l = new List<int>();

                // Begin the optimizatio process
                for (int i = 0; i < r.Length; i++) {
                    // If char is an '(', add the index to the helper list and continue
                    if (r[ i ] == '(') {
                        l.Add( i );
                        continue;
                    }

                    // If the char is an ')', validate the group
                    if (r[ i ] == ')') {
                        // If the char before the last '(' is an '+' or '(' ...
                        switch (r[ Math.Max( l[ l.Count - 1 ] - 1, 0 ) ]) {
                            case '+':
                            case '(':
                                // ... and the char after the ')' we're checking now is an '+', '-' or ')' ...
                                switch (r[ Math.Min( i + 1, r.Length - 1 ) ]) {
                                    case '+':
                                    case '-':
                                    case ')':
                                        // Remove the '()' since they're most likely desnecessary.
                                        r = r.Remove( Math.Max( l[ l.Count - 1 ], 0 ), 1 );
                                        r = r.Remove( Math.Min( i, r.Length ) - 1, 1 );

                                        // Go two steps back in the loop since we removed 2 chars from the String,
                                        //   otherwise we would miss some invalid inputs
                                        i -= 2;
                                        break;
                                }

                                break;
                        }

                        // Remove the last inserted index of '(' from the list,
                        //   since we matched an ')' for it.
                        l.RemoveAt( l.Count - 1 );
                    }
                }

                // Print the result
                Console.WriteLine( r );
            }
        }
    }
}

Side notes

Fixed some typos and renamed some vars.

Nested an switch to get rid of an unnecessary variable. Also, fixed a bug that would render some solutions invalid, reported by Anders Kaseorg.

P.S.: If you have a tip or found a bug, please let me know in the comments and I'll try to fix it ( I'll then add a note about the bug fix with your name ;) )


答:
Python, 46 45 bytes

```<code>lambda l:[l.pop(l.index(min(l)))for _ in 1*l]
</code>```

Simple selection sort.

Title: Sort an Integer List

Body:
Python, 46 45 bytes

lambda l:[l.pop(l.index(min(l)))for _ in 1*l]

Simple selection sort.


Title: Box-256 Assembly - BIG SQUARE II

Body:
I'd like to start a series of challenges for http://box-256.com/ starting with the first challenge, “BIG SQUARE II”. After this one I'll add another for "CHECKERBOARD" and so on.

Rules:

Complete the BIG SQAURE II challenge in the Box-256 emulator (either on the website or download the program if you run Windows)

Post back here a screenshot of your working answer

You MUST include the code in plain text so that others can easily copy and very it’s operation.

Scoring:

The winner will be the least amount of instructions used (just the instruction calls, either by name or opcode, the arguments to them are not counted as JMP takes one argument but MOD can take three).

I think in the future contests we can add some additional bonus points for use of coding tricks and we could include the argument count too. I wanted to start basic to get the ball rolling.

Winning

I think we should put a stake in the ground and say two weeks from today we announce the winner(s, there maybe be mutliple entries with the same instruction count).

Body:
I think my answer is probably what you were suggesting @orlp ?

I've used 3 instrutions, PIX, ADD and JMP, the rest are the co-ordinates (however the instructions and coordinates are spaced out below for easier reading):

000 000 000 000
000 000 000 000
PIX @2C 002 000
ADD 001 @09 @09
JMP @08 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
000 000 000 000
011 012 013 014
015 016 017 018
019 01A 01B 01C
01D 01E 021 022
023 024 025 026
027 028 029 02A
02B 02C 02D 02E
031 032 03D 03E
041 042 04D 04E
051 052 05D 05E
061 062 06D 06E
071 072 07D 07E
081 082 08D 08E
091 092 09D 09E
0A1 0A2 0AD 0AE
0B1 0B2 0BD 0BE
0C1 0C2 0CD 0CE
0D1 0D2 0D3 0D4
0D5 0D6 0D7 0D8
0D9 0DA 0DB 0DC
0DD 0DE 0E1 0E2
0E3 0E4 0E5 0E6
0E7 0E8 0E9 0EA
0EB 0EC 0ED 0EE


答:
JavaScript (ES6), 51 bytes

```<code>a=>a.map(_=>m=Math.min(...a.filter(e=>e>m)),m=-1/0)
</code>```

Each loop finds the smallest number that hasn't been found so far.

Title: Sort an Integer List

Body:
JavaScript (ES6), 51 bytes

a=>a.map(_=>m=Math.min(...a.filter(e=>e>m)),m=-1/0)

Each loop finds the smallest number that hasn't been found so far.


答:
Haskell, <s>42</s> <s>41</s> 38 bytes

```<code>f u=filter(`elem`u)[(minBound::Int)..]
</code>```

Loops through all integers (signed 64bit, on my machine) and keeps those that are in u. Of course it doesn't finish in reasonable time.

The previous version looped through [minimum u..maximum u] which has the same worst case running time.

Edit: @xnor saved a byte. Thanks!

Title: Sort an Integer List

Body:
Haskell, <s>42</s> <s>41</s> 38 bytes

f u=filter(`elem`u)[(minBound::Int)..]

Loops through all integers (signed 64bit, on my machine) and keeps those that are in u. Of course it doesn't finish in reasonable time.

The previous version looped through [minimum u..maximum u] which has the same worst case running time.

Edit: @xnor saved a byte. Thanks!


答:
Oracle SQL 11.2, 205 bytes

WITH s AS(SELECT COLUMN_VALUE||''e FROM XMLTABLE(('"'||REPLACE(:1,',','","')||'"'))),v(p,f)AS(SELECT e,e FROM s UNION ALL SELECT p||','||e,e FROM v,s WHERE e+0>f)SELECT p FROM v WHERE LENGTH(p)=LENGTH(:1);
```
<p>Un-golfed</p>
<pre class="lang-sql prettyprint-override"><code>WITH
s AS  -- Split the string using ',' as separator
(     -- ||'' cast the xml type to varchar
  SELECT COLUMN_VALUE||''e FROM XMLTABLE(('"'||REPLACE(:1,',','","')||'"'))
),
v(p,f) AS  -- Recursive view : p = sorted string, f last number added
(
  SELECT e,e FROM s -- use each number as seed
  UNION ALL         -- only add a number if it is > the last added
  SELECT p||','||e,e FROM v,s WHERE e+0>f  -- +0 is needed to compare int and not strings
)
-- The valid string has the same length as the input
SELECT p FROM v WHERE LENGTH(p)=LENGTH(:1)
</code>```

As for what sort method it is, I have no idea, ORDER BY made sure I forgot them.

Title: Sort an Integer List

Body:
Oracle SQL 11.2, 205 bytes

WITH s AS(SELECT COLUMN_VALUE||''e FROM XMLTABLE(('"'||REPLACE(:1,',','","')||'"'))),v(p,f)AS(SELECT e,e FROM s UNION ALL SELECT p||','||e,e FROM v,s WHERE e+0>f)SELECT p FROM v WHERE LENGTH(p)=LENGTH(:1);

Un-golfed

WITH
s AS  -- Split the string using ',' as separator
(     -- ||'' cast the xml type to varchar
  SELECT COLUMN_VALUE||''e FROM XMLTABLE(('"'||REPLACE(:1,',','","')||'"'))
),
v(p,f) AS  -- Recursive view : p = sorted string, f last number added
(
  SELECT e,e FROM s -- use each number as seed
  UNION ALL         -- only add a number if it is > the last added
  SELECT p||','||e,e FROM v,s WHERE e+0>f  -- +0 is needed to compare int and not strings
)
-- The valid string has the same length as the input
SELECT p FROM v WHERE LENGTH(p)=LENGTH(:1)

As for what sort method it is, I have no idea, ORDER BY made sure I forgot them.


答:
MATL, 11 bytes

```<code>`t4#X<2#)tn
</code>```

Try it online!

This sorts by the following procedure, which is O(n2):

Take the minimum of the array.

Remove that value from the array, and store it for subsequent display.

Apply the same procedure with the rest of the array, until it becomes empty.

Display all numbers in the order in which they were obtained.

MATL is stack-based. The array with remaining values is kept at the top of the stack. The removed values are below, in order. At the end of the program all those values are displayed. The array at the top would also be displayed, but since it's empty it's not shown.

```<code>`        % Do...while loop
  t      %   Duplicate. Implicitly take input in the first iteration
  4#X<   %   Compute index of mininum of the array
  2#)    %   Push the minimum, and then the array with remaining entries
  tn     %   Duplicate and push number of elements, to be used as loop condition
         % Implicitly end do...while loop
         % Implicitly display stack contents
</code>```

Title: Sort an Integer List

Body:
MATL, 11 bytes

`t4#X<2#)tn

Try it online!

This sorts by the following procedure, which is O(n2):

Take the minimum of the array.

Remove that value from the array, and store it for subsequent display.

Apply the same procedure with the rest of the array, until it becomes empty.

Display all numbers in the order in which they were obtained.

MATL is stack-based. The array with remaining values is kept at the top of the stack. The removed values are below, in order. At the end of the program all those values are displayed. The array at the top would also be displayed, but since it's empty it's not shown.

`        % Do...while loop
  t      %   Duplicate. Implicitly take input in the first iteration
  4#X<   %   Compute index of mininum of the array
  2#)    %   Push the minimum, and then the array with remaining entries
  tn     %   Duplicate and push number of elements, to be used as loop condition
         % Implicitly end do...while loop
         % Implicitly display stack contents


答:
MATL, <s>16</s> 15 bytes

```<code>3$:3Gvu9X10ZGZD
</code>```

This may fail for very large denominators. I hope output format is acceptable.

Try it online!

```<code>3$:    % take three inputs and generate range
3G     % push third input again
v      % vertically concatenate. Gives vertical array as output
u      % get unique elements (i.e. remove the last one if it is repeated)
9X1    % predefined literal 'rat'
0ZG    % set rational format
ZD     % display using that format
</code>```

Title: In-between fractions

Body:
In-between fractions

The challenge:

You will need to create code that takes atleast 3 inputs; 2 integers and "a fraction representation" - whichever type suits your language for representing the fraction increments) ie. If you choose string the input would be "1/4" or you could choose 2 extra integer inputs or a tuple or w/e.

Input can be anywhere reasonable (STDIN, function arguments, from a file, etc.), and so can output (STDOUT, function return value, to a file, etc.)

Rules:

The input "fraction" will always be a valid fraction, less than 1; example "1/4"

The second input integer will always have a higher value than the first integer. I.E the first input integer will always have a lower value than the second.

The input integers can be negative.

Outputted fractions should be reduced as much as possible (simplified)

The code will need to output every "fraction step" between the 2 numbers in increments of the input fraction.

The code should be a program or function as stated here

Example 1:

Input: -2,3,"1/2"

Output:

```<code> -2
 -3/2
 -1
 -1/2
  0
  1/2
  1
  3/2
  2
  5/2
  3
</code>```

Example 2:

Input: 1,2,"2/3"

Output:

```<code>1
5/3
2
</code>```

or

```<code>1
4/3
2
</code>```

Note: Counting can start from either direction (thank you @Mego)

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

Body:
MATL, <s>16</s> 15 bytes

3$:3Gvu9X10ZGZD

This may fail for very large denominators. I hope output format is acceptable.

Try it online!

3$:    % take three inputs and generate range
3G     % push third input again
v      % vertically concatenate. Gives vertical array as output
u      % get unique elements (i.e. remove the last one if it is repeated)
9X1    % predefined literal 'rat'
0ZG    % set rational format
ZD     % display using that format


答:
Python, 120 Bytes

```<code>def f(a):import time,threading;[threading.Thread(None,lambda b=b,c=min(a):print(time.sleep(b-c)or b)).start()for b in a]
</code>```

This probably won't be the shortest answer but I feel like this algorithm belongs here. call with a list of integers, they'll be printed in a sorted manner to stdout. I wouldn't try it with too large numbers though.

Title: Sort an Integer List

Body:
The Challenge

It's quite simple really, sort a list of numbers.

Details

You must sort a list of numbers in ascending order, without using any built-in sorting functions/libraries/etc (i.e. list.sort() in Python).

Input/output can be done in any method you choose, as long as it is human readable.

Standard loopholes are disallowed as always.

Shortest code in bytes wins.

You must explain/list what sort method you used (Bubble, Insertion, Selection, etc.)

Input will not contain duplicates.

Sample Input/Output

Input: 99,-2,53,4,67,55,23,43,88,-22,36,45

Output: -22,-2,4,23,36,43,45,53,55,67,88,99

Note: A near direct opposite of Sort a List of Numbers

Body:
Python, 120 Bytes

def f(a):import time,threading;[threading.Thread(None,lambda b=b,c=min(a):print(time.sleep(b-c)or b)).start()for b in a]

This probably won't be the shortest answer but I feel like this algorithm belongs here. call with a list of integers, they'll be printed in a sorted manner to stdout. I wouldn't try it with too large numbers though.


答:
Haskell, 38 bytes

h%t|(a,b)<-span(<h)t=a++h:b
foldr(%)[]
```
<p>The binary function <code>%</code> insert a new element <code>h</code> into a sorted list <code>t</code> by partitioning <code>t</code> into a prefix <code>a</code> of elements <code><h</code> and a suffix <code>b</code> of elements <code>>h</code>, and sticks in <code>h</code> between them.</p>
<p>The operation <code>foldr(%)[]</code> then builds up a sorted list from empty by repeatedly inserting elements from the input list.</p>
<p>This is one byte shorter than the direct recursive implementation</p>
<pre class="lang-haskell prettyprint-override"><code>f(h:t)|(a,b)<-span(<h)$f t=a++h:b
f x=x
</code>```

Another strategy for 41 bytes:

f[]=[]
f l|x<-minimum l=x:f(filter(/=x)l)
```

Title: Sort an Integer List

Body:
Haskell, 38 bytes

h%t|(a,b)<-span(<h)t=a++h:b
foldr(%)[]

The binary function % insert a new element h into a sorted list t by partitioning t into a prefix a of elements <h and a suffix b of elements >h, and sticks in h between them.

The operation foldr(%)[] then builds up a sorted list from empty by repeatedly inserting elements from the input list.

This is one byte shorter than the direct recursive implementation

f(h:t)|(a,b)<-span(<h)$f t=a++h:b
f x=x

Another strategy for 41 bytes:

f[]=[]
f l|x<-minimum l=x:f(filter(/=x)l)


问:
Tips for golfing in Prolog
What general tips do you have for golfing in Prolog? I am looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Prolog (e.g. one letter variables is not specific to Prolog to reduce the size of programs).

Please indicate in your tips if it is specific to an implementation of Prolog (e.g. SWI-Prolog specific built-ins)

Please post only one tip per answer, or a list of tips that are all closely related to the same main idea.

答:
Reuse a predicate with different calling modes

For example, you can parse and print a structure with the same predicate, once with a variable argument and another time with a ground term.
I used this approach in Make the Stretchy Snakes Kiss. This is not possible in all challenges, of course.

Title: Tips for golfing in Prolog


答:
Octave, <s>34</s> 30 bytes

```<code>@(a,b,c)rats(union([a:c:b],b))
</code>```

Now takes the fraction as a numeric expression rather than separate numerator and denominator.

Sample on ideone

Title: In-between fractions

Body:
Octave, <s>34</s> 30 bytes

@(a,b,c)rats(union([a:c:b],b))

Now takes the fraction as a numeric expression rather than separate numerator and denominator.

Sample on ideone