答:
Befunge - 5 Bytes

```<code>&&+.@
</code>```

& - Request int from user and push to stack

+ - Pop top two elements from stack and add and push result

. - Pop value and output as int

@ - End program

Try it here (Although you will have to copy/paste into the text area)

Edit: oops, didn't notice the earlier (identical) befunge answer, I'll leave this here unless I'm told to delete it, not sure of the opinion on that.

Title: Add two numbers

Body:
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Befunge - 5 Bytes

&&+.@

& - Request int from user and push to stack

+ - Pop top two elements from stack and add and push result

. - Pop value and output as int

@ - End program

Try it here (Although you will have to copy/paste into the text area)

Edit: oops, didn't notice the earlier (identical) befunge answer, I'll leave this here unless I'm told to delete it, not sure of the opinion on that.


问:
Where should I put my mirror?
This is a mirror: |. I just found out that you can stick a mirror in the middle of a string if the string can be mirrored on itself! For example, the string abccba. If you cut it in half the two halves are mirror images of each other:

```<code>abc  <-->  cba
</code>```

So, we can stick a mirror in the middle of the string, and our new string is abc|cba. Sometimes, only part of the string can be mirrored on itself. For example, the string "mirror". The two r's are mirrored, but the rest of the string isn't. That's OK, we'll just remove the parts of the string that don't mirror each other, and we get the following string:

```<code>r|r
</code>```

Some strings could be mirrored in multiple places. For example, "Hello World, xyzzyx". I like having a lot of text reflected in my mirror, so you need to find the best place to put my mirror. In this case, you should output the longer mirrored string and just like our last example, remove everything else. This string becomes:

```<code>xyz|zyx
</code>```

Some strings look like they can be mirrored, but actually can not. If a string cannot be mirrored anywhere, you should output nothing.

The challenge:

Given a string containing only printable-ascii, find the best place to put my mirror. In other words,

Find the largest even-length palindromic substring, then output it with a pipe character '|' in the middle of it.

The input will be 1-50 characters long.

You can assume that the input will not contain mirrors | or newlines. Beyond that, all printable-ascii characters are fair game. If the longest mirrored substring is tied between two substrings, you can choose which one to output. For example, for the string "abba ollo", you must output "ab|ba" or "ol|lo", but it doesn't matter which one you output. Strings are case-sensitive, e.g. "ABba" should not output "AB|ba", it should output the empty string.

Sample IO:

```<code>"Hello World"     --> "l|l"
"Programming Puzzles and Code-Golf"     --> Either "m|m" or "z|z"
"abcba"           --> ""
"Hulluh"          --> "ul|lu"
"abcdefggfedcba"  --> "abcdefg|gfedcba"
"abcdefggfabc"    --> "fg|gf"
"AbbA"            --> "Ab|bA"
"This input is a lot like the last one, but with more characters that don't change the output. AbbA" --> "Ab|bA"
</code>```

As usual, this is code-golf, so standard loopholes apply, and the shortest answer in bytes wins!

答:
TSQL <s>227</s> 223 bytes

I hardcoded the length to max 99 bytes, this saved bytes but made it slower. It still have a decent performance though.

Golfed:

```<code>DECLARE @t varchar(99)='AbccbA'

,@z char(99)='',@a INT=0,@ INT=0WHILE @a<LEN(@t)SELECT
@z=IIF(LEN(x)>LEN(@z)/2and @t LIKE'%'+x+REVERSE(x)+'%'COLLATE
Thai_bin,x+'|'+REVERSE(x),@z),@=IIF(@=50,1,@+1),@a+=IIF(@=1,1,0)FROM(SELECT
SUBSTRING(@t,@a,@)x)x PRINT @z
</code>```

Ungolfed:

```<code>DECLARE @t varchar(99)='AbccbA'

,@z char(99)='',
@a INT=0,
@ INT=0
WHILE @a<LEN(@t)
  SELECT
    @z=IIF(LEN(x)>LEN(@z)/2and @t LIKE'%'+x+REVERSE(x)+'%'COLLATE Thai_bin,x+'|'
       +REVERSE(x),@z),
    @=IIF(@=99,1,@+1),
    @a+=IIF(@=1,1,0)
  FROM
    (SELECT SUBSTRING(@t,@a,@)x)x

PRINT @z
</code>```

Fiddle

ContentLicense: CC BY-SA 3.0

Title: Where should I put my mirror?

Body:
TSQL <s>227</s> 223 bytes

I hardcoded the length to max 99 bytes, this saved bytes but made it slower. It still have a decent performance though.

Golfed:

DECLARE @t varchar(99)='AbccbA'

,@z char(99)='',@a INT=0,@ INT=0WHILE @a<LEN(@t)SELECT
@z=IIF(LEN(x)>LEN(@z)/2and @t LIKE'%'+x+REVERSE(x)+'%'COLLATE
Thai_bin,x+'|'+REVERSE(x),@z),@=IIF(@=50,1,@+1),@a+=IIF(@=1,1,0)FROM(SELECT
SUBSTRING(@t,@a,@)x)x PRINT @z

Ungolfed:

DECLARE @t varchar(99)='AbccbA'

,@z char(99)='',
@a INT=0,
@ INT=0
WHILE @a<LEN(@t)
  SELECT
    @z=IIF(LEN(x)>LEN(@z)/2and @t LIKE'%'+x+REVERSE(x)+'%'COLLATE Thai_bin,x+'|'
       +REVERSE(x),@z),
    @=IIF(@=99,1,@+1),
    @a+=IIF(@=1,1,0)
  FROM
    (SELECT SUBSTRING(@t,@a,@)x)x

PRINT @z

Fiddle


问:
Groups of repeating items

Challenge description

Given a list / array of items, display all groups of consecutive repeating items.

Input / output description

Your input is a list / array of items (you can assume all of them are of the same type). You don't need to support every type your language has, but is has to support at least one (preferably int, but types like boolean, although not very interesting, are also fine). Sample outputs:

```<code>[4, 4, 2, 2, 9, 9] -> [[4, 4], [2, 2], [9, 9]]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] -> [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
[1, 1, 1, 3, 3, 1, 1, 2, 2, 2, 1, 1, 3] -> [[1, 1, 1], [3, 3], [1, 1], [2, 2, 2], [1, 1], [3]]
[9, 7, 8, 6, 5] -> [[9], [7], [8], [6], [5]]
[5, 5, 5] -> [[5, 5, 5]]
['A', 'B', 'B', 'B', 'C', 'D', 'X', 'Y', 'Y', 'Z'] -> [['A'], ['B', 'B', 'B'], ['C'], ['D'], ['X'], ['Y', 'Y'], ['Z']]
[True, True, True, False, False, True, False, False, True, True, True] -> [[True, True, True], [False, False], [True], [False, False], [True, True, True]]
[0] -> [[0]]
</code>```

As for empty lists, output is undefined - it can be nothing, an empty list, or an exception - whatever suits your golfing purposes the best. You don't have to create a separate list of lists either, so this is a perfectly valid output as well:

```<code>[1, 1, 1, 2, 2, 3, 3, 3, 4, 9] ->

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

The important thing is to keep the groups separated in some way. This is code-golf so the shortest code in bytes wins

答:
JavaScript (ES6), <s>39</s> 37 bytes

f=
s=>s.replace(/(\w+) (?!\1\b)/g,`$1
`)
;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input oninput=o.textContent=f(this.value);><pre id=o></code>```

Works on any space-separated word-like tokens. Saved 2 bytes thanks to @MartinEnder♦. Best I could do for array input and return is 68:

```<code>a=>a.reduce((l,r)=>(l==r?c.push(r):b.push(c=[r]),r),b=[c=[a[0]]])&&b
</code>```

ContentLicense: CC BY-SA 4.0

Title: Groups of repeating items

Body:
JavaScript (ES6), <s>39</s> 37 bytes

f=
s=>s.replace(/(\w+) (?!\1\b)/g,`$1
`)
;

<input oninput=o.textContent=f(this.value);><pre id=o>

Works on any space-separated word-like tokens. Saved 2 bytes thanks to @MartinEnder♦. Best I could do for array input and return is 68:

a=>a.reduce((l,r)=>(l==r?c.push(r):b.push(c=[r]),r),b=[c=[a[0]]])&&b


答:
Pyth, <s>9</s> 7 bytes

```<code>mr9]dr8
</code>```

Credit to @LeakyNun for 2 byte!

Explanation:

```<code>             input
     r8      run-length decode
m            for each...
   ]d        ...treat each run as standalone encoded form...
 r9          ...decode
             print
</code>```

Old answer, 12 bytes

```<code>hf.Am!t{dT./
</code>```

Forgot about run length built-in, but I think this is an okay approach, so I kept it.

Explanation:

```<code>                input
          ./    all possible partitions
 f       T      filter by...
  .A            ...whether all groups of integers...
    m!t{d       ...have length one after deduplication
h               get the first element (first one has no adjacent [1,1] and [1])
                print
</code>```

Title: Groups of repeating items

Body:
Challenge description

Given a list / array of items, display all groups of consecutive repeating items.

Input / output description

Your input is a list / array of items (you can assume all of them are of the same type). You don't need to support every type your language has, but is has to support at least one (preferably int, but types like boolean, although not very interesting, are also fine). Sample outputs:

```<code>[4, 4, 2, 2, 9, 9] -> [[4, 4], [2, 2], [9, 9]]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] -> [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
[1, 1, 1, 3, 3, 1, 1, 2, 2, 2, 1, 1, 3] -> [[1, 1, 1], [3, 3], [1, 1], [2, 2, 2], [1, 1], [3]]
[9, 7, 8, 6, 5] -> [[9], [7], [8], [6], [5]]
[5, 5, 5] -> [[5, 5, 5]]
['A', 'B', 'B', 'B', 'C', 'D', 'X', 'Y', 'Y', 'Z'] -> [['A'], ['B', 'B', 'B'], ['C'], ['D'], ['X'], ['Y', 'Y'], ['Z']]
[True, True, True, False, False, True, False, False, True, True, True] -> [[True, True, True], [False, False], [True], [False, False], [True, True, True]]
[0] -> [[0]]
</code>```

As for empty lists, output is undefined - it can be nothing, an empty list, or an exception - whatever suits your golfing purposes the best. You don't have to create a separate list of lists either, so this is a perfectly valid output as well:

```<code>[1, 1, 1, 2, 2, 3, 3, 3, 4, 9] ->

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

The important thing is to keep the groups separated in some way. This is code-golf so the shortest code in bytes wins

Body:
Pyth, <s>9</s> 7 bytes

mr9]dr8

Credit to @LeakyNun for 2 byte!

Explanation:

             input
     r8      run-length decode
m            for each...
   ]d        ...treat each run as standalone encoded form...
 r9          ...decode
             print

Old answer, 12 bytes

hf.Am!t{dT./

Forgot about run length built-in, but I think this is an okay approach, so I kept it.

Explanation:

                input
          ./    all possible partitions
 f       T      filter by...
  .A            ...whether all groups of integers...
    m!t{d       ...have length one after deduplication
h               get the first element (first one has no adjacent [1,1] and [1])
                print


问:
Rearrange pixels in image so it can't be recognized and then get it back
Create a program which can rearrange pixels in image so it can't be recognized.
However your program should able to convert it back to original image.

You can write two functions - for encoding and decoding, however one function which applied repeatedly gives original image (example in math - f(x) = 1 - x) is a bonus.

Also producing some pattern in output gives bonus too.

Image may be represented as 1D/2D array or image object if your language supports it.
Note that you can only change order of pixels!

Will be logical to select as winner code which produces less recognizable image, however I don't know how to measure it exactly, all ways I can imagine can be cheated. Therefore I chose this question to be popularity contest - let users choose what the best answer!

Test image 1 (800 x 422 px):

Test image 2 (800 x 480 px):

Please provide with code output image.

答:
Matlab with a pinch of Group Theory (+ bonus)

In this approach we assume that we have an even number of total pixels. (If not, we just ignore one pixel) So we need to choose half of the pixels to swap with the other half. For this, we index all the pixels from 0 up to 2N-1 and consider these indices as a cyclic group.

Among the primes we search for a number p that is not too small and not too big, and that is coprime to 2N, the order of our group. This means g generates our group or {k*g mod 2N | k=0,1,...,2N-1} = {0,1,...,2N-1}.

So we choose the first N multiples of g as one set, and all the remaining indeces as the other set, and just swap the corresponding set of pixels.

If p is chosen the right way, the first set is evenly distributed over the whole image.

The two test cases:

Slightly off topic but interesting:

During testing I noticed, that if you save it to a (lossy compressed) jpg (instead of a losslessly compressed png) and apply the transformation back and forth, you quite quickly see artefacts of the compression, this shows the results of two consecutive rearrangements:

As you can see, the jpg compression makes the result look almost black and white!

```<code>clc;clear;
inputname = 'codegolf_rearrange_pixels2.png';
inputname = 'codegolf_rearrange_pixels2_swapped.png';
outputname = 'codegolf_rearrange_pixels2_swapped.png';

%read image
src = imread(inputname);

%separate into channels
red = src(:,:,1);
green = src(:,:,2);
blue = src(:,:,3);

Ntotal = numel(red(:));  %number of pixels
Nswap = floor(Ntotal/2); %how many pairs we can swap

%find big enough generator
factors = unique(factor(Ntotal));
possible_gen = primes(max(size(red)));
eliminated = setdiff(possible_gen,factors);
if mod(numel(eliminated),2)==0 %make length odd for median
    eliminated = [1,eliminated];
end
generator = median(eliminated);

%set up the swapping vectors
swapindices1 = 1+mod((1:Nswap)*generator, Ntotal);
swapindices2 = setdiff(1:Ntotal,swapindices1);
swapindices2 = swapindices2(1:numel(swapindices1)); %make sure both have the same length

%swap the pixels
red([swapindices1,swapindices2]) = red([swapindices2,swapindices1]);
green([swapindices1,swapindices2]) = green([swapindices2,swapindices1]);
blue([swapindices1,swapindices2]) = blue([swapindices2,swapindices1]);

%write and display
output = cat(3,red,green,blue);
imwrite(output,outputname);
subplot(2,1,1);
imshow(src)
subplot(2,1,2);
imshow(output);
</code>```

Body:
Matlab with a pinch of Group Theory (+ bonus)

In this approach we assume that we have an even number of total pixels. (If not, we just ignore one pixel) So we need to choose half of the pixels to swap with the other half. For this, we index all the pixels from 0 up to 2N-1 and consider these indices as a cyclic group.

Among the primes we search for a number p that is not too small and not too big, and that is coprime to 2N, the order of our group. This means g generates our group or {k*g mod 2N | k=0,1,...,2N-1} = {0,1,...,2N-1}.

So we choose the first N multiples of g as one set, and all the remaining indeces as the other set, and just swap the corresponding set of pixels.

If p is chosen the right way, the first set is evenly distributed over the whole image.

The two test cases:

Slightly off topic but interesting:

During testing I noticed, that if you save it to a (lossy compressed) jpg (instead of a losslessly compressed png) and apply the transformation back and forth, you quite quickly see artefacts of the compression, this shows the results of two consecutive rearrangements:

As you can see, the jpg compression makes the result look almost black and white!

clc;clear;
inputname = 'codegolf_rearrange_pixels2.png';
inputname = 'codegolf_rearrange_pixels2_swapped.png';
outputname = 'codegolf_rearrange_pixels2_swapped.png';

%read image
src = imread(inputname);

%separate into channels
red = src(:,:,1);
green = src(:,:,2);
blue = src(:,:,3);

Ntotal = numel(red(:));  %number of pixels
Nswap = floor(Ntotal/2); %how many pairs we can swap

%find big enough generator
factors = unique(factor(Ntotal));
possible_gen = primes(max(size(red)));
eliminated = setdiff(possible_gen,factors);
if mod(numel(eliminated),2)==0 %make length odd for median
    eliminated = [1,eliminated];
end
generator = median(eliminated);

%set up the swapping vectors
swapindices1 = 1+mod((1:Nswap)*generator, Ntotal);
swapindices2 = setdiff(1:Ntotal,swapindices1);
swapindices2 = swapindices2(1:numel(swapindices1)); %make sure both have the same length

%swap the pixels
red([swapindices1,swapindices2]) = red([swapindices2,swapindices1]);
green([swapindices1,swapindices2]) = green([swapindices2,swapindices1]);
blue([swapindices1,swapindices2]) = blue([swapindices2,swapindices1]);

%write and display
output = cat(3,red,green,blue);
imwrite(output,outputname);
subplot(2,1,1);
imshow(src)
subplot(2,1,2);
imshow(output);


问:
Find whether a number is happy or not?
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers). Given a number print whether it is happy or unhappy.

```<code>Sample Inputs
7
4
13

Sample Outputs
Happy
Unhappy
Happy
</code>```

Note: Your program should not take more than 10 secs for any number below 1,000,000,000.

答:
C# 94 bytes

```<code>int d(int n)=>n<10?n*n:(d(n%10)+d(n/10));string h(int n)=>n==1?"happy":n==4?"unhappy":h(d(n));
</code>```

For any given number (as int), h() will return the correct value. You can try the code on .NetFiddle.

Kudos to user unknown for the original algorithm.

Title: Find whether a number is happy or not?

Body:
C# 94 bytes

int d(int n)=>n<10?n*n:(d(n%10)+d(n/10));string h(int n)=>n==1?"happy":n==4?"unhappy":h(d(n));

For any given number (as int), h() will return the correct value. You can try the code on .NetFiddle.

Kudos to user unknown for the original algorithm.


问:
Can you Golf Golf?
You are required to generate a random 18-hole golf course.

Example output:

```<code>[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]
</code>```

Rules:

Your program must output a list of hole lengths for exactly 18 holes

Each hole must have a length of 3, 4 or 5

The hole lengths must add up to 72 for the entire course

Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

答:
Ruby 1.9 (62 chars)

```<code>a=Array.new(18){[3,4,5].sample}until(a||[]).inject(:+)==72
p a
</code>```

Rails (55 chars)

In the $ rails c REPL (in any Rails folder):

```<code>a=Array.new(18){[3,4,5].sample}until(a||[]).sum==72
p a
</code>```

Note: It works with Ruby 1.8 if you use shuffle[0] instead of sample.

Title: Can you Golf Golf?

Body:
Ruby 1.9 (62 chars)

a=Array.new(18){[3,4,5].sample}until(a||[]).inject(:+)==72
p a

Rails (55 chars)

In the $ rails c REPL (in any Rails folder):

a=Array.new(18){[3,4,5].sample}until(a||[]).sum==72
p a

Note: It works with Ruby 1.8 if you use shuffle[0] instead of sample.


答:
Retina, <s>24</s> 22 bytes

2 bytes thanks to Martin Ender.

A 15-byte answer already exists, so this is just another approach which costs more bytes.

```<code>S-`(?<=(\d+)) (?!\1\b)
</code>```

Try it online!

It splits on spaces whose preceding number differ from the proceeding.

This is a demonstration of lookarounds.

Title: Groups of repeating items

Body:
Retina, <s>24</s> 22 bytes

2 bytes thanks to Martin Ender.

A 15-byte answer already exists, so this is just another approach which costs more bytes.

S-`(?<=(\d+)) (?!\1\b)

Try it online!

It splits on spaces whose preceding number differ from the proceeding.

This is a demonstration of lookarounds.


答:
TSQL, 132 bytes

This is a little different from the other answers - sql doesn't have arrays, the obvious input for sql is a table.

Golfed:

```<code>DECLARE @ table(i int identity, v varchar(20))
INSERT @ values(1),(1),(1),(3),(3),(1),(1),(2),(2),(2),(1),(1),(3)

SELECT REPLICATE(v+' ',COUNT(*))FROM(SELECT i,i-row_number()over(partition
by v order by i)x,v FROM @)z GROUP BY x,v ORDER BY max(i)
</code>```

Ungolfed:

```<code>DECLARE @ table(i int identity, v varchar(20))
INSERT @ values(1),(1),(1),(3),(3),(1),(1),(2),(2),(2),(1),(1),(3)

SELECT
  REPLICATE(v+' ',COUNT(*))
FROM
  (
     SELECT
       i,
       i-row_number()over(partition by v order by i)x,
       v
     FROM @
  )z
GROUP BY
  x,v
ORDER BY
  max(i)
</code>```

Fiddle

Title: Groups of repeating items

Body:
TSQL, 132 bytes

This is a little different from the other answers - sql doesn't have arrays, the obvious input for sql is a table.

Golfed:

DECLARE @ table(i int identity, v varchar(20))
INSERT @ values(1),(1),(1),(3),(3),(1),(1),(2),(2),(2),(1),(1),(3)

SELECT REPLICATE(v+' ',COUNT(*))FROM(SELECT i,i-row_number()over(partition
by v order by i)x,v FROM @)z GROUP BY x,v ORDER BY max(i)

Ungolfed:

DECLARE @ table(i int identity, v varchar(20))
INSERT @ values(1),(1),(1),(3),(3),(1),(1),(2),(2),(2),(1),(1),(3)

SELECT
  REPLICATE(v+' ',COUNT(*))
FROM
  (
     SELECT
       i,
       i-row_number()over(partition by v order by i)x,
       v
     FROM @
  )z
GROUP BY
  x,v
ORDER BY
  max(i)

Fiddle


Title: Groups of repeating items

Body:
Perl 5 - 39 Bytes

print$_.($/)[$_ eq@a[++$-]]for@a=sort@a


答:
C, <s>88</s> 77 bytes

Moved the strmcmp inside the printf saving 11 bytes

```<code>f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}
</code>```

Usage:

```<code>f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}
main(c,v)char**v;{f(v);}
</code>```

Sample Input:

(command line parameters)

```<code>1 1 1 1 2 2 2 2 3 3 3 3 4 5 6 7777
</code>```

Sample Output:

```<code>1 1 1 1
2 2 2 2
3 3 3 3
4
5
6
7777
</code>```

Tested on:

```<code>gcc 4.4.7 (Red Hat 4.4.7-16)  - OK
gcc 5.3.0 (Cygwin)            - Segmetation Fault
gcc 4.8.1 (Windows)           - OK
</code>```

I'm trying to fix the 5.3.0 Segmetation Fault.

88 Version

```<code>f(char**a){*a++;char*x;for(;*a;x=*a++)strcmp(*a,x)?printf("\n%s ",*a):printf("%s ",*a);}
</code>```

Title: Groups of repeating items

Body:
C, <s>88</s> 77 bytes

Moved the strmcmp inside the printf saving 11 bytes

f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}

Usage:

f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}
main(c,v)char**v;{f(v);}

Sample Input:

(command line parameters)

1 1 1 1 2 2 2 2 3 3 3 3 4 5 6 7777

Sample Output:

1 1 1 1
2 2 2 2
3 3 3 3
4
5
6
7777

Tested on:

gcc 4.4.7 (Red Hat 4.4.7-16)  - OK
gcc 5.3.0 (Cygwin)            - Segmetation Fault
gcc 4.8.1 (Windows)           - OK

I'm trying to fix the 5.3.0 Segmetation Fault.

88 Version

f(char**a){*a++;char*x;for(;*a;x=*a++)strcmp(*a,x)?printf("\n%s ",*a):printf("%s ",*a);}


问:
Find the nth decimal of pi
There are already 30 challenges dedicated to pi but not a single one asks you to find the nth decimal, so...

Challenge

For any integer in the range of 0 <= n <= 10000 display the nth decimal of pi.

Rules

Decimals are every number after 3.

Your program may be a function, or a full program

You must output the result in base 10

You may get n from any suitable input method (stdin, input(), function parameters, ...), but not hardcoded

You may use 1-based indexing if that's native to your language of choice

You don't have to deal with invalid input (n == -1, n == 'a' or n == 1.5)

Builtins are allowed, if they support up to at least 10k decimals

Runtime doesn't matter, since this is about the shortest code and not the fastest code

This is code-golf, shortest code in bytes wins

Test cases

```<code>f(0)     == 1
f(1)     == 4 // for 1-indexed languages f(1) == 1
f(2)     == 1 // for 1-indexed languages f(2) == 4
f(3)     == 5
f(10)    == 8
f(100)   == 8
f(599)   == 2
f(760)   == 4
f(1000)  == 3
f(10000) == 5
</code>```

For reference, here are the first 100k digits of pi.

答:
Python 2, 66 bytes

n=input()+9
x=p=5L**7
while~-p:x=p/2*x/p+10**n;p-=2
print`x/5`[-9]
```

<p>Input is taken from stdin.</p>

<hr>

<p><strong>Sample Usage</strong></p>

<pre class="lang-python prettyprint-override"><code>$ echo 10 | python pi-nth.py
8

$ echo 100 | python pi-nth.py
8

$ echo 1000 | python pi-nth.py
3

$ echo 10000 | python pi-nth.py
5
</code>```

Title: Find the nth decimal of pi

Body:
Python 2, 66 bytes

n=input()+9
x=p=5L**7
while~-p:x=p/2*x/p+10**n;p-=2
print`x/5`[-9]

Input is taken from stdin.

Sample Usage

$ echo 10 | python pi-nth.py
8

$ echo 100 | python pi-nth.py
8

$ echo 1000 | python pi-nth.py
3

$ echo 10000 | python pi-nth.py
5


问:
Print the "even" permutations of symmetric group Sn in cyclic notation

THE TASK

DEFINITIONS

Consider the points {1,2,3,4,5} and all their permutations. We can find the total number of possible permutations of these 5 points by a simple trick: Imaging filling 5 slots with these points, the first slot will have 5 possible numbers, the second 4 (as one has been used to fill the first slot) the third 3 and so on. Thus the total number of Permutations is 5*4*3*2*1; this would be 5! permutations or 120 permutations. We can think of this as the symmetric group S5, and then Symmetric Group Sn would have n! or (n*n-1*n-2...*1) permutations.

An "even" permutation is one where there is an even number of even length cycles. It is easiest to understand when written in cyclic notation, for example (1 2 3)(4 5) permutes 1->2->3->1 and 4->5->4 and has one 3 length cycle (1 2 3) and one 2 length cycle (4 5). When classifying a permutation as odd or even we ignore odd length cycles and say that this permutation [(1 2 3)(4 5)] is odd as it has an odd number {1} of even length cycles.
Even examples:

(1)(2 3)(4 5) = two 2 length cycle | EVEN |

(1 2 3 4 5) = no even length cycles | EVEN | * note that if no even length cycles are present then the permutation is even.

Odd Examples:

(1 2)(3 4 5) = one 2 length cycle | ODD |

(1)(2 3 4 5) = one 4 length cycle | ODD |

As exactly half of the permutations in any Symmetric Group are even we can call the even group the Alternating Group N, So as S5 = 120 A5 = 60 permutations.

NOTATION

Permutations should, for this at least, be written in cyclic notation where each cycle is in different parenthesis and each cycle goes in ascending order. For example (1 2 3 4 5) not (3 4 5 1 2). And for cycles with a single number, such as: (1)(2 3 4)(5) the single / fixed points can be excluded meaning (1)(2 3 4)(5) = (2 3 4). But the identity {the point where all points are fixed (1)(2)(3)(4)(5)} should be written as () just to represent it.

THE CHALLENGE

I would like you to, in as little code possible, take any positive integer as an input {1,2,3,4...} and display all the permutations of the Alternating Group An where n is the input / all the even permutations of Sn. For example:

```<code>Input = 3
()
(1 2 3)
(1 3 2)
</code>```

and

```<code>Input = 4
()
(1 2)(3 4)
(1 3)(2 4)
(1 4)(2 3)
(1 2 3)
(1 3 2)
(1 2 4)
(1 4 2)
(1 3 4)
(1 4 3)
(2 3 4)
(2 4 3)
</code>```

And as with in the examples I would like for all cycles of one length to be elided, and as for the identity: outputs of  nothing, () {not only brackets but with whatever you are using to show different permutations} or id are acceptable.

EXTRA READING

You can find more information here:

https://en.wikipedia.org/wiki/Permutation

https://en.wikipedia.org/wiki/Alternating_group

GOOD LUCK

And as this is codegolf whoever can print the Alternating Group An's permutations in the shortest bytes wins.

Body:
GAP, 32 bytes

Thanks to @ChristianSievers  for cutting the count in half.

f:=n->List(AlternatingGroup(n));

Usage at the prompt:

gap> f(4);
[ (), (1,3,2), (1,2,3), (1,4,3), (2,4,3), (1,3)(2,4), (1,2,4), (1,4)(2,3), (2,3,4), (1,3,4), (1,2)(3,4), (1,4,2) ]


问:
Distinct Sieves
Given a list of integers, create a boolean mask such that the true indices can be used to filter the distinct values from the list. Which index is selected as the true one does not matter as long as only one of them is selected for each set of indices corresponding to identical values.

The input will be a non-empty list of non-negative integers in a format suitable for your language and the output will be a list of boolean values following the specification above. You are allowed to use your own definitions of truthy and falsy values in the output list.

In my examples below, I define 1 to be truthy and 0 to be falsy.

```<code>[5, 4, 7, 1]  Input
[1, 1, 1, 1]  Output
              Select only the values with with true indicies in the sieve
[5  4  7  1]  Contains zero duplicate values

[5, 9, 7, 5, 6, 0, 5]
[0, 1, 1, 1, 1, 1, 0]
[   9, 7, 5, 6, 0   ]
</code>```

Test Cases

When there is an or, it means that there are multiple valid outputs. If there is a trailing ellipsis ... after the or, it means that not all of the possible outputs were listed.

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

[55] = [1]

[32, 44] = [1, 1]

[0, 0] = [1, 0] or [0, 1]

[9001, 9001, 9001] = [1, 0 , 0] or [0, 1, 0] or [0, 0, 1]

[5, 4, 7, 1] = [1, 1, 1, 1]

[1, 2, 3, 4, 3, 5] = [1, 1, 1, 1, 0, 1] or
                     [1, 1, 0, 1, 1, 1]

[5, 9, 7, 5, 6, 0, 5] = [1, 1, 1, 0, 1, 1, 0] or
                        [0, 1, 1, 1, 1, 1, 0] or
                        [0, 1, 1, 0, 1, 1, 1]

[0, 8, 6, 6, 3, 8, 7, 2] = [1, 1, 1, 0, 1, 0, 1, 1] or
                           [1, 0, 0, 1, 1, 1, 1, 1] or
                           [1, 0, 1, 0, 1, 1, 1, 1] or
                           [1, 1, 0, 1, 1, 0, 1, 1]

[45, 47, 47, 45, 24, 24, 24, 8, 47, 41, 47, 88]
= [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1] or ...

[154, 993, 420, 154, 154, 689, 172, 417, 790, 175, 790, 790, 154, 172, 175, 175, 420, 417, 154, 175, 172, 175, 172, 993, 689, 993, 993, 790]
= [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] or ...
</code>```

Rules

This is code-golf so the shortest solution wins.

Builtins are allowed!

You are allowed to use your own definitions of truthy and falsy values in the output list. If you choose to do so, please state your definitions.

The input will be a non-empty list of non-negative integers.

You are free to choose between outputting only one of the sieves or multiple or even all of them. As long as each sieve is valid, it will be accepted.

答:
PHP, <s>66</s> <s>62</s> 39 bytes

accepts all atomic values (boolean, integer, float, string)

except for values evaluating to false (false, 0, "") and numeric strings ("1" equals 1)

flags first occurence

new version (program, 37+2 bytes)

beats Java and (now again) C#. Even almost beats Python now. Happy.

```<code><?foreach($a as$v)$u[$v]=print$u[$v]|0;
</code>```

+6 for PHP>=5.4, +16-3 for a function

prints undelimited list of 0 (true) and 1 (false)

insert ! after print to invert

usage: set register_globals=On, short_open_tags=On and error_reporting=0 in php.ini for php-cgi

then call php-cgi -f <filename> a[]=<value1> a[]=<value2> ...;echo"";

for PHP>=5.4: replace $a with $_GET[a] (+6), set short_open_tags=On and error_reporting=0

or replace $a with array_slice($argv,1) (+19), remove <?  (-2)

and call php -d error_reporting=0 -r '' <value1> <value2> ...;echo""

old version (function, 62 bytes)

```<code>function f($a){foreach($a as$v)$u[$v]=1|$m[]=$u[$v];return$m;}
</code>```

returns array of false for true and true for false; (ouput as empty string or 1)

insert ! after $m[]= to invert

There is another way for a qualified function with 55 bytes, too.

tests (on old version)

```<code>function out($a){if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';}
function test($x,$e,$y){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>",out($x),'</td><td>',out($y),'</td><td>',out($e),'</td><td>',(strcmp(out($y),out($e))?'N':'Y'),"</td></tr>";$h='';}
$samples=[
    [0],[1],    [55],[1],    [32,44],[1,1],    [9001,9001,9001],[1,false,false],
    [5,4,7,1],[1,1,1,1],    [1,2,3,4,3,5],[1,1,1,1,false,1],
    [5,9,7,5,6,0,5],[1,1,1,false,1,1,false],    [0,8,6,6,3,8,7,2],[1,1,1,false,1,false,1,1],
    [45,47,47,45,24,24,24,8,47,41,47,88],[1,1,'','',1,'','',1,'',1,'',1],
    [154,993,420,154,154,689,172,417,790,175,790,790,154,172,175,
        175,420,417,154,175,172,175,172,993,689, 993,993,790],
        array_merge([1,1,1,false,false,1,1,1,1,1],array_fill(0,18,false))
];
for($i=count($samples);$i--;--$i)for($j=count($samples[$i]);$j--;)$samples[$i][$j]=!$samples[$i][$j];
while($samples)
{
    $a=array_shift($samples);
    $em=array_shift($samples);
    test($a,$em,$ym=s($a));
    $eu=[];foreach($em as$i=>$f)if($f)$eu[]=$a[$i];
    $yu=[];foreach($ym as$i=>$f)if($f)$yu[]=$a[$i];
#   sort($eu); sort($yu);
    test('unique values',$eu,$yu);
}
echo '</table>';
</code>```

Title: Distinct Sieves

Body:
PHP, <s>66</s> <s>62</s> 39 bytes

accepts all atomic values (boolean, integer, float, string)

except for values evaluating to false (false, 0, "") and numeric strings ("1" equals 1)

flags first occurence

new version (program, 37+2 bytes)

beats Java and (now again) C#. Even almost beats Python now. Happy.

<?foreach($a as$v)$u[$v]=print$u[$v]|0;

+6 for PHP>=5.4, +16-3 for a function

prints undelimited list of 0 (true) and 1 (false)

insert ! after print to invert

usage: set register_globals=On, short_open_tags=On and error_reporting=0 in php.ini for php-cgi

then call php-cgi -f <filename> a[]=<value1> a[]=<value2> ...;echo"";

for PHP>=5.4: replace $a with $_GET[a] (+6), set short_open_tags=On and error_reporting=0

or replace $a with array_slice($argv,1) (+19), remove <?  (-2)

and call php -d error_reporting=0 -r '<code>' <value1> <value2> ...;echo""

old version (function, 62 bytes)

function f($a){foreach($a as$v)$u[$v]=1|$m[]=$u[$v];return$m;}

returns array of false for true and true for false; (ouput as empty string or 1)

insert ! after $m[]= to invert

There is another way for a qualified function with 55 bytes, too.

tests (on old version)

function out($a){if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';}
function test($x,$e,$y){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>",out($x),'</td><td>',out($y),'</td><td>',out($e),'</td><td>',(strcmp(out($y),out($e))?'N':'Y'),"</td></tr>";$h='';}
$samples=[
    [0],[1],    [55],[1],    [32,44],[1,1],    [9001,9001,9001],[1,false,false],
    [5,4,7,1],[1,1,1,1],    [1,2,3,4,3,5],[1,1,1,1,false,1],
    [5,9,7,5,6,0,5],[1,1,1,false,1,1,false],    [0,8,6,6,3,8,7,2],[1,1,1,false,1,false,1,1],
    [45,47,47,45,24,24,24,8,47,41,47,88],[1,1,'','',1,'','',1,'',1,'',1],
    [154,993,420,154,154,689,172,417,790,175,790,790,154,172,175,
        175,420,417,154,175,172,175,172,993,689, 993,993,790],
        array_merge([1,1,1,false,false,1,1,1,1,1],array_fill(0,18,false))
];
for($i=count($samples);$i--;--$i)for($j=count($samples[$i]);$j--;)$samples[$i][$j]=!$samples[$i][$j];
while($samples)
{
    $a=array_shift($samples);
    $em=array_shift($samples);
    test($a,$em,$ym=s($a));
    $eu=[];foreach($em as$i=>$f)if($f)$eu[]=$a[$i];
    $yu=[];foreach($ym as$i=>$f)if($f)$yu[]=$a[$i];
#   sort($eu); sort($yu);
    test('unique values',$eu,$yu);
}
echo '</table>';


Title: Find the nth decimal of pi

Body:
There are already 30 challenges dedicated to pi but not a single one asks you to find the nth decimal, so...

Challenge

For any integer in the range of 0 <= n <= 10000 display the nth decimal of pi.

Rules

Decimals are every number after 3.

Your program may be a function, or a full program

You must output the result in base 10

You may get n from any suitable input method (stdin, input(), function parameters, ...), but not hardcoded

You may use 1-based indexing if that's native to your language of choice

You don't have to deal with invalid input (n == -1, n == 'a' or n == 1.5)

Builtins are allowed, if they support up to at least 10k decimals

Runtime doesn't matter, since this is about the shortest code and not the fastest code

This is code-golf, shortest code in bytes wins

Test cases

```<code>f(0)     == 1
f(1)     == 4 // for 1-indexed languages f(1) == 1
f(2)     == 1 // for 1-indexed languages f(2) == 4
f(3)     == 5
f(10)    == 8
f(100)   == 8
f(599)   == 2
f(760)   == 4
f(1000)  == 3
f(10000) == 5
</code>```

For reference, here are the first 100k digits of pi.

Body:
CJam, 32

7e4,-2%{2+_2/@*\/2e10005+}*sq~)=

Try it online (it's a bit slow)


答:
Sage, <s>32</s> 25 bytes

```<code>lambda d:`n(pi,9^5)`[d+2]
</code>```

My first answer in a language of this kind.

n rounds pi to 17775 digits.

Title: Find the nth decimal of pi

Body:
Sage, <s>32</s> 25 bytes

lambda d:`n(pi,9^5)`[d+2]

My first answer in a language of this kind.

n rounds pi to 17775 digits.


答:
PHP - 77 Chars

```<code><?while(array_sum($a)!=72){for($i=0;18>$i;){$a[++$i]=rand(3,5);}}print_r($a);
</code>```

Much like sgrieve's solution, this builds a list of 18 holes, checks total par, and either prints it or rejects it and tries again. Oddly enough, our two solutions are the same length.

Rather annoyingly, PHP doesn't offer array functions with any brevity of name. Array_sum and print_r are killing me. Suggestions welcome.

Title: Can you Golf Golf?

Body:
You are required to generate a random 18-hole golf course.

Example output:

```<code>[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]
</code>```

Rules:

Your program must output a list of hole lengths for exactly 18 holes

Each hole must have a length of 3, 4 or 5

The hole lengths must add up to 72 for the entire course

Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

Body:
PHP - 77 Chars

<?while(array_sum($a)!=72){for($i=0;18>$i;){$a[++$i]=rand(3,5);}}print_r($a);

Much like sgrieve's solution, this builds a list of 18 holes, checks total par, and either prints it or rejects it and tries again. Oddly enough, our two solutions are the same length.

Rather annoyingly, PHP doesn't offer array functions with any brevity of name. Array_sum and print_r are killing me. Suggestions welcome.


答:
Bash + coreutils, <s>60</s> 49 bytes

<s>echo "scale=10100;4*a(1)"|bc -l|tr -d '\\\n'|cut -c$(($1+2))</s>

```<code>bc -l<<<"scale=$1+9;4*a(1)-3"|tr -dc 0-9|cut -c$1
</code>```

Improved by Dennis. Thanks!

The index is one-based.

Title: Find the nth decimal of pi

Body:
Bash + coreutils, <s>60</s> 49 bytes

<s>echo "scale=10100;4*a(1)"|bc -l|tr -d '\\\n'|cut -c$(($1+2))</s>

bc -l<<<"scale=$1+9;4*a(1)-3"|tr -dc 0-9|cut -c$1

Improved by Dennis. Thanks!

The index is one-based.


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

1 byte saved thanks to @Luis

```<code>YPiEY$GH+)
</code>```

This solution utilizes 1-based indexing

Try it Online

All test cases

Explanation

```<code>YP  % Pre-defined literal for pi
iE  % Grab the input and multiply by 2 (to ensure we have enough digits to work with)
Y$  % Compute the first (iE) digits of pi and return as a string
G   % Grab the input again
H+  % Add 2 (to account for '3.') in the string
)   % And get the digit at that location
    % Implicitly display the result
</code>```

Title: Find the nth decimal of pi

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

1 byte saved thanks to @Luis

YPiEY$GH+)

This solution utilizes 1-based indexing

Try it Online

All test cases

Explanation

YP  % Pre-defined literal for pi
iE  % Grab the input and multiply by 2 (to ensure we have enough digits to work with)
Y$  % Compute the first (iE) digits of pi and return as a string
G   % Grab the input again
H+  % Add 2 (to account for '3.') in the string
)   % And get the digit at that location
    % Implicitly display the result


答:
Jelly, 5 bytes

```<code>I0;œṗ
</code>```

Works for all numeric types. Try it online! or verify all numeric test cases.

How it works

```<code>I0;œṗ  Main link. Argument: A (array)

I      Increments; compute the differences of consecutive elements.
 0;    Prepend a zero.
   œṗ  Partition; split A at truthy values in the result to the left.
</code>```

Title: Groups of repeating items

Body:
Challenge description

Given a list / array of items, display all groups of consecutive repeating items.

Input / output description

Your input is a list / array of items (you can assume all of them are of the same type). You don't need to support every type your language has, but is has to support at least one (preferably int, but types like boolean, although not very interesting, are also fine). Sample outputs:

```<code>[4, 4, 2, 2, 9, 9] -> [[4, 4], [2, 2], [9, 9]]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] -> [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
[1, 1, 1, 3, 3, 1, 1, 2, 2, 2, 1, 1, 3] -> [[1, 1, 1], [3, 3], [1, 1], [2, 2, 2], [1, 1], [3]]
[9, 7, 8, 6, 5] -> [[9], [7], [8], [6], [5]]
[5, 5, 5] -> [[5, 5, 5]]
['A', 'B', 'B', 'B', 'C', 'D', 'X', 'Y', 'Y', 'Z'] -> [['A'], ['B', 'B', 'B'], ['C'], ['D'], ['X'], ['Y', 'Y'], ['Z']]
[True, True, True, False, False, True, False, False, True, True, True] -> [[True, True, True], [False, False], [True], [False, False], [True, True, True]]
[0] -> [[0]]
</code>```

As for empty lists, output is undefined - it can be nothing, an empty list, or an exception - whatever suits your golfing purposes the best. You don't have to create a separate list of lists either, so this is a perfectly valid output as well:

```<code>[1, 1, 1, 2, 2, 3, 3, 3, 4, 9] ->

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

The important thing is to keep the groups separated in some way. This is code-golf so the shortest code in bytes wins

Body:
Jelly, 5 bytes

I0;œṗ

Works for all numeric types. Try it online! or verify all numeric test cases.

How it works

I0;œṗ  Main link. Argument: A (array)

I      Increments; compute the differences of consecutive elements.
 0;    Prepend a zero.
   œṗ  Partition; split A at truthy values in the result to the left.


答:
Java 134 bytes

```<code>void a(String[]a){int i=0,l=a.length;for(;i<l-1;i++)System.out.print(a[i]+((a[i].equals(a[i+1]))?" ":"\n"));System.out.print(a[l-1]);}
</code>```

iterates through, and decides whether to separate with a new line or a space.

Title: Groups of repeating items

Body:
Java 134 bytes

void a(String[]a){int i=0,l=a.length;for(;i<l-1;i++)System.out.print(a[i]+((a[i].equals(a[i+1]))?" ":"\n"));System.out.print(a[l-1]);}

iterates through, and decides whether to separate with a new line or a space.


答:
C++, 242 bytes

Admittedly an overkill solution, as it works on any standard container of any ordered type:

```<code>#include<algorithm>
#include<list>
#include<set>
template<class T>auto f(T a){using V=typename T::value_type;std::set<V>s;std::list<bool>r;std::transform(a.begin(),a.end(),std::back_inserter(r),[&](V m){return s.insert(m).second;});return r;}
</code>```

Ungolfed:

(and further generalised)

```<code>template<class T>
auto f(T a)
{
    using std::begin;
    using std::end;
    using V=typename T::value_type;
    std::set<V>s;
    std::list<bool>r;
    std::transform(begin(a),end(a),std::back_inserter(r),[&](V m){return s.insert(m).second;});
    return r;
}
</code>```

Test suite:

```<code>int test(const std::list<bool>& expected, const auto& x) { return f(x) != expected; }
#include<array>
#include<chrono>
#include<forward_list>
#include<initializer_list>
#include<string>
#include<vector>
using namespace std::literals::chrono_literals;
int main()
{
    return 0
        + test({},            std::vector<short>{})
        + test({1},           std::array<int,1>{})
        + test({1},           std::vector<char>{55})
        + test({true,true},   std::vector<unsigned>{32,44})
        + test({1,0},         std::list<std::string>{"zero", "zero"})
        + test({1,0,0},       std::vector<long>{9001,9001,9001})
        + test({1,1,1,1},     std::array<char,4>{5,4,7,1})
        + test({1,1,1,1,0,1}, std::initializer_list<std::string>{"one","two","three","four","three","five"})
        + test({1,0,1,0,0},   std::forward_list<std::chrono::seconds>{60s, 1min, 3600s, 60min, 1h});
}
</code>```

Title: Distinct Sieves

Body:
Given a list of integers, create a boolean mask such that the true indices can be used to filter the distinct values from the list. Which index is selected as the true one does not matter as long as only one of them is selected for each set of indices corresponding to identical values.

The input will be a non-empty list of non-negative integers in a format suitable for your language and the output will be a list of boolean values following the specification above. You are allowed to use your own definitions of truthy and falsy values in the output list.

In my examples below, I define 1 to be truthy and 0 to be falsy.

```<code>[5, 4, 7, 1]  Input
[1, 1, 1, 1]  Output
              Select only the values with with true indicies in the sieve
[5  4  7  1]  Contains zero duplicate values

[5, 9, 7, 5, 6, 0, 5]
[0, 1, 1, 1, 1, 1, 0]
[   9, 7, 5, 6, 0   ]
</code>```

Test Cases

When there is an or, it means that there are multiple valid outputs. If there is a trailing ellipsis ... after the or, it means that not all of the possible outputs were listed.

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

[55] = [1]

[32, 44] = [1, 1]

[0, 0] = [1, 0] or [0, 1]

[9001, 9001, 9001] = [1, 0 , 0] or [0, 1, 0] or [0, 0, 1]

[5, 4, 7, 1] = [1, 1, 1, 1]

[1, 2, 3, 4, 3, 5] = [1, 1, 1, 1, 0, 1] or
                     [1, 1, 0, 1, 1, 1]

[5, 9, 7, 5, 6, 0, 5] = [1, 1, 1, 0, 1, 1, 0] or
                        [0, 1, 1, 1, 1, 1, 0] or
                        [0, 1, 1, 0, 1, 1, 1]

[0, 8, 6, 6, 3, 8, 7, 2] = [1, 1, 1, 0, 1, 0, 1, 1] or
                           [1, 0, 0, 1, 1, 1, 1, 1] or
                           [1, 0, 1, 0, 1, 1, 1, 1] or
                           [1, 1, 0, 1, 1, 0, 1, 1]

[45, 47, 47, 45, 24, 24, 24, 8, 47, 41, 47, 88]
= [1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1] or ...

[154, 993, 420, 154, 154, 689, 172, 417, 790, 175, 790, 790, 154, 172, 175, 175, 420, 417, 154, 175, 172, 175, 172, 993, 689, 993, 993, 790]
= [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] or ...
</code>```

Rules

This is code-golf so the shortest solution wins.

Builtins are allowed!

You are allowed to use your own definitions of truthy and falsy values in the output list. If you choose to do so, please state your definitions.

The input will be a non-empty list of non-negative integers.

You are free to choose between outputting only one of the sieves or multiple or even all of them. As long as each sieve is valid, it will be accepted.

Body:
C++, 242 bytes

Admittedly an overkill solution, as it works on any standard container of any ordered type:

#include<algorithm>
#include<list>
#include<set>
template<class T>auto f(T a){using V=typename T::value_type;std::set<V>s;std::list<bool>r;std::transform(a.begin(),a.end(),std::back_inserter(r),[&](V m){return s.insert(m).second;});return r;}

Ungolfed:

(and further generalised)

template<class T>
auto f(T a)
{
    using std::begin;
    using std::end;
    using V=typename T::value_type;
    std::set<V>s;
    std::list<bool>r;
    std::transform(begin(a),end(a),std::back_inserter(r),[&](V m){return s.insert(m).second;});
    return r;
}

Test suite:

int test(const std::list<bool>& expected, const auto& x) { return f(x) != expected; }
#include<array>
#include<chrono>
#include<forward_list>
#include<initializer_list>
#include<string>
#include<vector>
using namespace std::literals::chrono_literals;
int main()
{
    return 0
        + test({},            std::vector<short>{})
        + test({1},           std::array<int,1>{})
        + test({1},           std::vector<char>{55})
        + test({true,true},   std::vector<unsigned>{32,44})
        + test({1,0},         std::list<std::string>{"zero", "zero"})
        + test({1,0,0},       std::vector<long>{9001,9001,9001})
        + test({1,1,1,1},     std::array<char,4>{5,4,7,1})
        + test({1,1,1,1,0,1}, std::initializer_list<std::string>{"one","two","three","four","three","five"})
        + test({1,0,1,0,0},   std::forward_list<std::chrono::seconds>{60s, 1min, 3600s, 60min, 1h});
}


问:
Help me figure out what TeX I can use!
On TeX.SE the Help Centre says that the following is on topic:

```<code>Formats like LaTeX, ConTeXt and plain TeX
Engines like pdfTeX, LuaTeX and XeTeX
Distributions like TeX Live, MiKTeX, and MacTeX
Related software and tools, BibTeX, MakeIndex, Lyx, etc.
</code>```

I wanted you to write a program to tell me whether my TeX is in the on-topic types of TeX.

An explicit list of the valid TeX-s is as follows:

MetaPost

PostScript

MetaFUN

TeX

LaTeX

LuaLaTeX

LuaTeX

ConTeXt

BibTeX

pdfTeX

Lyx

MakeIndex

TeX Live

XeLaTeX

XeTeX

MacTeX

MiKTeX

Rules

You may use any language.

This is code-golf, to the shortest answer wins.

If you use Regex, you can just match correct ones.

You only need to match one at a time: no

Lyx
BibTeX

You must check with capitalization listed here.

Tests

```<code>TeX -> True/1/<match>
pTeX -> False/0/<not-match>
ConTeXt -> True/1/<match>
context -> False/0/<not-match>
MetaFun -> False/0/<not-match>
MetaFUN -> True/1/<match>
</code>```

P.S. Bonus points for an on-topic TeX answer!

答:
JavaScript Regex, <s>99</s> <s>101</s> <s>99</s> 97 + 1 for g flag = 98 bytes

```<code>^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$
</code>```

Test it here. Type into the Text box. Alternatively, test it here.

var j = $("#dos");
var text;
function abc(){
  text = $('#uno').val();
  j.val(text.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == text ? "Matches!" : "No match!");
};```
<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>
<input id='uno' /><br />
<button id='tres' onclick="javascript:abc()">Test!</button><br/>
<input id='dos' /></code>```

Test all cases:

var j = $("#dos");
var tests = ["TeX", "pTeX", "ConTeXt", "context", "MetaFun", "MetaFUN", "TeX Live"];
function abc(e){
  j.val(j.val() + e + ": " + (e.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == e ? "Matches!" : "No match!") + "\n");
};

function def(){
  tests.forEach(abc);
}```
<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>
<button id='tres' onclick="javascript:def()">Test!</button><br/>
<textarea rows=50 cols=200 id='dos'>
</textarea></code>```

Title: Help me figure out what TeX I can use!

Body:
JavaScript Regex, <s>99</s> <s>101</s> <s>99</s> 97 + 1 for g flag = 98 bytes

^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$

Test it here. Type into the Text box. Alternatively, test it here.

var j = $("#dos");
var text;
function abc(){
  text = $('#uno').val();
  j.val(text.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == text ? "Matches!" : "No match!");
};

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='uno' /><br />
<button id='tres' onclick="javascript:abc()">Test!</button><br/>
<input id='dos' />

Test all cases:

var j = $("#dos");
var tests = ["TeX", "pTeX", "ConTeXt", "context", "MetaFun", "MetaFUN", "TeX Live"];
function abc(e){
  j.val(j.val() + e + ": " + (e.match(/^(((Xe|Lua)?(La)?|Bib|MiK|pdf|Mac)TeX|ConTeXt|TeX Live|Meta(FUN|Post)|PostScript|MakeIndex|Lyx)$/g) == e ? "Matches!" : "No match!") + "\n");
};

function def(){
  tests.forEach(abc);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='tres' onclick="javascript:def()">Test!</button><br/>
<textarea rows=50 cols=200 id='dos'>
</textarea>


答:
05AB1E, 13 bytes

```<code>¬svyÊi¶}yðJ?y
</code>```

Explained

```<code>¬s             # push first element of list to stack and swap with input
  v            # for each X in input
   yÊi¶}       # if X is different from last iteration, push a newline
        yðJ?   # push X followed by a space to stack and join stack to string
            y  # push X to stack for next iterations comparison
</code>```

Should work for any list.

Tested on int and char.

Try it online

Title: Groups of repeating items

Body:
05AB1E, 13 bytes

¬svyÊi¶}yðJ?y

Explained

¬s             # push first element of list to stack and swap with input
  v            # for each X in input
   yÊi¶}       # if X is different from last iteration, push a newline
        yðJ?   # push X followed by a space to stack and join stack to string
            y  # push X to stack for next iterations comparison

Should work for any list.

Tested on int and char.

Try it online


答:
05AB1E, 3 bytes

```<code>žs¤
</code>```

Explained

```<code>žs   # push pi to N digits
  ¤  # get last digit
</code>```

Try it online

Uses 1-based indexing.

Supports up to 100k digits.

Title: Find the nth decimal of pi

Body:
05AB1E, 3 bytes

žs¤

Explained

žs   # push pi to N digits
  ¤  # get last digit

Try it online

Uses 1-based indexing.

Supports up to 100k digits.


答:
Clojure, 253 bytes

```<code>(defmacro q[& a] `(with-precision ~@a))(defn h[n](nth(str(reduce +(map #(let[p(+(* n 2)1)a(q p(/ 1M(.pow 16M %)))b(q p(/ 4M(+(* 8 %)1)))c(q p(/ 2M(+(* 8 %)4)))d(q p(/ 1M(+(* 8 %)5)))e(q p(/ 1M(+(* 8 %)6)))](* a(-(-(- b c)d)e)))(range(+ n 9)))))(+ n 2)))
</code>```

Calculate number pi using this formula. Have to redefine macro with-precision as it's used too frequently.

You can see the output here: https://ideone.com/AzumC3
1000 and 10000 takes exceeds time limit used on ideone, shrugs

Title: Find the nth decimal of pi

Body:
Clojure, 253 bytes

(defmacro q[& a] `(with-precision ~@a))(defn h[n](nth(str(reduce +(map #(let[p(+(* n 2)1)a(q p(/ 1M(.pow 16M %)))b(q p(/ 4M(+(* 8 %)1)))c(q p(/ 2M(+(* 8 %)4)))d(q p(/ 1M(+(* 8 %)5)))e(q p(/ 1M(+(* 8 %)6)))](* a(-(-(- b c)d)e)))(range(+ n 9)))))(+ n 2)))

Calculate number pi using this formula. Have to redefine macro with-precision as it's used too frequently.

You can see the output here: https://ideone.com/AzumC3
1000 and 10000 takes exceeds time limit used on ideone, shrugs


答:
Python, 128 120 116 characters

import random,itertools
random.choice([g for g in itertools.product(*(range(3,6)for l in range(18))) if sum(g)==72])
```

import statements are still length killers (23 characters only to import 2 function in the namespace)

i hope you do not need the result in a near future, as this code first evaluates all possible solutions before chosing one at random. maybe the slowest solution to this problem.

i do claim extra kudos for equal probability of each configuration...

Title: Can you Golf Golf?

Body:
Python, 128 120 116 characters

import random,itertools
random.choice([g for g in itertools.product(*(range(3,6)for l in range(18))) if sum(g)==72])

import statements are still length killers (23 characters only to import 2 function in the namespace)

i hope you do not need the result in a near future, as this code first evaluates all possible solutions before chosing one at random. maybe the slowest solution to this problem.

i do claim extra kudos for equal probability of each configuration...


Title: Find the nth decimal of pi

Body:
There are already 30 challenges dedicated to pi but not a single one asks you to find the nth decimal, so...

Challenge

For any integer in the range of 0 <= n <= 10000 display the nth decimal of pi.

Rules

Decimals are every number after 3.

Your program may be a function, or a full program

You must output the result in base 10

You may get n from any suitable input method (stdin, input(), function parameters, ...), but not hardcoded

You may use 1-based indexing if that's native to your language of choice

You don't have to deal with invalid input (n == -1, n == 'a' or n == 1.5)

Builtins are allowed, if they support up to at least 10k decimals

Runtime doesn't matter, since this is about the shortest code and not the fastest code

This is code-golf, shortest code in bytes wins

Test cases

```<code>f(0)     == 1
f(1)     == 4 // for 1-indexed languages f(1) == 1
f(2)     == 1 // for 1-indexed languages f(2) == 4
f(3)     == 5
f(10)    == 8
f(100)   == 8
f(599)   == 2
f(760)   == 4
f(1000)  == 3
f(10000) == 5
</code>```

For reference, here are the first 100k digits of pi.

Body:
Mathematica 30 bytes

RealDigits[Pi,10,1,-#][[1,1]]&

f=%

f@0
f@1
f@2
f@3
f@10
f@100
f@599
f@760
f@1000
f@10000

1

4

1

5

8

8

2

4

3

5


Title: Groups of repeating items

Body:
sed, <s>33</s> 23+1=24 bytes

s/([^ ]+)( \1)* */&\n/g

It needs the -r option.

Usage example:

$ echo '1 1 1 2 2 3 3 3 4 9 9' | sed -r 's/([^ ]+)( \1)* */&\n/g'
1 1 1
2 2
3 3 3
4
9 9


答:
Pyke, 2 bytes (non competitive)

Only supports integers

```<code>$f
</code>```

Try it here!

```<code>split_at(input, delta(input))
</code>```

Added split_at node, splits input when 2nd arg is truthy

Title: Groups of repeating items

Body:
Pyke, 2 bytes (non competitive)

Only supports integers

$f

Try it here!

split_at(input, delta(input))

Added split_at node, splits input when 2nd arg is truthy


答:
Python 2, <s>73</s> <s>71</s> 73 bytes

thanks to @aditsu for increasing my score by 2 bytes

Finally an algorithm that can complete under 2 seconds.

n=10**10010
a=p=2*n
i=1
while a:a=a*i/(2*i+1);p+=a;i+=1
lambda n:`p`[n+1]
```

Ideone it!

Uses the formula pi = 4*arctan(1) while computing arctan(1) using its taylor series.

Title: Find the nth decimal of pi

Body:
Python 2, <s>73</s> <s>71</s> 73 bytes

thanks to @aditsu for increasing my score by 2 bytes

Finally an algorithm that can complete under 2 seconds.

n=10**10010
a=p=2*n
i=1
while a:a=a*i/(2*i+1);p+=a;i+=1
lambda n:`p`[n+1]

Ideone it!

Uses the formula pi = 4*arctan(1) while computing arctan(1) using its taylor series.


答:
J, <s>19</s> 15 bytes

```<code>10([|<.@o.@^)>:
</code>```

Takes an integer n and outputs the nth digit of pi. Uses zero-based indexing. To get the nth digit, compute pi times 10n+1, take the floor of that value, and then take it modulo 10.

Usage

The input is an extended integer.

```<code>   f =: 10([|<.@o.@^)>:
   (,.f"0) x: 0 1 2 3 10 100 599 760 1000
   0 1
   1 4
   2 1
   3 5
  10 8
 100 8
 599 2
 760 4
1000 3
   timex 'r =: f 10000x'
1100.73
   r
5
</code>```

On my machine, it takes about 18 minutes to compute the 10000th digit.

Explanation

```<code>10([|<.@o.@^)>:  Input: n
             >:  Increment n
10               The constant n
           ^     Compute 10^(n+1)
        o.@      Multiply by pi
     <.@         Floor it
   [             Get 10
    |            Take the floor modulo 10 and return
</code>```

Title: Find the nth decimal of pi

Body:
J, <s>19</s> 15 bytes

10([|<.@o.@^)>:

Takes an integer n and outputs the nth digit of pi. Uses zero-based indexing. To get the nth digit, compute pi times 10n+1, take the floor of that value, and then take it modulo 10.

Usage

The input is an extended integer.

   f =: 10([|<.@o.@^)>:
   (,.f"0) x: 0 1 2 3 10 100 599 760 1000
   0 1
   1 4
   2 1
   3 5
  10 8
 100 8
 599 2
 760 4
1000 3
   timex 'r =: f 10000x'
1100.73
   r
5

On my machine, it takes about 18 minutes to compute the 10000th digit.

Explanation

10([|<.@o.@^)>:  Input: n
             >:  Increment n
10               The constant n
           ^     Compute 10^(n+1)
        o.@      Multiply by pi
     <.@         Floor it
   [             Get 10
    |            Take the floor modulo 10 and return


Title: Where should I put my mirror?

Body:
This is a mirror: |. I just found out that you can stick a mirror in the middle of a string if the string can be mirrored on itself! For example, the string abccba. If you cut it in half the two halves are mirror images of each other:

```<code>abc  <-->  cba
</code>```

So, we can stick a mirror in the middle of the string, and our new string is abc|cba. Sometimes, only part of the string can be mirrored on itself. For example, the string "mirror". The two r's are mirrored, but the rest of the string isn't. That's OK, we'll just remove the parts of the string that don't mirror each other, and we get the following string:

```<code>r|r
</code>```

Some strings could be mirrored in multiple places. For example, "Hello World, xyzzyx". I like having a lot of text reflected in my mirror, so you need to find the best place to put my mirror. In this case, you should output the longer mirrored string and just like our last example, remove everything else. This string becomes:

```<code>xyz|zyx
</code>```

Some strings look like they can be mirrored, but actually can not. If a string cannot be mirrored anywhere, you should output nothing.

The challenge:

Given a string containing only printable-ascii, find the best place to put my mirror. In other words,

Find the largest even-length palindromic substring, then output it with a pipe character '|' in the middle of it.

The input will be 1-50 characters long.

You can assume that the input will not contain mirrors | or newlines. Beyond that, all printable-ascii characters are fair game. If the longest mirrored substring is tied between two substrings, you can choose which one to output. For example, for the string "abba ollo", you must output "ab|ba" or "ol|lo", but it doesn't matter which one you output. Strings are case-sensitive, e.g. "ABba" should not output "AB|ba", it should output the empty string.

Sample IO:

```<code>"Hello World"     --> "l|l"
"Programming Puzzles and Code-Golf"     --> Either "m|m" or "z|z"
"abcba"           --> ""
"Hulluh"          --> "ul|lu"
"abcdefggfedcba"  --> "abcdefg|gfedcba"
"abcdefggfabc"    --> "fg|gf"
"AbbA"            --> "Ab|bA"
"This input is a lot like the last one, but with more characters that don't change the output. AbbA" --> "Ab|bA"
</code>```

As usual, this is code-golf, so standard loopholes apply, and the shortest answer in bytes wins!

Body:
Haskell, <s>126</s> 111 bytes

(!)=drop
f s|n<-length s=last$"":[a++'|':b|k<-[1..n],t<-map(!s)[1..n-k],let[a,b]=take k<$>[t,k!t],a==reverse b]


答:
Lisp (<s>78</s> 69 chars)

<s>(do((c()(mapcar(lambda(x)(+ 3(random 3)))(make-list 18))))((=(apply'+ c)72)c))</s>

```<code>(do((c()(loop repeat 18 collect(+ 3(random 3)))))((=(apply'+ c)72)c))
</code>```

It's rather similar to sgrieve's Python solution.

Start with c as NIL, check for a sum of 72, the do "increment function" for c generates a list of 18 numbers between 3 and 5, check for 72 again, lather, rinse, repeat.

It's refreshing to see do and loop nicely play golf together.

Title: Can you Golf Golf?

Body:
You are required to generate a random 18-hole golf course.

Example output:

```<code>[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]
</code>```

Rules:

Your program must output a list of hole lengths for exactly 18 holes

Each hole must have a length of 3, 4 or 5

The hole lengths must add up to 72 for the entire course

Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

Body:
Lisp (<s>78</s> 69 chars)

<s>(do((c()(mapcar(lambda(x)(+ 3(random 3)))(make-list 18))))((=(apply'+ c)72)c))</s>

(do((c()(loop repeat 18 collect(+ 3(random 3)))))((=(apply'+ c)72)c))

It's rather similar to sgrieve's Python solution.

Start with c as NIL, check for a sum of 72, the do "increment function" for c generates a list of 18 numbers between 3 and 5, check for 72 again, lather, rinse, repeat.

It's refreshing to see do and loop nicely play golf together.


问:
Add two numbers
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
C++ – 56 bytes

Should work on all unsigned integer types:

```<code>template<typename U>U f(U a,U b){return b?f(++a,--b):a;}
</code>```

This is multiplication in the same style:

```<code>template<typename U>U g(U a,U b){return b>1?f(g(a,--b),a):(b?a:0);}
</code>```

Finally exponentiation:

```<code>template<typename U>U h(U a,U b){return b>1?g(h(a,--b),a):(b?a:1);}

</code>```

To test:

```<code>#include <iostream>

template<typename U>U f(U a,U b){return b?f(++a,--b):a;}
template<typename U>U g(U a,U b){return b>1?f(g(a,--b),a):(b?a:0);}
template<typename U>U h(U a,U b){return b>1?g(h(a,--b),a):(b?a:1);}

int main()
{
    std::cout << f(3, 4) << std::endl;
    std::cout << g(3, 4) << std::endl;
    std::cout << h(3, 4) << std::endl;
    return 0;
}
</code>```

Output:

```<code>7
12
81
</code>```

Title: Add two numbers

Body:
C++ – 56 bytes

Should work on all unsigned integer types:

template<typename U>U f(U a,U b){return b?f(++a,--b):a;}

This is multiplication in the same style:

template<typename U>U g(U a,U b){return b>1?f(g(a,--b),a):(b?a:0);}

Finally exponentiation:

template<typename U>U h(U a,U b){return b>1?g(h(a,--b),a):(b?a:1);}

To test:

#include <iostream>

template<typename U>U f(U a,U b){return b?f(++a,--b):a;}
template<typename U>U g(U a,U b){return b>1?f(g(a,--b),a):(b?a:0);}
template<typename U>U h(U a,U b){return b>1?g(h(a,--b),a):(b?a:1);}

int main()
{
    std::cout << f(3, 4) << std::endl;
    std::cout << g(3, 4) << std::endl;
    std::cout << h(3, 4) << std::endl;
    return 0;
}

Output:

7
12
81


问:
Implement bag operations
A bag, also called a multiset, is an unordered collection. You can call it a set that allows duplicates, or a list (or an array) that is not ordered/indexed. In this challenge, you are asked to implement bag operations: addition, difference, multiplication, division, counting and equality test.

Operations

The specified operations may not be conventional.

addition combines two bags into one, conserving the total number of each value

[1,2,2,3] + [1,2,4] = [1,1,2,2,2,3,4]

difference removes from a bag each element of another bag, or does nothing if no such element

[1,2,2,4] - [1,2] = [2,4]  [1,2,3] - [2,4] = [1,3]

multiplication multiplies each element in the bag.

[1,2,3,3,4] * 3 = [1,1,1,2,2,2,3,3,3,3,3,3,4,4,4] 2 * [1,3] = [1,1,3,3]

division is an uncommon one: each n equal elements are put in n equal new bags, elements that cannot form an n-group remain in the bag. Return any one of the n new bags.

[1,1,2,2,2] / 2 = [1,2] [1,2,2,3,3,3] / 3 = [3]

counting counts how many divisor bags can be produced from the dividend bag

[1,1,2,2,2,2,3,3,3] c [1,2,3] = 2

equality test checks if two bags have the same numbers of each element

[1,2,2,3] == [3,2,1,2] = truthy [1,2,3] == [1,2,2,3] = falsy (can also use = for this)

If you are using your own symbols for the operators, please specify.

Formats

Bags will be displayed as lists of the form [1,1,2,3,4]. You can use any other bracket than square ones, or even use quotes, or nothing at all. The elements will be integers(mathematically, not necessarily int) for the purpose of this question. Bags do not have to be sorted.

The input format will be two bags or a bag and an integer, with an operator. You can specify your own format as long as it contains these three.

The output format should be a single bag of the same format.

Rules

you may not use built-in functions, operations or libraries (including the standard library) that already implement these; it's ok though to use list concatenation and multiplication since they are by definition list operations, not bag operations (which happen to basically do the same thing)

standard loopholes apply

shortest answer wins

Test cases

```<code>[1,2,2,3] + [1,2,4]
[1,1,2,2,2,3,4]

[1,2,2,4] - [1,2]
[2,4]

[1,2,3] - [2,4]
[1,3]

[1,2,3,3,4] * 3
[1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]

2 * [1,3]
[1,1,3,3]

[1,1,2,2,2] / 2
[1,2]

[1,2,2,3,3,3] / 3
[3]

[1,1,2,2,2,2,3,3,3] c [1,2,3]
2

[3,2,1,2] == [1,2,2,3]
truthy

[1,2,3] == [1,2,2,3]
falsy
</code>```

答:
JavaScript (ES6), 260 bytes

```<code>(x,o,y,a=a=>a.reduce((r,e,i)=>[...r,...Array(e).fill(i)],[]),b=(a,r=[])=>a.map(e=>r[e]=-~r[e])&&r)=>[z=>a(b(y,z)),z=>y.map(e=>z[e]&&z[e]--)&&a(z),z=>a(z.map(e=>e*y)),z=>a(z.map(i=>i/y|0)),z=>b(y).map((e,i)=>r=Math.min(r,z[i]/e),r=1/0)|r,z=>``+z==b(y)][o](b(x))
</code>```

Takes 3 parameters. The first parameter is an array, the second is an operator, the third depends on the operator. Bags are required to hold non-negative integers.

```<code>[...] 0 [...] -> addition
[...] 1 [...] -> difference
[...] 2 <n> -> multiplication
[...] 3 <n> -> division
[...] 4 [...] -> counting
[...] 5 [...] -> equality
</code>```

Ungolfed:

```<code>function do_bag_op(lhs, op, rhs) {
    function bag2array(bag) {
        return bag.reduce(function (result, entry, index) {
            return result.concat(Array(entry).fill(index));
        }, []);
    }
    function array2bag(array, bag) {
        if (!bag) bag = [];
        array.forEach(function (entry) {
            if (bag[entry]) bag[entry]++;
            else bag[entry] = 1;
        }
        return bag;
    }
    var bag = array2bag(lhs);
    switch (o) {
    case 0: // addition
        return bag2array(array2bag(rhs, bag));
    case 1: // difference
        rhs.forEach(function(entry) {
            if (bag[entry]) bag[entry]--;
        });
        return bag2array(bag);
    case 2: // multiplication
        return bag2array(bag.map(function (entry) {
            return entry * rhs;
        }));
    case 3: // division
        return bag2array(bag.map(function (entry) {
            return Math.floor(entry / rhs);
        }));
    case 4: // counting
        return Math.floor(array2bag(rhs).reduce(function (count, entry, index) {
            return Math.min(count, bag[index] / entry);
        }, Infinity));
    case 5: // equality
        return String(bag) == String(array2bag(rhs));
    }
}
</code>```

Title: Implement bag operations

Body:
JavaScript (ES6), 260 bytes

(x,o,y,a=a=>a.reduce((r,e,i)=>[...r,...Array(e).fill(i)],[]),b=(a,r=[])=>a.map(e=>r[e]=-~r[e])&&r)=>[z=>a(b(y,z)),z=>y.map(e=>z[e]&&z[e]--)&&a(z),z=>a(z.map(e=>e*y)),z=>a(z.map(i=>i/y|0)),z=>b(y).map((e,i)=>r=Math.min(r,z[i]/e),r=1/0)|r,z=>``+z==b(y)][o](b(x))

Takes 3 parameters. The first parameter is an array, the second is an operator, the third depends on the operator. Bags are required to hold non-negative integers.

[...] 0 [...] -> addition
[...] 1 [...] -> difference
[...] 2 <n> -> multiplication
[...] 3 <n> -> division
[...] 4 [...] -> counting
[...] 5 [...] -> equality

Ungolfed:

function do_bag_op(lhs, op, rhs) {
    function bag2array(bag) {
        return bag.reduce(function (result, entry, index) {
            return result.concat(Array(entry).fill(index));
        }, []);
    }
    function array2bag(array, bag) {
        if (!bag) bag = [];
        array.forEach(function (entry) {
            if (bag[entry]) bag[entry]++;
            else bag[entry] = 1;
        }
        return bag;
    }
    var bag = array2bag(lhs);
    switch (o) {
    case 0: // addition
        return bag2array(array2bag(rhs, bag));
    case 1: // difference
        rhs.forEach(function(entry) {
            if (bag[entry]) bag[entry]--;
        });
        return bag2array(bag);
    case 2: // multiplication
        return bag2array(bag.map(function (entry) {
            return entry * rhs;
        }));
    case 3: // division
        return bag2array(bag.map(function (entry) {
            return Math.floor(entry / rhs);
        }));
    case 4: // counting
        return Math.floor(array2bag(rhs).reduce(function (count, entry, index) {
            return Math.min(count, bag[index] / entry);
        }, Infinity));
    case 5: // equality
        return String(bag) == String(array2bag(rhs));
    }
}


问:
Love Tester Code Golf
Create program that counts the total number of letters common to two names, and finds the product of their lengths, to function as a "love tester."

Conditions: you may not get a 1:1 answer (being 3 out of 3, etc.) output.

Input

Two names from STDIN or closest alternative.

Output

Compute x as the total number of letters in common between the two names, ignoring case. Compute y as the product of the lengths of the names. Then the output, to STDOUT or closest alternative, is

```<code>Name1 and Name2 have x out of y chances of love.
</code>```

Examples

Input:

```<code>Wesley
Polly
</code>```

Output:

```<code>Wesley and Polly have 2 out of 30 chances of love.
</code>```

Wesley and Polly have 2 letters in common, y and l, and the product of their lengths is 6 * 5 = 30.

Input:

```<code>Bill
Jill
</code>```

Output:

```<code>Bill and Jill have 3 out of 16 chances of love.
</code>```

Bonuses

Subtract 30 bytes for using simplified fractions, i.e. x out of y is in fully reduced form.

Scoring

This is code-golf answers will be scored in bytes with fewer bytes being better.

答:
Dyalog APL, 84-30= 54 bytes

∊' and ' ' have' 'out of' 'chances of love.',¨⍨⊢,{+/⌊⌿+⌿↑1↑¨⍨-32|⍉⎕ucs↑⍵}(,÷∨)(×/≢¨)

This is a train, inspired by Adám's answer.

×/≢¨ product of the lengths

{+/⌊⌿+⌿↑1↑¨⍨-32|⍉⎕ucs↑⍵} chances of love

(,÷v) the concatenation divided by the GCD; between the above two expressions, this reduces the fraction

⊢, prepend the names

,¨⍨ shuffles the strings on the left with the values on the right

∊ flatten

"Chances of love" computation in detail:

{+/⌊⌿+⌿↑1↑¨⍨-32|⍉⎕ucs↑⍵}
                     ↑⍵   arrange the names in a 2×N matrix, pad with spaces
                 ⎕ucs     take ascii codes
                ⍉         transpose the matrix as N×2
             32|          modulo 32 to case-fold
        1↑¨⍨-             for each X create a vector 0 0...0 1 of length X
       ↑                  arrange into a 3d array, pad with 0s
     +⌿                   1st axis sum, obtain freqs per letter and per name
   ⌊⌿                     1st axis min, obt. nr of common occurrences per letter
 +/                       sum

test, test2

Title: Love Tester Code Golf


答:
cubix, 6 bytes

```<code>OI\@+I
</code>```

Try it here!

This maps onto a cube with edge length one.

```<code>  O
I \ @ +
  I
</code>```

Much the same as other stack based answers, push input to the stack twice, add, output and terminate.
Operations are

I, input number

\, reflect down

I, input number

+, add top two of stack

O, output number

\, reflect to the right

@, terminate

The following will also work

```<code>II/@+O
</code>```

Mapping to

```<code>  I
I / @ +
  O
</code>```

Title: Add two numbers

Body:
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
cubix, 6 bytes

OI\@+I

Try it here!

This maps onto a cube with edge length one.

  O
I \ @ +
  I

Much the same as other stack based answers, push input to the stack twice, add, output and terminate.
Operations are

I, input number

\, reflect down

I, input number

+, add top two of stack

O, output number

\, reflect to the right

@, terminate

The following will also work

II/@+O

Mapping to

  I
I / @ +
  O


答:
Perl 5 - 77 Bytes

{$n=$_*$_ for split//,$u{$n}=$n;exit warn$/.'un'[$n==1].'happy'if$u{$n};redo}
```

$n is the input value

Title: Find whether a number is happy or not?

Body:
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers). Given a number print whether it is happy or unhappy.

```<code>Sample Inputs
7
4
13

Sample Outputs
Happy
Unhappy
Happy
</code>```

Note: Your program should not take more than 10 secs for any number below 1,000,000,000.

Body:
Perl 5 - 77 Bytes

{$n=$_*$_ for split//,$u{$n}=$n;exit warn$/.'un'[$n==1].'happy'if$u{$n};redo}

$n is the input value


问:
Smallest groups in an array

Introduction

Let's observe the following array:

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

A group consists of the same digits next to each other. In the above array, there are 5 different groups:

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

 1, 1, 1
          2, 2
                1, 1, 1, 1
                            2, 2, 2
                                     1, 1, 1
</code>```

The smallest group of these is [2, 2], so we output [2, 2].

Let's take another example:

```<code>[3, 3, 3, 4, 4, 4, 4, 5, 5, 4, 4, 3, 3, 4, 4]

 3, 3, 3
          4, 4, 4, 4
                      5, 5
                            4, 4
                                  3, 3
                                        4, 4
</code>```

You can see that there are multiple groups with the same length. The smallest groups are:

```<code>[3, 3], [4, 4], [4, 4] and [5, 5].
</code>```

So we just output [3, 3], [4, 4], [4, 4], [5, 5] in any reasonable format. You may output these in any order.

The Task

Given an array consisting of only positive integers, output the smallest group(s) from the array. You can assume that the array will contain at least 1 integer.

Test cases

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

Input: [1]
Output: [1]

Input: [1, 1, 10, 10, 10, 100, 100]
Output: [1, 1], [100, 100]
</code>```

This is code-golf, so the submission with the least amount of bytes wins!

答:
J, 31 bytes

```<code>[:(#~[:(=<./)#@>)]<;.1~1,2~:/\]
</code>```

Input is an array of values. Output is an array of boxed arrays.

Usage

```<code>   f =: [:(#~[:(=<./)#@>)]<;.1~1,2~:/\]
   f 1 1 2 2 3 3 4
┌─┐
│4│
└─┘
   f 3 3 3 4 4 4 4 5 5 4 4 3 3 4 4
┌───┬───┬───┬───┐
│5 5│4 4│3 3│4 4│
└───┴───┴───┴───┘
</code>```

Explanation

```<code>[:(#~[:(=<./)#@>)]<;.1~1,2~:/\]  Input: s
                              ]  Identity function, get s
                         2       The constant 2
                             \   Operate on each overlapping sublist of size 2
                          ~:/      Check if each pair is unequal, 1 if true else 0
                       1,        Prepend a 1 to that list
                 ]               Identity function, get s
                  <;.1~          Using the list above, chop s at each true index
[:(             )                Operate on the sublists
             #@>                 Get the length of each sublist
     [:(    )                    Operate on the length of each sublist
         <./                     Get the minimum length
        =                        Mark each index as 1 if equal to the min length else 0
   #~                            Copy only the sublists with min length and return
</code>```

Title: Smallest groups in an array

Body:
J, 31 bytes

[:(#~[:(=<./)#@>)]<;.1~1,2~:/\]

Input is an array of values. Output is an array of boxed arrays.

Usage

   f =: [:(#~[:(=<./)#@>)]<;.1~1,2~:/\]
   f 1 1 2 2 3 3 4
┌─┐
│4│
└─┘
   f 3 3 3 4 4 4 4 5 5 4 4 3 3 4 4
┌───┬───┬───┬───┐
│5 5│4 4│3 3│4 4│
└───┴───┴───┴───┘

Explanation

[:(#~[:(=<./)#@>)]<;.1~1,2~:/\]  Input: s
                              ]  Identity function, get s
                         2       The constant 2
                             \   Operate on each overlapping sublist of size 2
                          ~:/      Check if each pair is unequal, 1 if true else 0
                       1,        Prepend a 1 to that list
                 ]               Identity function, get s
                  <;.1~          Using the list above, chop s at each true index
[:(             )                Operate on the sublists
             #@>                 Get the length of each sublist
     [:(    )                    Operate on the length of each sublist
         <./                     Get the minimum length
        =                        Mark each index as 1 if equal to the min length else 0
   #~                            Copy only the sublists with min length and return


问:
I hate Mondays!
You should a program in language X, which will only output its source code (i.e function as a quine) when it is not a monday. On monday it should output some string with a levehnstein distance of 4 from the source code. i.e if the code is aaaa on sunday it should output aaaa and on monday it could output ....aaaa or bbbb or cccc or ..aaaa.. etc

Read about Levehnstein difference here https://en.wikipedia.org/wiki/Levenshtein_distance

Rules

Your solution must be testable

No cheating quines, and any other standard loopholes allowed

Should your language "X" lack access to the date it may assume its a random date at the cost of 35 bytes

This is code golf and I will accept the shortest solution (in bytes) as winner

答:
Reng v.5, noncompeting, 56 bytes

Version 5 brings to you object oriented programming!

```<code>"68¹65¹84¹69¹4&A3¹A1¹B6¹68¹97¹C1¹6Ó`1e4*{Xo}2[r*]rao! ;~
</code>```

This is a standard quine. Simply, "rao! ;~ executes , then outputs the programming, then exits.

¹ is Manhattan addition, e.g., digit concatenation. This gives the char codes of DATE, then 4& retrieves the date from the date module. (Equivalently, "DATE"4&.) This pushes a date object. (While it looks like it should be easily retrievable from the display in the stack, this is just how it prints in the stack display. It is unable to be manipulated.)

The next series provides another pseudo string, translating to getDay. Then, we get the property getDay of the date object on the stack using 6Ó. We then execute it with `. This provides JS's getDay. When it's 1, it's monday. We check for equality with 1 using 1e, then multiply by four. {Xo} pushes a code block that prints (o) char 33 (X), or !. 2[r creates a new stack with the top two items in reverse order. Then, we repeat (*) the code block 4 times (when monday) or 0 times (any other day). On monday, it prints 4 !s. Otherwise, it prints nothing. Then the string captured by wraparound is printed, and we have the rest of our source.

Output on monday:

```<code>!!!!68¹65¹84¹69¹4&A3¹A1¹B6¹68¹97¹C1¹6Ó`1e4*{Xo}2[r*]rao! ;~
</code>```

On other days:

```<code>68¹65¹84¹69¹4&A3¹A1¹B6¹68¹97¹C1¹6Ó`1e4*{Xo}2[r*]rao! ;~
</code>```

Title: I hate Mondays!

Body:
Reng v.5, noncompeting, 56 bytes

Version 5 brings to you object oriented programming!

"68¹65¹84¹69¹4&A3¹A1¹B6¹68¹97¹C1¹6Ó`1e4*{Xo}2[r*]rao! ;~

This is a standard quine. Simply, "<code>rao! ;~ executes <code>, then outputs the programming, then exits.

¹ is Manhattan addition, e.g., digit concatenation. This gives the char codes of DATE, then 4& retrieves the date from the date module. (Equivalently, "DATE"4&.) This pushes a date object. (While it looks like it should be easily retrievable from the display in the stack, this is just how it prints in the stack display. It is unable to be manipulated.)

The next series provides another pseudo string, translating to getDay. Then, we get the property getDay of the date object on the stack using 6Ó. We then execute it with `. This provides JS's getDay. When it's 1, it's monday. We check for equality with 1 using 1e, then multiply by four. {Xo} pushes a code block that prints (o) char 33 (X), or !. 2[r creates a new stack with the top two items in reverse order. Then, we repeat (*) the code block 4 times (when monday) or 0 times (any other day). On monday, it prints 4 !s. Otherwise, it prints nothing. Then the string captured by wraparound is printed, and we have the rest of our source.

Output on monday:

!!!!68¹65¹84¹69¹4&A3¹A1¹B6¹68¹97¹C1¹6Ó`1e4*{Xo}2[r*]rao! ;~

On other days:

68¹65¹84¹69¹4&A3¹A1¹B6¹68¹97¹C1¹6Ó`1e4*{Xo}2[r*]rao! ;~


答:
Python, 97

Using a different method than the rejection sampling, this picks a random list of indices of random even length and alternates adding and subtracting to the elements at these indices.

```<code>from random import*;a=[4]*18;d=1
for i in sample(range(18),2*randint(0,9)):a[i]+=d;d=-d
print a
</code>```

Title: Can you Golf Golf?

Body:
Python, 97

Using a different method than the rejection sampling, this picks a random list of indices of random even length and alternates adding and subtracting to the elements at these indices.

from random import*;a=[4]*18;d=1
for i in sample(range(18),2*randint(0,9)):a[i]+=d;d=-d
print a


问:
Compute the runs of a string
Consider the following definitions taken from The number of runs in a string by W. Rytter.  Note that word, string and substring are all roughly synonyms.

A run in a string is a nonextendable (with the same minimal period)
  periodic segment in a string.

A period p of a word w is any positive integer p such that w[i]=w[i+p]
  whenever both sides of this equation are defined. Let per(w) denote
  the size of the smallest period of w . We say that a word w is
  periodic iff per(w) <= |w|/2.

For, example consider the string x = abcab. per(abcab) = 3 as x[1] = x[1+3] = a, x[2]=x[2+3] = b and there is no smaller period. The string abcab is therefore not periodic.  However, the string abab is periodic as per(abab) = 2.

A run (or maximal periodicity) in a string w is an interval [i...j] with j>=i, such that

w[i...j] is a periodic word with the period p = per(w[i...j])

It is maximal. Formally, neither w[i-1] = w[i-1+p] nor w[j+1] = w[j+1-p].  Informally, the run cannot be contained in a larger run with the same period.

Denote by RUNS(w) the set of runs of w.

Examples

The four runs of atattatt are [4,5] = tt, [7,8] = tt, [1,4] = atat, [2,8] = tattatt.

The string aabaabaaaacaacac contains the following 7 runs:

[1,2] = aa, [4,5] = aa, [7,10] = aaaa, [12,13] = aa, [13,16] = acac, [1,8] = aabaabaa, [9,15] = aacaaca.

Your output should be a list of runs. Each run should specify the interval it represents but does not need to output the substring itself. The exact formatting can be whatever is convenient for you.

The examples use 1-indexing but you are free to use 0-indexing instead if it is more convenient.

TASK

Write code that given a string w, output RUNS(w).

Languages and input

You can use any language you like and take the input string in whatever form is most convenient.  You must give a full program however and you should show an example of your code running on the example input.

答:
CJam, 66

```<code>q:A,2m*{~A>_@)_@<2*@@2*<=},{_2$-2>2,.+={+}&}*]{[_1=\)\0=2*)+]}%_&p
</code>```

Try it online

Brief explanation:

The algorithm works in 4 steps (first 3 of them corresponding with the 3 main blocks you can observe):

Find all [length index] pairs that correspond to a duplicated substring (such as aabaabaaaacaacac); these are parts of runs.

Concatenate pairs that are part of the same run, i.e. consecutive indices and same length/period.

Construct the actual runs, by taking the minimum index and maximum index + 2 * length - 1.

At the end, remove the duplicated runs (which are the same interval obtained with a different period)

I'd like to golf it more, so this is all subject to change.

Title: Compute the runs of a string

Body:
CJam, 66

q:A,2m*{~A>_@)_@<2*@@2*<=},{_2$-2>2,.+={+}&}*]{[_1=\)\0=2*)+]}%_&p

Try it online

Brief explanation:

The algorithm works in 4 steps (first 3 of them corresponding with the 3 main blocks you can observe):

Find all [length index] pairs that correspond to a duplicated substring (such as aabaabaaaacaacac); these are parts of runs.

Concatenate pairs that are part of the same run, i.e. consecutive indices and same length/period.

Construct the actual runs, by taking the minimum index and maximum index + 2 * length - 1.

At the end, remove the duplicated runs (which are the same interval obtained with a different period)

I'd like to golf it more, so this is all subject to change.