问:
Tips for golfing in Haskell
What general tips do you have for golfing in Haskell? I am looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Haskell. Please post only one tip per answer.

If you are new to golfing in Haskell, please have a look at the Guide to Golfing Rules in Haskell. There is also a dedicated Haskell chat room: Of Monads and Men.

答:
Use Data.Lists

This package defines a lot of nice functions on lists! It’s like Data.List in base, but fancier.

Importing it costs 18 bytes (import Data.Lists\n).

Here are some nice things it exports, on top of everything from Data.List:

```<code>Various shortcuts:

  for              ≡ flip map
  unionOf          ≡ foldr union []
  hasAny e x       ≡ any (`elem` e) x
  countElem i      ≡ length . filter (== i)
  list b f xs      ≡ if null xs then b else f xs
  firstOr x        ≡ list x head
  maxList xs       ≡ list 0 maximum
  catchNull f      ≡ list Nothing (Just . f)
  lastToMaybe      ≡ catchNull last
  chop f           ≡ list [] (\x->let (y,ys)=f x in y:chop f ys)
  pair x y         ≡ guard (length x == length y) >> Just (zip x y)
  pairWith f x y   ≡ guard (length x == length y) >> Just (zipWith f x y)

Split functions:

  splitOn "x" "axbxc"                  ≡ ["a","b","c"]
  endBy ";" "foo;bar;baz;"             ≡ ["foo","bar","baz"]
  splitWhen (<0) [1,3,-4,5,7,-9,0,2]   ≡ [[1,3],[5,7],[0,2]]
  splitOneOf ";.," "foo,bar;baz.gluk"  ≡ ["foo","bar","baz","gluk"]
  endByOneOf ";.," "ae;io.,u,"         ≡ ["ae","io","","u"]
  chunk 3 ['a'..'k']                   ≡ ["abc","def","ghi","jk"]
  replace old new                      ≡ intercalate new . splitOn old

Variants of Data.List functions:

  elemRIndex     ∷ a -> [a] -> Maybe Int   (Rightmost index)
  powerslice     ∷ [a] → [[a]]             (All slices of a list)

  spanList       ∷ ([a] → Bool) → [a] → ([a], [a])
  breakList      ∷ ([a] → Bool) → [a] → ([a], [a])
  takeWhileList  ∷ ([a] → Bool) → [a] → [a]
  dropWhileList  ∷ ([a] → Bool) → [a] → [a]

Data.List.Argmax:

  argmin,         argmax           ∷ Ord b ⇒ (a → b) → [a] →   a
  argmins,        argmaxes         ∷ Ord b ⇒ (a → b) → [a] →  [a]
  argminWithMin,  argmaxWithMax    ∷ Ord b ⇒ (a → b) → [a] → ( a,  b)
  argminsWithMin, argmaxesWithMax  ∷ Ord b ⇒ (a → b) → [a] → ([a], b)

Association list functions: treat [(k, v)] as a pseudo-map type.

  delFromAL l k  ≡ filter ((/= k) . fst) l
  addToAL l k v  ≡ (k, v) : delFromAL l k
  keysAL         ≡ map fst
  hasKeyAL k     ≡ any ((== k) . fst)
  flipAL         ∷ [(k, v)] → [(v, [k])]
</code>```

Title: Tips for golfing in Haskell

Body:
Use Data.Lists

This package defines a lot of nice functions on lists! It’s like Data.List in base, but fancier.

Importing it costs 18 bytes (import Data.Lists\n).

Here are some nice things it exports, on top of everything from Data.List:

Various shortcuts:

  for              ≡ flip map
  unionOf          ≡ foldr union []
  hasAny e x       ≡ any (`elem` e) x
  countElem i      ≡ length . filter (== i)
  list b f xs      ≡ if null xs then b else f xs
  firstOr x        ≡ list x head
  maxList xs       ≡ list 0 maximum
  catchNull f      ≡ list Nothing (Just . f)
  lastToMaybe      ≡ catchNull last
  chop f           ≡ list [] (\x->let (y,ys)=f x in y:chop f ys)
  pair x y         ≡ guard (length x == length y) >> Just (zip x y)
  pairWith f x y   ≡ guard (length x == length y) >> Just (zipWith f x y)

Split functions:

  splitOn "x" "axbxc"                  ≡ ["a","b","c"]
  endBy ";" "foo;bar;baz;"             ≡ ["foo","bar","baz"]
  splitWhen (<0) [1,3,-4,5,7,-9,0,2]   ≡ [[1,3],[5,7],[0,2]]
  splitOneOf ";.," "foo,bar;baz.gluk"  ≡ ["foo","bar","baz","gluk"]
  endByOneOf ";.," "ae;io.,u,"         ≡ ["ae","io","","u"]
  chunk 3 ['a'..'k']                   ≡ ["abc","def","ghi","jk"]
  replace old new                      ≡ intercalate new . splitOn old

Variants of Data.List functions:

  elemRIndex     ∷ a -> [a] -> Maybe Int   (Rightmost index)
  powerslice     ∷ [a] → [[a]]             (All slices of a list)

  spanList       ∷ ([a] → Bool) → [a] → ([a], [a])
  breakList      ∷ ([a] → Bool) → [a] → ([a], [a])
  takeWhileList  ∷ ([a] → Bool) → [a] → [a]
  dropWhileList  ∷ ([a] → Bool) → [a] → [a]

Data.List.Argmax:

  argmin,         argmax           ∷ Ord b ⇒ (a → b) → [a] →   a
  argmins,        argmaxes         ∷ Ord b ⇒ (a → b) → [a] →  [a]
  argminWithMin,  argmaxWithMax    ∷ Ord b ⇒ (a → b) → [a] → ( a,  b)
  argminsWithMin, argmaxesWithMax  ∷ Ord b ⇒ (a → b) → [a] → ([a], b)

Association list functions: treat [(k, v)] as a pseudo-map type.

  delFromAL l k  ≡ filter ((/= k) . fst) l
  addToAL l k v  ≡ (k, v) : delFromAL l k
  keysAL         ≡ map fst
  hasKeyAL k     ≡ any ((== k) . fst)
  flipAL         ∷ [(k, v)] → [(v, [k])]


问:
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.

答:
Pyth, 26 bytes

```<code>t#Mf%+QlT2mcdf<>dTS<dTd.pS

          m            .pSQ   Map over permutations d of [1, …, Q]:
             f        d         Find all indices T in [1, …, Q] such that
               >dT                the last Q-T elements of d
              <   S<dT            is less than the sorted first T elements of d
           cd                   Chop d at those indices
   f                          Filter on results T such that
      Q                         the input number Q
     + lT                       plus the length of T
    %    2                      modulo 2
                                is truthy (1)
t#M                           In each result, remove 0- and 1-cycles.
</code>```

dTS<dTd.pS&input=3&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5" rel="nofollow">Try it online

This solution is based on a neat bijection between permutations in one-line notation and permutations in cycle notation. Of course, there’s the obvious bijection where the two notations represent the same permutation:

[8, 4, 6, 3, 10, 1, 5, 9, 2, 7] = (1 8 9 2 4 3 6)(5 10 7)

but that would take too much code.  Instead, simply chop the one-line notation into pieces before all numbers that are smaller than all their predecessors, call these pieces cycles, and build a new permutation out of them.

[8, 4, 6, 3, 10, 1, 5, 9, 2, 7] ↦ (8)(4 6)(3 10)(1 5 9 2 7)

To reverse this bijection, we can take any permutation in cycle form, rotate each cycle so its smallest number is first, sort the cycles so that their smallest numbers appear in decreasing order, and erase all the parentheses.

ContentLicense: CC BY-SA 3.0

Body:
Pyth, 26 bytes

t#Mf%+QlT2mcdf<>dTS<dTd.pS

          m            .pSQ   Map over permutations d of [1, …, Q]:
             f        d         Find all indices T in [1, …, Q] such that
               >dT                the last Q-T elements of d
              <   S<dT            is less than the sorted first T elements of d
           cd                   Chop d at those indices
   f                          Filter on results T such that
      Q                         the input number Q
     + lT                       plus the length of T
    %    2                      modulo 2
                                is truthy (1)
t#M                           In each result, remove 0- and 1-cycles.

Try it online

This solution is based on a neat bijection between permutations in one-line notation and permutations in cycle notation. Of course, there’s the obvious bijection where the two notations represent the same permutation:

[8, 4, 6, 3, 10, 1, 5, 9, 2, 7] = (1 8 9 2 4 3 6)(5 10 7)

but that would take too much code.  Instead, simply chop the one-line notation into pieces before all numbers that are smaller than all their predecessors, call these pieces cycles, and build a new permutation out of them.

[8, 4, 6, 3, 10, 1, 5, 9, 2, 7] ↦ (8)(4 6)(3 10)(1 5 9 2 7)

To reverse this bijection, we can take any permutation in cycle form, rotate each cycle so its smallest number is first, sort the cycles so that their smallest numbers appear in decreasing order, and erase all the parentheses.


问:
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)

Title: Can you Golf Golf?

Body:
Q (25 characters)

Original (27)

while[72<>sum a:18?3 4 5];a

Sample output

4 4 3 3 4 5 4 3 4 5 5 3 5 5 5 4 3 3

Slightly shorter (25)

{72<>sum x}{x:18?3 4 5}/0


问:
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.

答:
Actually, 11 bytes

```<code>;╗ñ`i@╜í=`M
</code>```

Try it online!

Explanation:

```<code>;╗ñ`i@╜í=`M
;╗           save a copy of input in reg0
  ñ          enumerate
   `i@╜í=`M  for each (index, value) pair:
    i@         flatten, swap
      ╜í       first index in input of value
        =      compare equality
</code>```

Title: Distinct Sieves

Body:
Actually, 11 bytes

;╗ñ`i@╜í=`M

Try it online!

Explanation:

;╗ñ`i@╜í=`M
;╗           save a copy of input in reg0
  ñ          enumerate
   `i@╜í=`M  for each (index, value) pair:
    i@         flatten, swap
      ╜í       first index in input of value
        =      compare equality


问:
Reverse odd runs
Inspiration.

Task

Reverse runs of odd numbers in a given list of 2 to 215 non-negative integers.

Examples

0 1 → 0 1

1 3 → 3 1

1 2 3 → 1 2 3

1 3 2 → 3 1 2

10 7 9 6 8 9 → 10 9 7 6 8 9

23 12 32 23 25 27 → 23 12 32 27 25 23

123 123 345 0 1 9 → 345 123 123 0 9 1

答:
Haskell, <s>46</s> 44 bytes

```<code>h%p|(l,r)<-span(odd.(h*))p=l++h:r
foldr(%)[]
</code>```

Thanks to @xnor for recognizing a fold and saving two bytes.

Title: Reverse odd runs

Body:
Haskell, <s>46</s> 44 bytes

h%p|(l,r)<-span(odd.(h*))p=l++h:r
foldr(%)[]

Thanks to @xnor for recognizing a fold and saving two bytes.


问:
Create output twice the length of the code

The Challenge

Write a complete program that writes twice as many bytes to standard output as the length of the program.

Rules

The program must write ASCII characters to the standard output.

The contents of the output doesn't matter.

The output, measured in bytes, must be exactly twice the length of the program, also measured in bytes, unless you fulfill the bonus.

Any trailing newline is included in the output's byte count.

Bonus

Your program can optionally take a number, n, as input. If so, the output must be exactly n * program length bytes. You can assume that n will always be a positive integer. If no input is provided, n must default to 2.

If you do this,  you can subtract 25 bytes from your score.

Shortest program wins.

Restrictions

No standard loopholes.

The program must be at least 1 byte long.

No adding unnecessary whitespace to the source code to change its length. Similarly, comments don't count.

Unless you fulfill the bonus, the program must accept no input. If you do fulfill the bonus, the integer must be the only input.

Lowest score (program length in bytes - bonus) wins.

The shortest answer for each language wins for that language.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code># Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code># Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code># Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the leaderboard snippet:

```<code># [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

var QUESTION_ID=59436,OVERRIDE_USER=41505;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

```

答:
Desmos, 3 bytes

```<code>9^6
</code>```

Equals 531441

Body:
Desmos, 3 bytes

9^6

Equals 531441


答:
Perl5, 11 bytes

x is string repetition operator

```<code>print 1x22
</code>```

Title: Create output twice the length of the code

Body:
The Challenge

Write a complete program that writes twice as many bytes to standard output as the length of the program.

Rules

The program must write ASCII characters to the standard output.

The contents of the output doesn't matter.

The output, measured in bytes, must be exactly twice the length of the program, also measured in bytes, unless you fulfill the bonus.

Any trailing newline is included in the output's byte count.

Bonus

Your program can optionally take a number, n, as input. If so, the output must be exactly n * program length bytes. You can assume that n will always be a positive integer. If no input is provided, n must default to 2.

If you do this,  you can subtract 25 bytes from your score.

Shortest program wins.

Restrictions

No standard loopholes.

The program must be at least 1 byte long.

No adding unnecessary whitespace to the source code to change its length. Similarly, comments don't count.

Unless you fulfill the bonus, the program must accept no input. If you do fulfill the bonus, the integer must be the only input.

Lowest score (program length in bytes - bonus) wins.

The shortest answer for each language wins for that language.

Leaderboards

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code># Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code># Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code># Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the leaderboard snippet:

```<code># [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

var QUESTION_ID=59436,OVERRIDE_USER=41505;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:
Perl5, 11 bytes

x is string repetition operator

print 1x22


问:
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!

答:
05AB1E, <s>19</s> <s>17</s> 14 bytes

Code:

```<code>Œévy2ä'|ý©ÂQi®
</code>```

Explanation:

```<code>Œ                # Get all substrings of the input
 é               # Sort by length (shortest first)
  vy             # For each element...
    2ä           # Split into two pieces
      '|ý        # Join by "|"
         ©       # Copy this into the register
          Â      # Bifurcate, pushing a and reversed a
           Q     # Check if it's a palindrome
            i®   # If so, push that string again
                 # Implicit, the top element is outputted
</code>```

Uses the CP-1252 encoding. Try it online!.

Title: Where should I put my mirror?

Body:
05AB1E, <s>19</s> <s>17</s> 14 bytes

Code:

Œévy2ä'|ý©ÂQi®

Explanation:

Œ                # Get all substrings of the input
 é               # Sort by length (shortest first)
  vy             # For each element...
    2ä           # Split into two pieces
      '|ý        # Join by "|"
         ©       # Copy this into the register
          Â      # Bifurcate, pushing a and reversed a
           Q     # Check if it's a palindrome
            i®   # If so, push that string again
                 # Implicit, the top element is outputted

Uses the CP-1252 encoding. Try it online!.


答:
Pyth - <s>19</s> <s>17</s> <s>15</s> 13 bytes

Thanks to @FryAmTheEggman for saving me two bytes.

<s>ARRGH the special case for no answer.</s> Solved that!

```<code>e_I#jL\|cL2.:
</code>```

Test Suite.

```<code>e                Last element in list, this works out to longest one
  _I             Invariance under reverse, this detect palindrome
   #             Filter
   jL            Map join
    \|           By "|"
    cL2          Map chop in two pieces
     .:Q)        Substrings. Implicit Q). ) makes it do all substrings.
</code>```

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:
Pyth - <s>19</s> <s>17</s> <s>15</s> 13 bytes

Thanks to @FryAmTheEggman for saving me two bytes.

<s>ARRGH the special case for no answer.</s> Solved that!

e_I#jL\|cL2.:

Test Suite.

e                Last element in list, this works out to longest one
  _I             Invariance under reverse, this detect palindrome
   #             Filter
   jL            Map join
    \|           By "|"
    cL2          Map chop in two pieces
     .:Q)        Substrings. Implicit Q). ) makes it do all substrings.


问:
Starbucks to English
In the classic days of Starbucks before these newfangled sticker-printers and wireless drivethrough headset palmtop scanner dealies, in the heady days of 2000-ish, Starbucks had a concise system for describing beverages with a strict syntax and accompanying encoded form.

Vertically on the cup there are a series of labelled boxes which may contain certain values.:

```<code>Decaf
[   ]     -blank-  X  1/2  1/3  2/3
Shots
[   ]     -blank-  0 1 2 3 ... 20    followed by    S T G V
Syrup
[   ]     -blank-  V M C H
Milk
[   ]     -blank-  Wh % N B
Custom
[    ]    -blank- ((-|x)?(F|WC|M|CR) )+
Drink
[   ]     E EM ECP A L C CM
</code>```

But we will use a horizontal form for easier manipulation. These are the names of the 6 fields of the input which may be any convenient form. Examples here are simple CSV. The Custom field and Syrup fields each may be a concatenation of several values. You may use any convenient subdelimiter. Examples here use space. The Shots field is also a concatenation of a (possible) number and a designation of the cup size (which is implicit in the physical cup but naturally fits in this place in the encoding).

The Decaf field values are translated into words like this

```<code>-blank-   -nothing-
X         "decaf"
1/2       "half-caf"
1/3       "one-third-caf"
2/3       "two-thirds-caf"
</code>```

Logically, the fractional values are only permissible when the number of shots is divisible by the denominator; but for this challenge it is not necessary to detect or diagnose this error.

The Shots field should be broken into its numerical component (if present) and the size identifier. The number should be displayed in latin tuple form: single, double, triple, quadruple, quintuple, beyond 5 just print the number and the suffix "-tuple" ie. 7-tuple, 16-tuple. The size designations are:

```<code>S  short
T  tall
G  grande
V  venti
</code>```

Eg.

```<code>2T  double tall
3G  triple grande
</code>```

The Syrup field may contain one or more of several optional-number/lettercode tokens. The maximum number of a syrup is 20. Even that is too much. LOL.

```<code>V  vanilla
C  caramel
M  mocha
H  hazelnut
</code>```

Eg.

```<code>2V 2C     two vanilla two caramel
H         hazelnut
M H 1V    mocha hazelnut one vanilla
</code>```

The Milk field may contain one of the following.

```<code>Wh  whole-milk
%   two-percent
N   skim
B   breve
</code>```

The Custom field may contain one or more of several modifiers with optional x or - sign.

```<code>x  extra     F   foam
-  no        WC  whip
             M   mocha drizzle
             CR  caramel drizzle
</code>```

The Drink field contains one drink id.

```<code>E    espresso
EM   espresso macchiato
ECP  espresso con panna
A    americano
L    latte
C    cappuccino
CM   caramel macchiato
</code>```

Any field may be blank except for the size designation and the drink id.

Examples.

```<code>,3G,V,Wh,,L    =>   triple grande vanilla whole-milk latte
X,2T,,N,,L     =>   decaf double tall skim latte
1/2,V,,,,CM    =>   half-caf venti caramel macchiato
2/3,3V,3V,B,WC,L  => two-thirds-caf triple venti three vanilla breve whip latte
,G,,,xCR,CM    =>   grande extra caramel drizzle caramel macchiato
X,4T,2M 2C,B,xWC -F xM,C  =>
  decaf quadruple tall two mocha two caramel breve extra whip no foam extra mocha drizzle cappuccino
</code>```

There is no need to diagnose erroneous or illogical concoctions such as a "no foam ... cappuccino*.

Additional Complication

For only the drinks with the word espresso, the number single should be replaced by solo and double should be replaced by doppio. And the size may be unspecified and omitted. Also, just for the bare espresso drink itself, if the only other specification is one of these two specially-replaced numbers-of-shots, then the word espresso itself should be omitted.

```<code>-blank-   -nothing-
X         "decaf"
1/2       "half-caf"
1/3       "one-third-caf"
2/3       "two-thirds-caf"
</code>```0

Additional observations on 'reading a cup'

This part is not a requirement for this challenge but may be a useful refinement in applying this sort of verbalized system in other domains.

I mentioned syntax at the very beginning, and by applying the schema to incoming streams of words, orders could be transmitted verbally by several order takers to the barista making beverages. The rough framework SIZE .... DRINK provides demarcation between several orders spoken at once. There is thus a tendency to make all the interior attributes as adjectival phrases so the order also has a valid English noun-phrase structure. So whip is often spoken with whip or whipped and foam is often spoken foamy or with foam.

Thus, for some old-time baristas, they're not "correcting you" when they repeat the order in the proper format (well,... sometimes). They're simply organizing the information for the purpose of remembering all the details exactly. By schematizing the information, an entire beverage order becomes a single unit for the purpose of applying the magic number 7 plus or minus 2. So a barista with this skill can hold 5-9 orders in their head provided other distractions do not consume too much head room. :)

答:
Ruby -plaF,, <s>975</s> 870 bytes

I got a random upvote on my old, almost-four-year-old answer to this question, and because of my comments on how horribly it went (you can check the post history if you want to see what I wrote before) I was inspired to make it better (aka: rewrite most of it from the ground up) and managed to golf over a hundred bytes off it. Still longer than the Python answer, but I'm much happier with how things turned out now.

About 20 bytes were saved by switching from trying to run regex patterns to affect specific parts of the comma structure to using the -aF, flag to autosplit a line of input on commas and save it to $F, allowing me to modify some elements before stitching it back together and finally modifying the output variable with the last few sub/gsub commands.

Honestly, the number of regex replacements made here means most of this could be a Retina program, but I don't know Retina well enough for that.

g=->n,c{n.grep(/^ ?#{c}/i)[0]}
n=%w"0 one two three four five six seven eight nine ten eleven twelve thir four fif";n+=n[6,4]<<'twenty'
$F[1].sub!(/(\d*)(\w)?/){i=eval$1;"#{i&&(%w"0 sing doub trip quadrup quintup"[i]||$1+"-tup")+"le"} #{g[%w"short tall grande venti",$2]if$2}"}
$F[2].gsub!(/(\d*)(\w)/){i=eval$1;"#{i&&n[i]}#{'teen'if(13..19)===i} #{g[%w"vanilla caramel mocha hazelnut",$2]}"}
$F[3].sub!(/.+/){%w"skim whole-milk breve two-percent"[$&.sum%26%4]}
$F[4].gsub!(/(x|-)?(\w+)/){"#{%w"extra no"[$1.ord%2]if$1} #{g[%w"caramelD mochaD whip foam",$2[0]].sub ?D,' drizzle'}"}
$_=$F*' '
sub(/^\S+/){%w"de - half- one-third- two-thirds-"[$&.sum%8]+"caf"}
sub'CP',' con pana'
sub'CM','caramel'+m=' macchiato'
e='espresso'
gsub(/[A-Z]/){g[%w"americano latte cappuccino"+[m,e],$&]}
gsub(/ +/,' ')
$_.strip!
sub(/[sd]...le/){g[%w"doppio solo",$&[0]]}if$_[e]
sub'o '+e,?o
```

Try it online!

Title: Starbucks to English

Body:
Ruby -plaF,, <s>975</s> 870 bytes

I got a random upvote on my old, almost-four-year-old answer to this question, and because of my comments on how horribly it went (you can check the post history if you want to see what I wrote before) I was inspired to make it better (aka: rewrite most of it from the ground up) and managed to golf over a hundred bytes off it. Still longer than the Python answer, but I'm much happier with how things turned out now.

About 20 bytes were saved by switching from trying to run regex patterns to affect specific parts of the comma structure to using the -aF, flag to autosplit a line of input on commas and save it to $F, allowing me to modify some elements before stitching it back together and finally modifying the output variable with the last few sub/gsub commands.

Honestly, the number of regex replacements made here means most of this could be a Retina program, but I don't know Retina well enough for that.

g=->n,c{n.grep(/^ ?#{c}/i)[0]}
n=%w"0 one two three four five six seven eight nine ten eleven twelve thir four fif";n+=n[6,4]<<'twenty'
$F[1].sub!(/(\d*)(\w)?/){i=eval$1;"#{i&&(%w"0 sing doub trip quadrup quintup"[i]||$1+"-tup")+"le"} #{g[%w"short tall grande venti",$2]if$2}"}
$F[2].gsub!(/(\d*)(\w)/){i=eval$1;"#{i&&n[i]}#{'teen'if(13..19)===i} #{g[%w"vanilla caramel mocha hazelnut",$2]}"}
$F[3].sub!(/.+/){%w"skim whole-milk breve two-percent"[$&.sum%26%4]}
$F[4].gsub!(/(x|-)?(\w+)/){"#{%w"extra no"[$1.ord%2]if$1} #{g[%w"caramelD mochaD whip foam",$2[0]].sub ?D,' drizzle'}"}
$_=$F*' '
sub(/^\S+/){%w"de - half- one-third- two-thirds-"[$&.sum%8]+"caf"}
sub'CP',' con pana'
sub'CM','caramel'+m=' macchiato'
e='espresso'
gsub(/[A-Z]/){g[%w"americano latte cappuccino"+[m,e],$&]}
gsub(/ +/,' ')
$_.strip!
sub(/[sd]...le/){g[%w"doppio solo",$&[0]]}if$_[e]
sub'o '+e,?o

<a href="https://tio.run/##ZZJhb9MwEIa/91ccWVe3xElJOiEQhAo6Bh8oQoAYIgvIS9zGmmMHx2nLuv51yjndhgRRJNt3vnufO59pL3/t98skeKFovlXh0vB6OP4O06NtvhuLUfoo2/VUcrz2HoFWHOxagy0N57DQrYGFWHFoxAYavuIKuFiWFpRwF91Rdla75hKv2VKYu6iF90z5iUof05Ps@XOCN5T9RXr9szTKwqa9fDAcDy@Kh6PhxXo0HY@2IuErJvvRM@9oKwaDYcfTCLWEQreXYI2o4WfLCtO6VSjb1l4qspubfuR7gTuNfE9ybwdH22WK0U2pjQXLpISlYarggKRWeLQfZ2LRj3feztHEWbj8B@d/GoVKu6MtsZwrIhbDaBKG0dNRkiTiXm/FlJCSQc4Mq7iESuclg5Jdc6la28neSk7uGhD6KOVQr0QF61JLHlRCXsGl4avuIYKamxypvbQ/wJjqOH58fJJ1SU7@cm9ugtEUwX1HjsCYkW@sYaA0BkahNsVxV3N0D3sLeXqgPEVxbO9Cs8px4kR0hDA9pQQKI66vJScd/I@kf/aQAOmhG4fo4tNtBdjdAGuVi8DNUOAGoQi6CrptE9xX8CTzUX2ByTAFmX0gKJFrBTVTjBxsc7TdAhK/SghULM9LwawmPZ4Q3tSGNw0elh1F@jL4liFGVxgGGZEzpUEyazm@Rl23eS6wFX5aUZ7R/gAbeIgEf4zqZIR1hY2bsAeHutKmyMIwlPwua6HrWmhotNTYoIFr0A77@SPlWYesgficTvV@Tydv6Bd6XlL6rveVxp8pfe@20ThGM36zeS8eT@jki/tf0fMZOukbdGxmH53zKz35TN9CPIdoMsMLm/MZBGewmYPz92hMIxdHX897NHIJXzvbYZ10629dW6FVsw9qyc7oHw" rel="nofollow noreferrer" title="Ruby – Try It Online">Try it online!

ContentLicense: CC BY-SA 4.0


答:
k (<s>18 17</s> 16 chars)

Back to the original approach, credit to CS for the improvement.

```<code>(+/4-){3+18?3}/0
</code>```

Other approach (17 chars), same method as the J solution, H/T to CS

```<code>4+a,-a:9?2 -18?18
</code>```

<s>Old version:

```<code>(72-+/){18?3+!3}/0
</code>```

</s>

Not susceptible to stack-overflow and runs in fixed amount of space.

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:
k (<s>18 17</s> 16 chars)

Back to the original approach, credit to CS for the improvement.

(+/4-){3+18?3}/0

Other approach (17 chars), same method as the J solution, H/T to CS

4+a,-a:9?2 -18?18

<s>Old version:

(72-+/){18?3+!3}/0

</s>

Not susceptible to stack-overflow and runs in fixed amount of space.


答:
Python 2, 149 bytes

R,L,s=range,len,input()
t=max([s[i:j/2+i/2]for i in R(L(s))for j in R(L(s)+1)if s[i:j]==s[i:j][::-1]and(j-i)%2<1],key=L)
print t+'|'*(L(t)>0)+t[::-1]
```

Try it online

This program finds the first half of the largest palindromic substring of even length, and prints that string, followed by a |, followed by that string reversed. If there is no suitable string, t will be the empty string, and '|'*(L(t)>0) will evaluate to the empty string.

Title: Where should I put my mirror?

Body:
Python 2, 149 bytes

R,L,s=range,len,input()
t=max([s[i:j/2+i/2]for i in R(L(s))for j in R(L(s)+1)if s[i:j]==s[i:j][::-1]and(j-i)%2<1],key=L)
print t+'|'*(L(t)>0)+t[::-1]

Try it online

This program finds the first half of the largest palindromic substring of even length, and prints that string, followed by a |, followed by that string reversed. If there is no suitable string, t will be the empty string, and '|'*(L(t)>0) will evaluate to the empty string.


Title: Where should I put my mirror?

Body:
JavaScript, <s>100</s> 99 bytes

s=>eval('for(O=i=0;s[i++];O=O[j+j]?O:o)for(o="|",j=0;(S=s[i-1-j])&&S==s[i+j++];o=S+o+S);O[1]?O:""')

or

s=>eval('for(O="",i=0;s[i++];O=O[j+j]||j<2?O:o)for(o="|",j=0;(S=s[i-1-j])&&S==s[i+j++];o=S+o+S);O')


答:
Python 2, <s>102</s> 97 bytes

def f(s):h=len(s)/2;r=s[:h]+'|'+s[h:];return s and max(r*(r==r[::-1]),f(s[1:]),f(s[:-1]),key=len)
```

Rather slow and inefficient... Verify the smaller test cases on Ideone.

Title: Where should I put my mirror?

Body:
Python 2, <s>102</s> 97 bytes

def f(s):h=len(s)/2;r=s[:h]+'|'+s[h:];return s and max(r*(r==r[::-1]),f(s[1:]),f(s[:-1]),key=len)

Rather slow and inefficient... Verify the smaller test cases on Ideone.


答:
Ruby, 24 bytes (with bonus)

```<code>->m{m.to_i.times {49.times {print "a"}}}[gets||2]
</code>```

Body:
Ruby, 24 bytes (with bonus)

->m{m.to_i.times {49.times {print "a"}}}[gets||2]


答:
Retina, 66 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>M!&`(.)+(?<-1>\1)+(?(1)¶)
O$#`.+
$.&
A-2`
^(.)+?(?=(?<-1>.)+$)
$&|
</code>```

Try it online! (The first line enables testing of several linefeed-separated test cases at once.)

Hmmm, much longer than I would like...

Title: Where should I put my mirror?

Body:
Retina, 66 bytes

Byte count assumes ISO 8859-1 encoding.

M!&`(.)+(?<-1>\1)+(?(1)¶)
O$#`.+
$.&
A-2`
^(.)+?(?=(?<-1>.)+$)
$&|

Try it online! (The first line enables testing of several linefeed-separated test cases at once.)

Hmmm, much longer than I would like...


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

```

答:
Befunge, 5 bytes

&&+.@

& takes an integer as input and puts it on the stack

+ pops two numbers from the stack and puts the sum back on the stack

. pops a number from the stack and outputs it as an integer

@ ends the program

Try it: http://www.quirkster.com/iano/js/befunge.html

Title: Add two numbers


问:
Integer square root of integer
Problem:

In your choice of language, write the shortest function that returns the floor of the square root of an unsigned 64-bit integer.

Test cases:

Your function must work correctly for all inputs, but here are a few which help illustrate the idea:

```<code>               INPUT ⟶ OUTPUT

                   0 ⟶  0
                   1 ⟶  1
                   2 ⟶  1
                   3 ⟶  1
                   4 ⟶  2
                   8 ⟶  2
                   9 ⟶  3
                  15 ⟶  3
                  16 ⟶  4
               65535 ⟶ 255
               65536 ⟶ 256
18446744073709551615 ⟶ 4294967295
</code>```

Rules:

You can name your function anything you like. (Unnamed, anonymous, or lambda functions are fine, as long as they are somehow callable.)

Character count is what matters most in this challenge, but runtime is also important. I'm sure you could scan upwards iteratively for the answer in O(√n) time with a very small character count, but O(log(n)) time would really be better (that is, assuming an input value of n, not a bit-length of n).

You will probably want to implement the function using purely integer and/or boolean artithmetic. However, if you really want to use floating-point calculations, then that is fine so long as you call no library functions. So, simply saying return (n>0)?(uint32_t)sqrtl(n):-1; in C is off limits even though it would produce the correct result. If you're using floating-point arithmetic, you may use *, /, +, -, and exponentiation (e.g., ** or ^ if it's a built-in operator in your language of choice, but only exponentiation of powers not less than 1). This restriction is to prevent "cheating" by calling sqrt() or a variant or raising a value to the ½ power.

If you're using floating-point operations (see #3), you aren't required that the return type be integer; only that that the return value is an integer, e.g., floor(sqrt(n)), and be able to hold any unsigned 32-bit value.

If you're using C/C++, you may assume the existence of unsigned 64-bit and 32-bit integer types, e.g., uint64_t and uint32_t as defined in stdint.h. Otherwise, just make sure your integer type is capable of holding any 64-bit unsigned integer.

If your langauge does not support 64-bit integers (for example, Brainfuck apparently only has 8-bit integer support), then do your best with that and state the limitation in your answer title. That said, if you can figure out how to encode a 64-bit integer and correctly obtain the square root of it using 8-bit primitive arithmetic, then more power to you!

Have fun and get creative!

答:
Lua, 74 bytes

```<code>n=io.read() if n==0 then print(0) os.exit() end print(math.floor(n^1.5/n))
</code>```

Try it online!

Title: Integer square root of integer

Body:
Lua, 74 bytes

n=io.read() if n==0 then print(0) os.exit() end print(math.floor(n^1.5/n))

Try it online!


问:
Full Width Text
Full width text is text that has a space after every character, including the last one. For instance, the first sentence of this question becomes:

```<code>F u l l   w i d t h   t e x t   i s   t e x t   t h a t   h a s   a   s p a c e   a f t e r   e v e r y   c h a r a c t e r ,   i n c l u d i n g   t h e   l a s t   o n e .
</code>```

Write a program that takes a line in text from standard input and outputs it as full-width text to standard out.

Leaderboard

var QUESTION_ID=75979,OVERRIDE_USER=52353;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

```

答:
Tcl, 44 bytes

```<code>puts [regsub -all {(.)} [gets stdin] {\1 }]
</code>```

Title: Full Width Text

Body:
Tcl, 44 bytes

puts [regsub -all {(.)} [gets stdin] {\1 }]


答:
Pyke, 7 bytes (noncompeting)

```<code>#Xt)ltt
</code>```

Try it here!

Finds the first number where i*i>=n and takes 2 from the number of numbers it had to check to get there

Title: Integer square root of integer

Body:
Problem:

In your choice of language, write the shortest function that returns the floor of the square root of an unsigned 64-bit integer.

Test cases:

Your function must work correctly for all inputs, but here are a few which help illustrate the idea:

```<code>               INPUT ⟶ OUTPUT

                   0 ⟶  0
                   1 ⟶  1
                   2 ⟶  1
                   3 ⟶  1
                   4 ⟶  2
                   8 ⟶  2
                   9 ⟶  3
                  15 ⟶  3
                  16 ⟶  4
               65535 ⟶ 255
               65536 ⟶ 256
18446744073709551615 ⟶ 4294967295
</code>```

Rules:

You can name your function anything you like. (Unnamed, anonymous, or lambda functions are fine, as long as they are somehow callable.)

Character count is what matters most in this challenge, but runtime is also important. I'm sure you could scan upwards iteratively for the answer in O(√n) time with a very small character count, but O(log(n)) time would really be better (that is, assuming an input value of n, not a bit-length of n).

You will probably want to implement the function using purely integer and/or boolean artithmetic. However, if you really want to use floating-point calculations, then that is fine so long as you call no library functions. So, simply saying return (n>0)?(uint32_t)sqrtl(n):-1; in C is off limits even though it would produce the correct result. If you're using floating-point arithmetic, you may use *, /, +, -, and exponentiation (e.g., ** or ^ if it's a built-in operator in your language of choice, but only exponentiation of powers not less than 1). This restriction is to prevent "cheating" by calling sqrt() or a variant or raising a value to the ½ power.

If you're using floating-point operations (see #3), you aren't required that the return type be integer; only that that the return value is an integer, e.g., floor(sqrt(n)), and be able to hold any unsigned 32-bit value.

If you're using C/C++, you may assume the existence of unsigned 64-bit and 32-bit integer types, e.g., uint64_t and uint32_t as defined in stdint.h. Otherwise, just make sure your integer type is capable of holding any 64-bit unsigned integer.

If your langauge does not support 64-bit integers (for example, Brainfuck apparently only has 8-bit integer support), then do your best with that and state the limitation in your answer title. That said, if you can figure out how to encode a 64-bit integer and correctly obtain the square root of it using 8-bit primitive arithmetic, then more power to you!

Have fun and get creative!

Body:
Pyke, 7 bytes (noncompeting)

#Xt)ltt

Try it here!

Finds the first number where i*i>=n and takes 2 from the number of numbers it had to check to get there


答:
Pyke, 4 bytes

```<code>F@oq
</code>```

Try it here!

```<code>     - o = 0 #(Implicit)
F    - for i in input:
 @   -   input.index(i)
   q -  ^==V
  o  -   o+=1
</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:
Pyke, 4 bytes

F@oq

Try it here!

     - o = 0 #(Implicit)
F    - for i in input:
 @   -   input.index(i)
   q -  ^==V
  o  -   o+=1


答:
JavaScript (ES6), 91

s=>[...s].map((d,i)=>{for(a='|',j=0;d=s[i-j],d&&d==s[i-~j];r=r[j+++j]?r:a)a=d+a+d},r='')&&r
```
<p><em>Less golfed</em></p>
<pre class="lang-js prettyprint-override"><code>f=s=>
  [...s].map(
    (d,i) => {
    for(a='|', j=0; d=s[i-j], d&&d==s[i-~j]; r = r[j++ +j]? r : a)
      a = d+a+d
    }, r=''
  ) && r
</code>```

Test

F=
s=>[...s].map((d,i)=>{for(a='|',j=0;d=s[i-j],d&&d==s[i-~j];r=r[j+++j]?r:a)a=d+a+d},r='')&&r

;[["Hello World", "l|l"]
,["Programming Puzzles and Code-Golf", "m|m"]
,["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"]]
.forEach(t=>{
  var i=t[0],k=t[1],r=F(i)
  console.log(k==r?'OK ':'KO ',i+' -> '+r,k!=r?'(check '+k+')':'')
})  ```

Title: Where should I put my mirror?

Body:
JavaScript (ES6), 91

s=>[...s].map((d,i)=>{for(a='|',j=0;d=s[i-j],d&&d==s[i-~j];r=r[j+++j]?r:a)a=d+a+d},r='')&&r

Less golfed

f=s=>
  [...s].map(
    (d,i) => {
    for(a='|', j=0; d=s[i-j], d&&d==s[i-~j]; r = r[j++ +j]? r : a)
      a = d+a+d
    }, r=''
  ) && r

Test

F=
s=>[...s].map((d,i)=>{for(a='|',j=0;d=s[i-j],d&&d==s[i-~j];r=r[j+++j]?r:a)a=d+a+d},r='')&&r

;[["Hello World", "l|l"]
,["Programming Puzzles and Code-Golf", "m|m"]
,["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"]]
.forEach(t=>{
  var i=t[0],k=t[1],r=F(i)
  console.log(k==r?'OK ':'KO ',i+' -> '+r,k!=r?'(check '+k+')':'')
})


答:
Prelude, 4 bytes

```<code>??+!
</code>```

Requires my modified Prelude interpreter which uses decimal I/O.

Like several other answers, this is just read, read, add, write.

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:
Prelude, 4 bytes

??+!

Requires my modified Prelude interpreter which uses decimal I/O.

Like several other answers, this is just read, read, add, write.


答:
Lua, 133 bytes

s=...for i=#s,1,-1 do for j=1,#s-i do m=j+i/2-i%2/2t=s:sub(j,m).."|"..s:sub(m+1,i+j)if t==t.reverse(t)then print(t)return end end end
```

Verify all testcases on Ideone.com.

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:
Lua, 133 bytes

s=...for i=#s,1,-1 do for j=1,#s-i do m=j+i/2-i%2/2t=s:sub(j,m).."|"..s:sub(m+1,i+j)if t==t.reverse(t)then print(t)return end end end

Verify all testcases on Ideone.com.


答:
Perl 5, <s>105</s> <s>100</s> 98 + 1 = <s>106</s> <s>101</s> 99 bytes

```<code>/(?=((.)(?1)?\2)(?{[push@_,$1})(?!))/;($_)=sort{length$b<=>length$a}@_;substr($_,length>>1,0)='|'if$_
</code>```

I just wanted to give recursive regexes a go. Needs the -p option. Edit: Saved (crossed out 4) 7 bytes thanks to @msh210. (The missing byte is due to a saving that was superseded by @msh210's latest saving.)

Title: Where should I put my mirror?

Body:
Perl 5, <s>105</s> <s>100</s> 98 + 1 = <s>106</s> <s>101</s> 99 bytes

/(?=((.)(?1)?\2)(?{[push@_,$1})(?!))/;($_)=sort{length$b<=>length$a}@_;substr($_,length>>1,0)='|'if$_

I just wanted to give recursive regexes a go. Needs the -p option. Edit: Saved (crossed out 4) 7 bytes thanks to @msh210. (The missing byte is due to a saving that was superseded by @msh210's latest saving.)


答:
Haskell, <s>29</s> 27  bytes

```<code>f a=[elem x t|x:t<-tails a]
</code>```

Uses False as true, True as false value:

```<code>λ> let f a=[elem x t|x:t<-tails a] in f [5, 9, 7, 5, 6, 0, 5]
[True,False,False,True,False,False,False]
</code>```

You might have to import Data.List to use tails but,  tryhaskell.org runs the code as is.

Title: Distinct Sieves

Body:
Haskell, <s>29</s> 27  bytes

f a=[elem x t|x:t<-tails a]

Uses False as true, True as false value:

λ> let f a=[elem x t|x:t<-tails a] in f [5, 9, 7, 5, 6, 0, 5]
[True,False,False,True,False,False,False]

You might have to import Data.List to use tails but,  tryhaskell.org runs the code as is.


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

答:
Mathematica, 5 bytes

```<code>Split
</code>```

... there's a built-in for that.

Title: Groups of repeating items

Body:
Mathematica, 5 bytes

Split

... there's a built-in for that.


答:
C (94 chars)

```<code>int h[18],s=0,i;
while(s!=72)for(i=s=0;i<18;s+=h[i++]=rand()%3+3);
while(i)printf("%d ",h[--i]);
</code>```

The s=0 on line 1 may not be required, because what are the chances an uninitialized int will equal 72?  I just don't like reading uninitialized values in straight C.  Also, this probably requires seeding the rand() function.

output

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

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:
C (94 chars)

int h[18],s=0,i;
while(s!=72)for(i=s=0;i<18;s+=h[i++]=rand()%3+3);
while(i)printf("%d ",h[--i]);

The s=0 on line 1 may not be required, because what are the chances an uninitialized int will equal 72?  I just don't like reading uninitialized values in straight C.  Also, this probably requires seeding the rand() function.

output

3 3 3 4 5 5 3 3 4 5 5 4 3 4 5 5 5 3


答:
MATL, 9 bytes

```<code>Y'v"@Z}Y"

Y'     % Take input. Run-length encoding. Gives two row arrays: values and run lengths
v      % Concatenate vertically
"      % For each column
  @Z}  %   Push column and split into its two elements
  Y"   %   Run-length decoding
       % End for. Implicitly display
</code>```

Input is a row array of numbers, with spaces or commas as separators.

Try it online! Test with non-integer numbers.

MATL, 11 bytes

```<code>lidgvYsG7XQ
</code>```

Input is a column array of either numbers or characters, using ; as separator.

Try it online! Test with arbitrary numbers. Test with characters.

```<code>l     % Push 1
i     % Take input, say [4;4;2;2;9;9]
d     % Consecutive differences of input: [0;-2;0;7;0]
g     % Convert to logical: gives 1 if consecutive entries were different: [0;1;0;1;0]
v     % Concatenate vertically with the initial 1: [1;0;1;0;1;0]
Ys    % Cumulative sum. Each value is a group label: [1;1;2;2;3;3]
G     % Push input again
7XQ   % Split into horizontal arrays as indicated by group labels: {[4 4];[2 2];[9 9]}
      % Implicitly display
</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:
MATL, 9 bytes

Y'v"@Z}Y"

Y'     % Take input. Run-length encoding. Gives two row arrays: values and run lengths
v      % Concatenate vertically
"      % For each column
  @Z}  %   Push column and split into its two elements
  Y"   %   Run-length decoding
       % End for. Implicitly display

Input is a row array of numbers, with spaces or commas as separators.

Try it online! Test with non-integer numbers.

MATL, 11 bytes

lidgvYsG7XQ

Input is a column array of either numbers or characters, using ; as separator.

Try it online! Test with arbitrary numbers. Test with characters.

l     % Push 1
i     % Take input, say [4;4;2;2;9;9]
d     % Consecutive differences of input: [0;-2;0;7;0]
g     % Convert to logical: gives 1 if consecutive entries were different: [0;1;0;1;0]
v     % Concatenate vertically with the initial 1: [1;0;1;0;1;0]
Ys    % Cumulative sum. Each value is a group label: [1;1;2;2;3;3]
G     % Push input again
7XQ   % Split into horizontal arrays as indicated by group labels: {[4 4];[2 2];[9 9]}
      % Implicitly display


答:
J, 13 bytes

```<code><;.1~1,2~:/\]
</code>```

Since J does not support ragged arrays, each run of equal elements is boxed. The input is an array of values and the output is array of boxed arrays.

Usage

```<code>   f =: <;.1~1,2~:/\]
   f 4 4 2 2 9 9
┌───┬───┬───┐
│4 4│2 2│9 9│
└───┴───┴───┘
   f 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│
└─────┴───┴───┴─────┴───┴─┘
   f 'ABBBCDXYYZ'
┌─┬───┬─┬─┬─┬──┬─┐
│A│BBB│C│D│X│YY│Z│
└─┴───┴─┴─┴─┴──┴─┘
   f 0
┌─┐
│0│
└─┘
</code>```

Explanation

```<code><;.1~1,2~:/\]  Input: s
            ]  Identify function to get s
       2       The constant 2
           \   Operate on each overlapping sublist of size 2
        ~:/      Are the two values unequal, 1 if true else 0
     1,        Prepend a 1 to it
<;.1~          Using the list just made, chop s at each index equal to 1 and box it
               Return this as the result
</code>```

Title: Groups of repeating items

Body:
J, 13 bytes

<;.1~1,2~:/\]

Since J does not support ragged arrays, each run of equal elements is boxed. The input is an array of values and the output is array of boxed arrays.

Usage

   f =: <;.1~1,2~:/\]
   f 4 4 2 2 9 9
┌───┬───┬───┐
│4 4│2 2│9 9│
└───┴───┴───┘
   f 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│
└─────┴───┴───┴─────┴───┴─┘
   f 'ABBBCDXYYZ'
┌─┬───┬─┬─┬─┬──┬─┐
│A│BBB│C│D│X│YY│Z│
└─┴───┴─┴─┴─┴──┴─┘
   f 0
┌─┐
│0│
└─┘

Explanation

<;.1~1,2~:/\]  Input: s
            ]  Identify function to get s
       2       The constant 2
           \   Operate on each overlapping sublist of size 2
        ~:/      Are the two values unequal, 1 if true else 0
     1,        Prepend a 1 to it
<;.1~          Using the list just made, chop s at each index equal to 1 and box it
               Return this as the result


答:
Brachylog, 13 bytes

```<code>:{s.dl1}fs.c?
</code>```

Warning: this is extremely inefficient, and you will understand why in the explanation.

This expects a list (e.g [1:1:2:2:2]) as input. The elements inside the list can be pretty much anything.

Explanation

```<code>:{     }f       Find all ordered subsets of the Input with a unique element in them
  s.                Output is a subset of the input
    dl1             Output minus all duplicates has a length of 1 (i.e. one unique value)
         s.     Output is an ordered subset of those subsets
           c?   The concatenation of those subsets is the Input
</code>```

This works only because of the way s - Subset unifies: the smallest sets are at the end. Therefore the first thing it finds that concatenates to the Input are the longest runs, e.g. [[1:1]:[2:2:2]] and not for example [[1:1]:[2:2]:[2]].

Title: Groups of repeating items

Body:
Brachylog, 13 bytes

:{s.dl1}fs.c?

Warning: this is extremely inefficient, and you will understand why in the explanation.

This expects a list (e.g [1:1:2:2:2]) as input. The elements inside the list can be pretty much anything.

Explanation

:{     }f       Find all ordered subsets of the Input with a unique element in them
  s.                Output is a subset of the input
    dl1             Output minus all duplicates has a length of 1 (i.e. one unique value)
         s.     Output is an ordered subset of those subsets
           c?   The concatenation of those subsets is the Input

This works only because of the way s - Subset unifies: the smallest sets are at the end. Therefore the first thing it finds that concatenates to the Input are the longest runs, e.g. [[1:1]:[2:2:2]] and not for example [[1:1]:[2:2]:[2]].


答:
Retina, <s>15</s> 8 bytes

Thanks to Lynn for suggesting a simpler I/O format.

```<code>!`(.)\1*
</code>```

Treats the input as a list of characters (and uses linefeeds to separate groups).

Try it online!

This simply works by matching groups and printing them all (which uses linefeed separation automatically).

Title: Groups of repeating items

Body:
Retina, <s>15</s> 8 bytes

Thanks to Lynn for suggesting a simpler I/O format.

!`(.)\1*

Treats the input as a list of characters (and uses linefeeds to separate groups).

Try it online!

This simply works by matching groups and printing them all (which uses linefeed separation automatically).


答:
hashmap (Yes, the name starts with a lowercase letter.), 3 bytes

```<code>hh+
h   Take input
 h  Take input
  + Get the sum
</code>```

Title: Add two numbers

Body:
hashmap (Yes, the name starts with a lowercase letter.), 3 bytes

hh+
h   Take input
 h  Take input
  + Get the sum


答:
C#, 117 bytes

```<code>void f(List<String>m){Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));}
</code>```

ungolfed (not really)

```<code>    public static void f(List<String>m)
    {
        Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));
    }
</code>```

Title: Groups of repeating items

Body:
C#, 117 bytes

void f(List<String>m){Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));}

ungolfed (not really)

    public static void f(List<String>m)
    {
        Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));
    }


答:
Dyalog APL, 9 bytes

```<code>⊢⊂⍨1,2≠/⊢
</code>```

⊢ the argument

⊂⍨ partitioned at

1 at the first element

, and then

2≠/ where subsequent pairs differ

⊢ in the argument

Title: Groups of repeating items

Body:
Dyalog APL, 9 bytes

⊢⊂⍨1,2≠/⊢

⊢ the argument

⊂⍨ partitioned at

1 at the first element

, and then

2≠/ where subsequent pairs differ

⊢ in the argument


答:
Pyth, 36 35 bytes

```<code>VQIqNk=hZ).?=+Y]*]kZ=Z1=kN;t+Y]*]kZ
</code>```

Test link

Edit: explanation:

```<code>                                      standard variables: Y=[], Z=0, k='', Q=input
VQ                                    iterate over input
  IqNk                                if the current entity is equal to k:
      =hZ)                            increase Z.
          .?                          else:
               ]*]kZ                  list of length Z filled with k
            =+Y                       add it to Y
                    =Z1               set Z to 1
                       =kN            set k to the current entity
                          ;           end loop
                              ]*]kZ   list of length Z filled with k
                            +Y        add it to Y
                           t          implicitly print the tail of Y (removing the first element)
</code>```

Title: Groups of repeating items

Body:
Pyth, 36 35 bytes

VQIqNk=hZ).?=+Y]*]kZ=Z1=kN;t+Y]*]kZ

<a href="http://pyth.herokuapp.com/?code=VQIqNk%3DhZ%29.%3F%3D%2BY]*]kZ%3DZ1%3DkN%3Bt%2BY]*]kZ&input=[1%2C1%2C1%2C2%2C2%2C3%2C3%2C3%2C1]&test_suite=1&test_suite_input=[4%2C+4%2C+2%2C+2%2C+9%2C+9]%0A[1%2C+1%2C+1%2C+2%2C+2%2C+3%2C+3%2C+3%2C+4%2C+4%2C+4%2C+4]%0A[1%2C+1%2C+1%2C+3%2C+3%2C+1%2C+1%2C+2%2C+2%2C+2%2C+1%2C+1%2C+3]%0A[9%2C+7%2C+8%2C+6%2C+5]%0A[5%2C+5%2C+5]%0A[%27A%27%2C+%27B%27%2C+%27B%27%2C+%27B%27%2C+%27C%27%2C+%27D%27%2C+%27X%27%2C+%27Y%27%2C+%27Y%27%2C+%27Z%27]+%0A[0]&debug=0" rel="nofollow">Test link

Edit: explanation:

                                      standard variables: Y=[], Z=0, k='', Q=input
VQ                                    iterate over input
  IqNk                                if the current entity is equal to k:
      =hZ)                            increase Z.
          .?                          else:
               ]*]kZ                  list of length Z filled with k
            =+Y                       add it to Y
                    =Z1               set Z to 1
                       =kN            set k to the current entity
                          ;           end loop
                              ]*]kZ   list of length Z filled with k
                            +Y        add it to Y
                           t          implicitly print the tail of Y (removing the first element)


答:
Python 2, 43 bytes

p=-1
for x in input():print"|"[:x^p],x,;p=x
```
<p>Works on lists of booleans. Example:</p>
<pre class="lang-python prettyprint-override"><code>>> [True,True,False,False,False,True,False,True,False]
 True  True | False  False  False | True | False | True | False
</code>```

Iterates through the input list, storing the last seen element. A separator bar is printed before each element that is different than the previous, checked as having bitwise xor ^ of 0. Initializing p=-1 avoids a separator before the first element.

Title: Groups of repeating items

Body:
Python 2, 43 bytes

p=-1
for x in input():print"|"[:x^p],x,;p=x

Works on lists of booleans. Example:

>> [True,True,False,False,False,True,False,True,False]
 True  True | False  False  False | True | False | True | False

Iterates through the input list, storing the last seen element. A separator bar is printed before each element that is different than the previous, checked as having bitwise xor ^ of 0. Initializing p=-1 avoids a separator before the first element.


问:
"Hello, World!"
So... uh... this is a bit embarrassing. But we don't have a plain "Hello, World!" challenge yet (despite having 35 variants tagged with hello-world, and counting). While this is not the most interesting code golf in the common languages, finding the shortest solution in certain esolangs can be a serious challenge. For instance, to my knowledge it is not known whether the shortest possible Brainfuck solution has been found yet.

Furthermore, while all of <s>Wikipedia</s> (the Wikipedia entry has been deleted but there is a copy at archive.org
), esolangs and Rosetta Code have lists of "Hello, World!" programs, none of these are interested in having the shortest for each language (there is also this GitHub repository). If we want to be a significant site in the code golf community, I think we should try and create the ultimate catalogue of shortest "Hello, World!" programs (similar to how our basic quine challenge contains some of the shortest known quines in various languages). So let's do this!

The Rules

Each submission must be a full program.

The program must take no input, and print Hello, World! to STDOUT (this exact byte stream, including capitalization and punctuation) plus an optional trailing newline, and nothing else.

The program must not write anything to STDERR.

If anyone wants to abuse this by creating a language where the empty program prints Hello, World!, then congrats, they just paved the way for a very boring answer.

Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language.

Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.

This is not about finding the language with the shortest "Hello, World!" program. This is about finding the shortest "Hello, World!" program in every language. Therefore, I will not mark any answer as "accepted".

If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainfuck-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.

As a side note, please don't downvote boring (but valid) answers in languages where there is not much to golf - these are still useful to this question as it tries to compile a catalogue as complete as possible. However, do primarily upvote answers in languages where the authors actually had to put effort into golfing the code.

For inspiration, check the Hello World Collection.

The Catalogue

The Stack Snippet at the bottom of this post generates the catalogue from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](https://esolangs.org/wiki/Fish), 121 bytes
</code>```

/* Configuration */

var QUESTION_ID = 55422; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8478; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    else console.log(body);
  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    lang = jQuery(''+lang+'').text();

    languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
    if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  text-align: left !important;
  display: block !important;
}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 500px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
hashmap, 15 bytes

```<code>"Hello, World!"
</code>```

Just push Hello, World!

Title: "Hello, World!"

Body:
hashmap, 15 bytes

"Hello, World!"

Just push Hello, World!


答:
CJam, 9 bytes

Two solutions:

```<code>{e`:a:e~}
{e`{(*}%}
</code>```

Test it here.

Explanation

```<code>e`   e# Run-length encode (gives a list of pairs [run-length value]).
:a   e# Wrap each pair in a singleton list.
:e~  e# Run-length decode each list.
</code>```

Or

```<code>e`   e# Run-length encode.
{    e# Map this block over each pair...
  (  e#   Pull out the run length.
  *  e#   Repeat the list containing only the value that many times.
}%
</code>```

Title: Groups of repeating items

Body:
CJam, 9 bytes

Two solutions:

{e`:a:e~}
{e`{(*}%}

Test it here.

Explanation

e`   e# Run-length encode (gives a list of pairs [run-length value]).
:a   e# Wrap each pair in a singleton list.
:e~  e# Run-length decode each list.

Or

e`   e# Run-length encode.
{    e# Map this block over each pair...
  (  e#   Pull out the run length.
  *  e#   Repeat the list containing only the value that many times.
}%


答:
Haskell, 22 bytes

import Data.List
group
```

There's a built-in. Works on any type that supports equality.

Title: Groups of repeating items

Body:
Haskell, 22 bytes

import Data.List
group

There's a built-in. Works on any type that supports equality.