问:
At least h with at least h

Input

A list of nonnegative integers.

Output

The largest nonnegative integer h such that at least h of the numbers in the list are greater than or equal to h.

Test Cases

```<code>[0,0,0,0] -> 0
[12,312,33,12] -> 4
[1,2,3,4,5,6,7] -> 4
[22,33,1,2,4] -> 3
[1000,2,2,2] -> 2
[23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42] -> 20
</code>```

Rules

You can write either a full program or a function, and anonymous functions are allowed too. This is code-golf, so the fewest byte count wins. Standard loopholes are disallowed.

Background

The h-index is a notion used in academia which aims to capture the impact and productivity of a researcher. According to Wikipedia, a researcher has index h, if he or she has published h scientific articles, each of which has been cited in other articles at least h times. Thus, this challenge is about computing the h-index from a list of citation counts.

Update

Wow, great answers all round! I have accepted the shortest one, but if someone else comes up with an even shorter one, I'll update my choice accordingly.

Winners by language

Here's a table of winners by language that I'll also try to keep up to date. I have included all posts with nonnegative score. Please correct me if I have made a mistake here.

APL: 7 bytes by @MorisZucca

Bash + coreutils: 29 bytes by @DigitalTrauma

C#: 103 bytes by @LegionMammal978

C++: 219 bytes by @user9587

CJam: 15 bytes by @nutki

GolfScript: 13 bytes by @IlmariKaronen

Haskell: 40 bytes by @proudhaskeller

J: 12 bytes by @ɐɔıʇǝɥʇuʎs

Java: 107 bytes by @Ypnypn

JavaScript: 48 bytes by @edc65

Mathematica: 38 bytes by @kukac67

Perl: 32 bytes by @nutki

Pyth: 10 bytes by @isaacg

Python: 49 bytes by @feersum

R: 29 bytes by @MickyT

Ruby: 41 bytes by @daniero

Scala: 62 bytes by @ChadRetz

SQL: 83 bytes by @MickyT

TI-BASIC: 22 bytes by @Timtech

答:
Jelly, 6 bytes

```<code>NỤỤ<’S
</code>```

Explanation:

```<code>N           Negate (so that repeated elements won't mess up the second grade down)
 Ụ          Grade down
  Ụ         Twice.
   <’       Predicate, check for each element if the new one (after grading) is lower than original array (minus 1 on each element)
     S      Sum
</code>```

Title: At least h with at least h

Body:
Jelly, 6 bytes

NỤỤ<’S

Explanation:

N           Negate (so that repeated elements won't mess up the second grade down)
 Ụ          Grade down
  Ụ         Twice.
   <’       Predicate, check for each element if the new one (after grading) is lower than original array (minus 1 on each element)
     S      Sum


问:
Help me sort my socks!
I have a pile of clean socks that I want to sort into pairs. Unfortunately, I can only take socks from either end of the pile, not the middle. Further, I can only remove socks from the pile a matching pair at a time. My strategy is to first split the pile into one or more smaller piles. I think some examples will make this clear. I'll represent each sock as a positive integer (matching integers indicate equal socks).

If the initial pile of socks is

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

then I don't have to do any splitting. I can remove both 1 socks, then both 2 socks, then both 3 socks.

If instead the initial pile is

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

then I have to split it first because I won't be able to pair all the socks by just removing them from the end. One possibility is to split it into the two piles

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

Now I can remove the 1 socks, leaving 2 3 and 2 3, followed by the 3 socks, leaving 2 and 2, and finally the 2 socks.

Your Job

Given the initial pile of socks, write a program that will split it into smaller piles that will allow me to sort the socks. Your program should split the pile into the fewest number of piles possible (if there are multiple best solutions, you need only find one).

The input will be given as a list, delimited string, or other convenient form. It will contain only integers between 1 and some maximum value n, with each integer occurring exactly twice.

The output should consist of the input list split into smaller lists, given in any convenient form.

Examples

```<code>Input             Sample Output
1 1               1 1
1 2 1 2           1; 2 1 2
1 3 2 4 3 2 1 4   1 3 2; 4 3 2 1 4
1 2 3 4 3 4 1 2   1; 2 3; 4 3 4 1 2
1 1 2 2 3 3       1 1 2; 2 3 3
4 3 4 2 2 1 1 3   4 3 4 2; 2 1 1 3
</code>```

Note that this isn't the only allowed output for most of these inputs. For the second case, for example, the outputs 1 2; 1 2 or 1 2 1; 2 would also be accepted.

Thanks to Sp3000 for some test suggestions!

I hate spending a long time sorting my clothes, so make your code as short as possible. Shortest answer in bytes wins!

Notes

I don't want to have to look behind a sock to see if its matching pair is there, so taking both socks in a pair from the same end is not allowed. E.g. if the pile is 1 1 2 2 then you wouldn't be able to leave it as one pile and take both 1 socks from the left end.

答:
JavaScript (ES6), 329

Not an easy task for a language that has no combinatorics builtins.

Probably sligthly more golfable.

Note: all partition are at least of size 2, as a partition with a single element is always less useful.

```<code>Example: [1] [2 3 4] // can take 1 or 2 or 4
Better: [1 2] [3 4] // can take 3 too
</code>```

a=>{G=(v,i,u=v)=>{if(i--){for(;r[i]=--u;)if(G(u,i))return 1;}else for(w=[...r,n=l].map((x,i)=>a.slice(z,z=x-~i),z=0),y=w.join`;`;w.map(b=>[0,1].map(q=>(x=b[q*=~-b.length])&&(t[x]?([c,p]=t[x],n-=2,p?c.pop():c.shift(),q?b.pop():b.shift()):t[x]=[b,q])),c=0,t=[]),c;)if(!n)return 1};for(l=a.length,r=[],k=0;!G(l-k-1,k);k++);return y}
```

<p><strong>Explanation in parts</strong></p>

<p>(it's overly verbose, but I found it tough to explain - eventually skip to "put it all together")</p>

<p>A recursive function to enumerate all possible splits of an array</p>

<pre class="lang-js prettyprint-override"><code>// v: array length
// i number of splits
// fill the global array r that must exists
G=(v,i,u=v)=>
{
  if(i--)
  {
    for(;r[i]=--u;)
      G(u,i)
  }
  else
  {
    // the current split position are in r, ready to use
    // for instance...
    parts = [...r,a.length].map(x=>a.slice(z,z=x),z=0)
    console.log(r, parts)
  }
};

r=[]
a=['A','B','C','D']
G(4, 2)

// output in console (firebug)
[2, 3] [["A", "B"], ["C"], ["D"]]
[1, 3] [["A"], ["B", "C"], ["D"]]
[1, 2] [["A"], ["B"], ["C", "D"]]
</code>```

Now, I need partitions of size 2 or more, so I must use this function with sligtly different parameters. The parameter v is "array size - number of desired partitions - 1". Then I must build the partitions in a slightly different way.

// Same call (4,2), same r, but the array b is of size 7
part = [...r,b.length].map((x,i)=>
          b.slice(z,z=x+i+1) // add 1 more element to each partition
       ,z=0))
// output in console (firebug)
[2, 3] [["A", "B", "C"], ["D", "E"], ["F", "G"]]
[1, 3] [["A", "B"], ["C", "D", "E"], ["F", "G"]]
[1, 2] [["A", "B"], ["C", "D"], ["E", "F", "G"]]
```

<p>So, I can enumerate the list of partitions for no split, 1 split, 2 splits and so on. When I find a working partition I will stop and output the result found.  </p>

<p>To check, scan the partition list, note the values at start and end of each, if found a repated value then remove it. Repeat until nothing can be removed, at last: if all pairs were removed then this partition is good.</p>

<pre class="lang-js prettyprint-override"><code>t = []; // array to note the repeated values
// t[x] == [
//           subarray holding value x,
//           position of value x (I care zero or nonzero)
//         ]
n = a.length // counter start, must reach 0
// remember part just in case, because this check will destroy it
result = part.join(';') // a string representation for return value
do
{
  // in the golfed code there is a forr loop
  // all this body is inside the for condition
  c = 0; // init c to a falsy, if a pair is found c becomes truthy
  part.forEach(b=> // b: array, current partition
    [0,1].forEach(q=> ( // exec for 0 (start), 1 (end)
      q *= b.length-1, // now q is the correct index
      x = b[q]) // x is the value at start or end
      x && ( // b could be empty, check that x is not 'undefined'
        t[x] ? // is there a value in t at position x?
           ( // yes, remove the pair
             n-=2, // pair found, decrement counter
             [c, p] = t[x], // get stored array and position
             p ? c.pop() : c.shift(), // remove from c at start or end
             q ? b.pop() : b.shift()  // remove twin value from b
           )
           : // no, remember the value in t
             t[x] = [b, q]
    )) // end [0,1].forEach
  ) // end part.forEach
}
while (c) // repeat until nothing can be removed
if(!n) return 1 // wow, result found (in 'result' variable)
</code>```

Then, the missing part is just a loop caling the G function increasing the partition count. The loop exit when a result is found.

Put it all together

F=a=>{
  G=(v,i,u=v)=>{
    if (i--)
    {
      for(; r[i]=--u; )
        if (G(u,i))
          return 1;
    }
    else
    {
      w = [...r,n=l].map((x,i)=>a.slice(z, z = x-~i), z = 0);
      y = w.join`;`;
      for(; // almost all the for body is inside the condition
        w.map(b=>
          [0,1].map(q=>
            (x=b[q*=~-b.length])
             &&(t[x]
                ?([c,p]=t[x],n-=2,
                   p?c.pop():c.shift(),
                   q?b.pop():b.shift())
                :t[x]=[b,q])) // end [0,1].map
          ,c=0,t=[] // init variables for w.map
        ),c; // the loop condition is on c
      )
        if(!n)return 1 // this is the for body
    }
  };
  for(l = a.length, r = [], k = 0; !G(l-k-1, k); k++);
  return y
}
```

<p><strong>Test</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>F=a=>{G=(v,i,u=v)=>{if(i--){for(;r[i]=--u;)if(G(u,i))return 1;}else for(w=[...r,n=l].map((x,i)=>a.slice(z,z=x-~i),z=0),y=w.join`;`;w.map(b=>[0,1].map(q=>(x=b[q*=~-b.length])&&(t[x]?([c,p]=t[x],n-=2,p?c.pop():c.shift(),q?b.pop():b.shift()):t[x]=[b,q])),c=0,t=[]),c;)if(!n)return 1};for(l=a.length,r=[],k=0;!G(l-k-1,k);k++);return y}

console.log=x=>O.textContent+=x+'\n'

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

TestData.forEach(t=>console.log(t+' -> '+F(t)))

function RandomTest() {
  var l=I.value*2
  var a=[...Array(l)].map((_,i)=>1+i/2|0)
  a.map((v,i)=>a[a[i]=a[j=0|i+Math.random()*(a.length-i)],j]=v) // shuffle
  Q.textContent=a+''+'\n\n'+F(a).replace(/;/g, ';\n') // better readability
}</code>```

Base test

```
Random test. Number of pairs: <input id=I value=15><button onclick="RandomTest()">-></button>
<pre id=Q>``````

ContentLicense: CC BY-SA 3.0

Title: Help me sort my socks!

Body:
JavaScript (ES6), 329

Not an easy task for a language that has no combinatorics builtins.

Probably sligthly more golfable.

Note: all partition are at least of size 2, as a partition with a single element is always less useful.

Example: [1] [2 3 4] // can take 1 or 2 or 4
Better: [1 2] [3 4] // can take 3 too

a=>{G=(v,i,u=v)=>{if(i--){for(;r[i]=--u;)if(G(u,i))return 1;}else for(w=[...r,n=l].map((x,i)=>a.slice(z,z=x-~i),z=0),y=w.join`;`;w.map(b=>[0,1].map(q=>(x=b[q*=~-b.length])&&(t[x]?([c,p]=t[x],n-=2,p?c.pop():c.shift(),q?b.pop():b.shift()):t[x]=[b,q])),c=0,t=[]),c;)if(!n)return 1};for(l=a.length,r=[],k=0;!G(l-k-1,k);k++);return y}

Explanation in parts

(it's overly verbose, but I found it tough to explain - eventually skip to "put it all together")

A recursive function to enumerate all possible splits of an array

// v: array length
// i number of splits
// fill the global array r that must exists
G=(v,i,u=v)=>
{
  if(i--)
  {
    for(;r[i]=--u;)
      G(u,i)
  }
  else
  {
    // the current split position are in r, ready to use
    // for instance...
    parts = [...r,a.length].map(x=>a.slice(z,z=x),z=0)
    console.log(r, parts)
  }
};

r=[]
a=['A','B','C','D']
G(4, 2)

// output in console (firebug)
[2, 3] [["A", "B"], ["C"], ["D"]]
[1, 3] [["A"], ["B", "C"], ["D"]]
[1, 2] [["A"], ["B"], ["C", "D"]]

Now, I need partitions of size 2 or more, so I must use this function with sligtly different parameters. The parameter v is "array size - number of desired partitions - 1". Then I must build the partitions in a slightly different way.

// Same call (4,2), same r, but the array b is of size 7
part = [...r,b.length].map((x,i)=>
          b.slice(z,z=x+i+1) // add 1 more element to each partition
       ,z=0))
// output in console (firebug)
[2, 3] [["A", "B", "C"], ["D", "E"], ["F", "G"]]
[1, 3] [["A", "B"], ["C", "D", "E"], ["F", "G"]]
[1, 2] [["A", "B"], ["C", "D"], ["E", "F", "G"]]

So, I can enumerate the list of partitions for no split, 1 split, 2 splits and so on. When I find a working partition I will stop and output the result found.

To check, scan the partition list, note the values at start and end of each, if found a repated value then remove it. Repeat until nothing can be removed, at last: if all pairs were removed then this partition is good.

t = []; // array to note the repeated values
// t[x] == [
//           subarray holding value x,
//           position of value x (I care zero or nonzero)
//         ]
n = a.length // counter start, must reach 0
// remember part just in case, because this check will destroy it
result = part.join(';') // a string representation for return value
do
{
  // in the golfed code there is a forr loop
  // all this body is inside the for condition
  c = 0; // init c to a falsy, if a pair is found c becomes truthy
  part.forEach(b=> // b: array, current partition
    [0,1].forEach(q=> ( // exec for 0 (start), 1 (end)
      q *= b.length-1, // now q is the correct index
      x = b[q]) // x is the value at start or end
      x && ( // b could be empty, check that x is not 'undefined'
        t[x] ? // is there a value in t at position x?
           ( // yes, remove the pair
             n-=2, // pair found, decrement counter
             [c, p] = t[x], // get stored array and position
             p ? c.pop() : c.shift(), // remove from c at start or end
             q ? b.pop() : b.shift()  // remove twin value from b
           )
           : // no, remember the value in t
             t[x] = [b, q]
    )) // end [0,1].forEach
  ) // end part.forEach
}
while (c) // repeat until nothing can be removed
if(!n) return 1 // wow, result found (in 'result' variable)

Then, the missing part is just a loop caling the G function increasing the partition count. The loop exit when a result is found.

Put it all together

F=a=>{
  G=(v,i,u=v)=>{
    if (i--)
    {
      for(; r[i]=--u; )
        if (G(u,i))
          return 1;
    }
    else
    {
      w = [...r,n=l].map((x,i)=>a.slice(z, z = x-~i), z = 0);
      y = w.join`;`;
      for(; // almost all the for body is inside the condition
        w.map(b=>
          [0,1].map(q=>
            (x=b[q*=~-b.length])
             &&(t[x]
                ?([c,p]=t[x],n-=2,
                   p?c.pop():c.shift(),
                   q?b.pop():b.shift())
                :t[x]=[b,q])) // end [0,1].map
          ,c=0,t=[] // init variables for w.map
        ),c; // the loop condition is on c
      )
        if(!n)return 1 // this is the for body
    }
  };
  for(l = a.length, r = [], k = 0; !G(l-k-1, k); k++);
  return y
}

Test

F=a=>{G=(v,i,u=v)=>{if(i--){for(;r[i]=--u;)if(G(u,i))return 1;}else for(w=[...r,n=l].map((x,i)=>a.slice(z,z=x-~i),z=0),y=w.join`;`;w.map(b=>[0,1].map(q=>(x=b[q*=~-b.length])&&(t[x]?([c,p]=t[x],n-=2,p?c.pop():c.shift(),q?b.pop():b.shift()):t[x]=[b,q])),c=0,t=[]),c;)if(!n)return 1};for(l=a.length,r=[],k=0;!G(l-k-1,k);k++);return y}

console.log=x=>O.textContent+=x+'\n'

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

TestData.forEach(t=>console.log(t+' -> '+F(t)))

function RandomTest() {
  var l=I.value*2
  var a=[...Array(l)].map((_,i)=>1+i/2|0)
  a.map((v,i)=>a[a[i]=a[j=0|i+Math.random()*(a.length-i)],j]=v) // shuffle
  Q.textContent=a+''+'\n\n'+F(a).replace(/;/g, ';\n') // better readability
}

Base test
<pre id=O></pre>
Random test. Number of pairs: <input id=I value=15><button onclick="RandomTest()">-></button>
<pre id=Q></pre>


问:
Stretch the word
The input is a word of lowercase letters not separated by whitespace. A newline at the end is optional.

The same word must be output in a modified version: For each character, double it the second time it appears in the original word, triple it the third time etc.

Example input:

```<code>bonobo
</code>```

Example output:

```<code>bonoobbooo
</code>```

Standard I/O rules apply. The shortest code in bytes wins.

Tests provided by @Neil :

```<code>tutu -> tuttuu
queue -> queuuee
bookkeeper -> boookkkeeepeeer
repetitive -> repeetittiiveee
uncopyrightables -> uncopyrightables
abracadabra -> abraacaaadaaaabbrraaaaa
mississippi -> misssiisssssssiiipppiiii
</code>```

答:
CJam, 14

```<code>q:A,{)A<_)--}/
</code>```

Try it online

Explanation:

```<code>q:A      read the input and store in A
,        get the string length
{…}/     for each number from 0 to length-1
  )      increment the number
  A<     get the prefix of A with that length
  _      duplicate it
  )      separate the last character
  -      remove it from the rest of the prefix
  -      remove all the remaining characters (different from the last one)
          from the prefix
</code>```

Title: Stretch the word

Body:
CJam, 14

q:A,{)A<_)--}/

Try it online

Explanation:

q:A      read the input and store in A
,        get the string length
{…}/     for each number from 0 to length-1
  )      increment the number
  A<     get the prefix of A with that length
  _      duplicate it
  )      separate the last character
  -      remove it from the rest of the prefix
  -      remove all the remaining characters (different from the last one)
          from the prefix


答:
J, 11 bytes

```<code>#~+/@(={:)\
</code>```

This is a monadic verb. Try it here. Usage:

```<code>   f =: #~+/@(={:)\
   f 'tutu'
'tuttuu'
</code>```

Explanation

```<code>#~+/@(={:)\
     (   )\  For each non-empty prefix:
       {:      Take last element,
      =        compare for equality to the others and itself
  +/@          and take sum (number of matches).
#~           Replicate original elements wrt the resulting array.
</code>```

Title: Stretch the word

Body:
The input is a word of lowercase letters not separated by whitespace. A newline at the end is optional.

The same word must be output in a modified version: For each character, double it the second time it appears in the original word, triple it the third time etc.

Example input:

```<code>bonobo
</code>```

Example output:

```<code>bonoobbooo
</code>```

Standard I/O rules apply. The shortest code in bytes wins.

Tests provided by @Neil :

```<code>tutu -> tuttuu
queue -> queuuee
bookkeeper -> boookkkeeepeeer
repetitive -> repeetittiiveee
uncopyrightables -> uncopyrightables
abracadabra -> abraacaaadaaaabbrraaaaa
mississippi -> misssiisssssssiiipppiiii
</code>```

Body:
J, 11 bytes

#~+/@(={:)\

This is a monadic verb. Try it here. Usage:

   f =: #~+/@(={:)\
   f 'tutu'
'tuttuu'

Explanation

#~+/@(={:)\
     (   )\  For each non-empty prefix:
       {:      Take last element,
      =        compare for equality to the others and itself
  +/@          and take sum (number of matches).
#~           Replicate original elements wrt the resulting array.


答:
Haskell, 39 bytes

```<code>f""=""
f x=f(init x)++filter(==last x)x
</code>```

Usage example: f "bonobo" -> "bonoobbooo".

Different enough from @Damien's answer. Builds the string from the right by extracting all occurrences of the last character from the string and prepending a recursive call with all but the last character.

Title: Stretch the word

Body:
Haskell, 39 bytes

f""=""
f x=f(init x)++filter(==last x)x

Usage example: f "bonobo" -> "bonoobbooo".

Different enough from @Damien's answer. Builds the string from the right by extracting all occurrences of the last character from the string and prepending a recursive call with all but the last character.


答:
Rust, 176 Bytes

fn s(w:&str)->String{let mut m=std::collections::HashMap::new();w.chars().map(|c|{let mut s=m.remove(&c).unwrap_or(String::new());s.push(c);m.insert(c,s.clone());s}).collect()}
```

This uses a map to store a string for every character in the input. For each character, the string will be removed from the map, concatenated with the character, inserted back into the map and appended to the output.

I would have liked to use get(...) instead of remove(...), but the borrow checker had me change my mind.

Title: Stretch the word

Body:
Rust, 176 Bytes

fn s(w:&str)->String{let mut m=std::collections::HashMap::new();w.chars().map(|c|{let mut s=m.remove(&c).unwrap_or(String::new());s.push(c);m.insert(c,s.clone());s}).collect()}

This uses a map to store a string for every character in the input. For each character, the string will be removed from the map, concatenated with the character, inserted back into the map and appended to the output.

I would have liked to use get(...) instead of remove(...), but the borrow checker had me change my mind.


问:
The plus-minus sequence

The plus-minus sequence

The plus-minus sequence is one that starts with two seeds, a(0) and b(0). Each iteration of this sequence is the addition and subtraction of the previous two members of the sequence. That is, a(N) = a(N-1) + b(N-1) and b(N) = a(N-1) - b(N-1).

Objective Produce the plus-minus sequence, in infinitude or the first K steps given K. You may do this using an infinite output program, a generator, or a function/program that gives the first K steps. The output order does not matter, so long as it is consistent. (I.e., b(K) a(K) or a(K) b(K), with some non-numeric, non-newline separator in between.) The output must start with the input.

Test cases

For inputs 10 2 (of a(0) b(0), this is a possible output for the first K approach (or a subsection of the infinite approach):

```<code>10     2
12     8
20     4
24     16
40     8
48     32
80     16
96     64
160    32
192    128
320    64
384    256
640    128
768    512
1280   256
1536   1024
2560   512
3072   2048
5120   1024
6144   4096
10240  2048
12288  8192
20480  4096
24576  16384
40960  8192
49152  32768
81920  16384
98304  65536
</code>```

For inputs 2 20 10 (a(0) b(0) k):

```<code>2     20
22   -18
4     40
44   -36
8     80
88   -72
16    160
176  -144
32    320
352  -288
</code>```

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

Catalog

The Stack Snippet at the bottom of this post generates the catalog 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>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
CP/M 8080, 47 bytes

z80 mnemonics but nothing the 8080 doesn't have, source commented once I decided to count the output rather than the input but terse function names retained, hand assembled so forgive the 'xx's where I know the number of bytes but haven't worked out the output addresses or offsets:

```<code># setup
ld c, 2     0e 02

# loop
.s

# update H (temporarily in B)
ld a, h     7c
add l       85
daa         27
ld b, a     46

# update L
ld a, h     7c
sub l       95
daa         27
ld l, a     6f

# copy B back to H, output H
ld h, b     60
call +o     cd xx xx

# output L
ld b, l     45
call +o     cd xx xx

# repeat
jr -s       18 xx

# output a two-digit BCD value followed by a space
.o

# output high digit
ld a, b     78
rra         1f
rra         1f
rra         1f
rra         1f
call +ob    cd xx xx

# output low digit
ld a, b     78
call +ob    cd xx xx

# output a space
ld e, #$20  1e 20
call 5      cd 00 05

# return
ret         c9

# output a single BCD digit
.ob
and #$f     e6 0f
add #$30    c6 30
ld e, a     5f
call 5      cd 00 05
ret         c9
</code>```

ContentLicense: CC BY-SA 4.0

Title: The plus-minus sequence

Body:
CP/M 8080, 47 bytes

z80 mnemonics but nothing the 8080 doesn't have, source commented once I decided to count the output rather than the input but terse function names retained, hand assembled so forgive the 'xx's where I know the number of bytes but haven't worked out the output addresses or offsets:

# setup
ld c, 2     0e 02

# loop
.s

# update H (temporarily in B)
ld a, h     7c
add l       85
daa         27
ld b, a     46

# update L
ld a, h     7c
sub l       95
daa         27
ld l, a     6f

# copy B back to H, output H
ld h, b     60
call +o     cd xx xx

# output L
ld b, l     45
call +o     cd xx xx

# repeat
jr -s       18 xx

# output a two-digit BCD value followed by a space
.o

# output high digit
ld a, b     78
rra         1f
rra         1f
rra         1f
rra         1f
call +ob    cd xx xx

# output low digit
ld a, b     78
call +ob    cd xx xx

# output a space
ld e, #$20  1e 20
call 5      cd 00 05

# return
ret         c9

# output a single BCD digit
.ob
and #$f     e6 0f
add #$30    c6 30
ld e, a     5f
call 5      cd 00 05
ret         c9


答:
awk, 72 bytes

```<code>BEGIN{FS=""}{for(i=1;i<=NF;i++){a[$i]++;for(j=0;j<a[$i];j++)printf $i}}
</code>```

The idea is to store the count of the appearing character in an associative array and print the character this count times.

Title: Stretch the word

Body:
awk, 72 bytes

BEGIN{FS=""}{for(i=1;i<=NF;i++){a[$i]++;for(j=0;j<a[$i];j++)printf $i}}

The idea is to store the count of the appearing character in an associative array and print the character this count times.


问:
Open the browser to http://codegolf.stackexchange.com
Your job is to open a browser window of the default browser to http://codegolf.stackexchange.com.

Your code must open the browser itself, and cannot rely on an open one.

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

Moderator note: A large number of answers to this challenge use the URLs http://ppcg.lol or http://ppcg.ga. These URLs did direct to https://codegolf.stackexchange.com at the time, but have since expired. By this meta discussion, they have been allowed to stay, with the note that they are currently invalid.

答:
Common Lisp,  31 bytes

```<code>(ext:shell "open http:ppcg.ga")
</code>```

Note: This worked at the time of writing.  The domain ppcg.ga has since expired, making this answer no longer valid.

Body:
Common Lisp,  31 bytes

(ext:shell "open http:ppcg.ga")

Note: This worked at the time of writing.  The domain ppcg.ga has since expired, making this answer no longer valid.


答:
Clojure, 44 bytes

```<code>#(iterate(fn[[a b]][(+ a b)(- a b)])[%1 %2])
</code>```

Function that produces an infinite lazy sequence.

Title: The plus-minus sequence

Body:
The plus-minus sequence

The plus-minus sequence is one that starts with two seeds, a(0) and b(0). Each iteration of this sequence is the addition and subtraction of the previous two members of the sequence. That is, a(N) = a(N-1) + b(N-1) and b(N) = a(N-1) - b(N-1).

Objective Produce the plus-minus sequence, in infinitude or the first K steps given K. You may do this using an infinite output program, a generator, or a function/program that gives the first K steps. The output order does not matter, so long as it is consistent. (I.e., b(K) a(K) or a(K) b(K), with some non-numeric, non-newline separator in between.) The output must start with the input.

Test cases

For inputs 10 2 (of a(0) b(0), this is a possible output for the first K approach (or a subsection of the infinite approach):

```<code>10     2
12     8
20     4
24     16
40     8
48     32
80     16
96     64
160    32
192    128
320    64
384    256
640    128
768    512
1280   256
1536   1024
2560   512
3072   2048
5120   1024
6144   4096
10240  2048
12288  8192
20480  4096
24576  16384
40960  8192
49152  32768
81920  16384
98304  65536
</code>```

For inputs 2 20 10 (a(0) b(0) k):

```<code>2     20
22   -18
4     40
44   -36
8     80
88   -72
16    160
176  -144
32    320
352  -288
</code>```

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

Catalog

The Stack Snippet at the bottom of this post generates the catalog 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>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
Clojure, 44 bytes

#(iterate(fn[[a b]][(+ a b)(- a b)])[%1 %2])

Function that produces an infinite lazy sequence.


问:
Fibonacci’s sexagesimals
Leonardo da Pisano a.k.a Fibonacci was instrumental in bringing the Hindu-Arabic numeral system into Europe. Before that, mathematicians there worked in base sixty with Roman numerals.

For example, the square root of two might be approximated as: one and twenty-four parts of sixty and fifty-one parts of three-thousand-six-hundred, and written as: i xxiv li, with the scaling determined by context. At the time, “nothingness” was known (i.e. zero), but had no standard representation in this number system.

Had Fibonacci ignored these new-fangled decimal digits he encountered during his travels, he surely would have addressed the deficiencies in the current system. This improved system we'll call Fibonacci’s sexagesimals.

Your task is to write a program, function or code snippet which takes a floating point number in ASCII or binary format and outputs in base sixty Roman numerals. The input can be file, console, command line or function argument and output can be file or console, whichever is easiest.

The output can be upper or lower case, and must include these improvements:

use n or N to indicate null meaning a place has no value, i.e. “zero” (a problem with the system)

use e or E to indicate et corresponding to the sexagesimal point (another problem with the system)

use a middle dot · or an asterisk * to separate groups of Roman numerals (yet another problem with the system)

Assume the input will be floating point with mantissa not greater than lix·lix·lix·lix·lix. Fractions less than n·e·n·n·n·n·i can be ignored. So, provided the input has these restrictions, at most ten groups of Roman numerals with one e can be outputted.

Numbers less than i must have a leading n·e to ensure the context is clear.

Some examples: input → output

0 → n

1 → i

60 → i·n

0.1 → n·e·vi

3600 → i·n·n

10.5 → x·e·xxx

16777215 → i·xvii·xl·xx·xv

3.1415926536 → iii·e·viii·xxix·xliv·n·xlvii

The output must avoid unnecessary leading n· in the mantissa part, isolated e, or trailing ·n in the fractional part of the output. So for example, n·n·n·n·i, i·e, and i·e·n·n·n·n·n are incorrect outputs for an input of 1.

Differences of plus or minus n·e·n·n·n·n·i in the output are within tolerances and acceptable.

The input is any legal floating point in the language of your choice, so can include positive or negative exponents as long as the input doesn't fall outside the range specified above.

And finally, Roman numeral built-ins are allowed!

答:
Python 3, <s>323</s> <s>319</s> 320 bytes

This answer implements Fibonacci's sexagesimals with the delimiter * and without regard for Kolmogorov complexity in the lists of Roman numerals (for now, at least). Attempts were made to join the while and for loop under which the Roman numerals are generated under one loop, but those attempts have not yet met with success. Any golfing tips and suggestions are welcome and appreciated.

Edit: Bug fixing and golfing.

Edit: More bug fixing.

def f(x):
 v=divmod;f=x%1;n=int(x);d=",I,II,III,IV,V,VI,VII,VIII,IX".split(",");t=",X,XX,XXX,XL,L".split(",");z=["N"];a=f>0;s=z*0**n+["E"]*a
 while n:n,m=v(n,60);j,k=v(m,10);s=[z,[t[j]+d[k]]][m>0]+s
 for i in range(5*a):m,f=v(f*60,1);j,k=v(int(m),10);s+=[z,[t[j]+d[k]]][m>0]
 while s[-1:]==z*a:s.pop()
 return"*".join(s)
```

<p><strong>Ungolfed:</strong></p>

<pre class="lang-python prettyprint-override"><code>def f(x):
    integ = int(x)
    frac = x % 1
    units=",I,II,III,IV,V,VI,VII,VIII,IX".split(",")
    tens=",X,XX,XXX,XL,L".split(",")
    zero = ["N"]
    output = []
    a = frac != 0
    if integ == 0:
        output += z
    if a:
        output += ["E"]
    while integ > 0:
        integ, digit = divmod(integ, 60)
        j, k = divmod(int(digit), 10)
        if digit:
            output += [tens[j], units[k]]
        else:
            output += zero
    for i in range(5*a):
        digit, frac = divmod(frac*60, 1)
        j, k = divmod(int(digit), 10)
        if digit:
            output += [tens[j], units[k]]
        else:
            output += zero
    while output[-1:] == zero * a:
        output.pop()
    return "*".join(output)
</code>```

Title: Fibonacci’s sexagesimals

Body:
Python 3, <s>323</s> <s>319</s> 320 bytes

This answer implements Fibonacci's sexagesimals with the delimiter * and without regard for Kolmogorov complexity in the lists of Roman numerals (for now, at least). Attempts were made to join the while and for loop under which the Roman numerals are generated under one loop, but those attempts have not yet met with success. Any golfing tips and suggestions are welcome and appreciated.

Edit: Bug fixing and golfing.

Edit: More bug fixing.

def f(x):
 v=divmod;f=x%1;n=int(x);d=",I,II,III,IV,V,VI,VII,VIII,IX".split(",");t=",X,XX,XXX,XL,L".split(",");z=["N"];a=f>0;s=z*0**n+["E"]*a
 while n:n,m=v(n,60);j,k=v(m,10);s=[z,[t[j]+d[k]]][m>0]+s
 for i in range(5*a):m,f=v(f*60,1);j,k=v(int(m),10);s+=[z,[t[j]+d[k]]][m>0]
 while s[-1:]==z*a:s.pop()
 return"*".join(s)

Ungolfed:

def f(x):
    integ = int(x)
    frac = x % 1
    units=",I,II,III,IV,V,VI,VII,VIII,IX".split(",")
    tens=",X,XX,XXX,XL,L".split(",")
    zero = ["N"]
    output = []
    a = frac != 0
    if integ == 0:
        output += z
    if a:
        output += ["E"]
    while integ > 0:
        integ, digit = divmod(integ, 60)
        j, k = divmod(int(digit), 10)
        if digit:
            output += [tens[j], units[k]]
        else:
            output += zero
    for i in range(5*a):
        digit, frac = divmod(frac*60, 1)
        j, k = divmod(int(digit), 10)
        if digit:
            output += [tens[j], units[k]]
        else:
            output += zero
    while output[-1:] == zero * a:
        output.pop()
    return "*".join(output)


答:
Python, <s>66</s> 62 bytes

Try it here

Golfed

```<code>def s(w,o=[],n=""):
 for x in w:o+=x;n+=x*o.count(x)
 return n
</code>```

Ungolfed

```<code>def stretch(word):
    occurrences = []
    newWord = ""
    for w in word:
        occurrences.append(w)
        newWord += w * occurrences.count(w)
    return newWord
</code>```

Title: Stretch the word

Body:
Python, <s>66</s> 62 bytes

Try it here

Golfed

def s(w,o=[],n=""):
 for x in w:o+=x;n+=x*o.count(x)
 return n

Ungolfed

def stretch(word):
    occurrences = []
    newWord = ""
    for w in word:
        occurrences.append(w)
        newWord += w * occurrences.count(w)
    return newWord


问:
Shortest code for infinite disk I/O
(Just open 50 tabs in Google Chrome :D (just kidding, no you can't))

Shortest code for infinite disk I/O any language, C# example:

using System.IO;

namespace FileApp {
    static class Program {
        public static void Main() {
            do {
                File.WriteAllText("a", "a");
                File.Delete("a");
            } while (true);
        }
    }
}
```

You can't just fill the entire disk though, as then it would halt in the end and would be finite.

And you can't do reading only, infinite writing has to happen. (It has to kill my SSD after enough runtime.)

Get cracking! :)

答:
DOS/Batch: 4 bytes

```<code>%0>x
</code>```

This batch file will call itself (%0) and redirect (>) the output to a file called x. Since echo is on by default, this will output the path and command.

Title: Shortest code for infinite disk I/O

Body:
DOS/Batch: 4 bytes

%0>x

This batch file will call itself (%0) and redirect (>) the output to a file called x. Since echo is on by default, this will output the path and command.


答:
Pyth, 25 bytes

```<code>hf!u #-R.-F{BhMs_BMGGT)./
</code>```

Test suite

Explanation:

```<code>hf!u #-R.-F{BhMs_BMGGT)./
                       ./    Form all partitions (implicitly) of the input.
 f                           Filter the permutations on
   u                 T)      Run the following function on the partition
                             until it reaches a fixed point:
                _BMG         Bifurcate the lists on reversal
               s             Concatenate
             hM              Take the first element of each list.
                             These elements are all the ones on the ends of lists.
           {B                Bifurcate on deduplication
        .-F                  Bagwise subtraction.
                             Only elements repeated in ends of lists remain.
      -R            G        Remove these elements from each list.
   ' #'                      Filter out empty lists.
  !                          Negate. Only an empty list as fixed point succeeds.
h                            Output the first successful partition.
</code>```

Title: Help me sort my socks!

Body:
I have a pile of clean socks that I want to sort into pairs. Unfortunately, I can only take socks from either end of the pile, not the middle. Further, I can only remove socks from the pile a matching pair at a time. My strategy is to first split the pile into one or more smaller piles. I think some examples will make this clear. I'll represent each sock as a positive integer (matching integers indicate equal socks).

If the initial pile of socks is

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

then I don't have to do any splitting. I can remove both 1 socks, then both 2 socks, then both 3 socks.

If instead the initial pile is

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

then I have to split it first because I won't be able to pair all the socks by just removing them from the end. One possibility is to split it into the two piles

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

Now I can remove the 1 socks, leaving 2 3 and 2 3, followed by the 3 socks, leaving 2 and 2, and finally the 2 socks.

Your Job

Given the initial pile of socks, write a program that will split it into smaller piles that will allow me to sort the socks. Your program should split the pile into the fewest number of piles possible (if there are multiple best solutions, you need only find one).

The input will be given as a list, delimited string, or other convenient form. It will contain only integers between 1 and some maximum value n, with each integer occurring exactly twice.

The output should consist of the input list split into smaller lists, given in any convenient form.

Examples

```<code>Input             Sample Output
1 1               1 1
1 2 1 2           1; 2 1 2
1 3 2 4 3 2 1 4   1 3 2; 4 3 2 1 4
1 2 3 4 3 4 1 2   1; 2 3; 4 3 4 1 2
1 1 2 2 3 3       1 1 2; 2 3 3
4 3 4 2 2 1 1 3   4 3 4 2; 2 1 1 3
</code>```

Note that this isn't the only allowed output for most of these inputs. For the second case, for example, the outputs 1 2; 1 2 or 1 2 1; 2 would also be accepted.

Thanks to Sp3000 for some test suggestions!

I hate spending a long time sorting my clothes, so make your code as short as possible. Shortest answer in bytes wins!

Notes

I don't want to have to look behind a sock to see if its matching pair is there, so taking both socks in a pair from the same end is not allowed. E.g. if the pile is 1 1 2 2 then you wouldn't be able to leave it as one pile and take both 1 socks from the left end.

Body:
Pyth, 25 bytes

hf!u #-R.-F{BhMs_BMGGT)./

Test suite

Explanation:

hf!u #-R.-F{BhMs_BMGGT)./
                       ./    Form all partitions (implicitly) of the input.
 f                           Filter the permutations on
   u                 T)      Run the following function on the partition
                             until it reaches a fixed point:
                _BMG         Bifurcate the lists on reversal
               s             Concatenate
             hM              Take the first element of each list.
                             These elements are all the ones on the ends of lists.
           {B                Bifurcate on deduplication
        .-F                  Bagwise subtraction.
                             Only elements repeated in ends of lists remain.
      -R            G        Remove these elements from each list.
   ' #'                      Filter out empty lists.
  !                          Negate. Only an empty list as fixed point succeeds.
h                            Output the first successful partition.


问:
Print N Squared
Write a program or function that takes in a non-negative integer N from stdin or as a function argument. It must print or return a string of a hollow ASCII-art square whose sides are each made with N copies of the number N.

Specifically:

If N is 0, no copies of N are used, so there should be no output (or only a single trailing newline).

If N is 1, the output is:

```<code>1
</code>```

If N is 2:

```<code>22
22
</code>```

If N is 3:

```<code>333
3 3
333
</code>```

If N is 4:

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

If N is 5:

```<code>55555
5   5
5   5
5   5
55555
</code>```

The pattern continues for 6 through 9.

If N is 10, the output is:

```<code>10101010101010101010
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10                10
10101010101010101010
</code>```

Notice that this is not actually square. It is 10 rows tall but 20 columns wide because 10 is two characters long. This is intended. The point is that each side of the "square" contains N copies of N. So all inputs beyond 9 will technically be ASCII rectangles.

For example, if N is 23, the output is:

```<code>2323232323232323232323232323232323232323232323
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
23                                          23
2323232323232323232323232323232323232323232323</code>```

Here are Pastebins of the required outputs for 99, 100, 111, and 123 (they may look wrong in a browser but in a text editor they'll look correct). The output for 1000 is to large for Pastebin but it would have 1000 rows and 4000 columns. Numbers with 4 or more digits must work just like smaller numbers.

Details:

N must be written in the usual decimal number representation, with no + sign or other non-digits.

The hollow area must only be filled with spaces.

No lines should have leading or trailing spaces.

A single newline after the squares' last line is optionally allowed.

Languages written after this challenge was made are welcome, they just aren't eligible to win.

The shortest code in bytes wins!

答:
Rust, 141 137 bytes

Abused some formatting stuff, otherwise this would've been a lot longer.

|i|{let f=||{for _ in 0..i{print!("{}",i)}println!("")};f();if i>1{for _ in 0..i-2{println!("{}{0:1$}",i,i.to_string().len()*(i-1))}f()}}
```

<p>Unpacked:</p>

<pre class="lang-rust prettyprint-override"><code>|i| {
    let f = || {
        for _ in 0..i {
            print!("{}",i)
        }
        println!("")
    };

    f();

    if i>1 {
        for _ in 0..i-2 {
            println!("{}{0:1$}",i,i.to_string().len()*(i-1))
        }
        f()
    }
}
</code>```

Playground Link

Title: Print N Squared

Body:
Rust, 141 137 bytes

Abused some formatting stuff, otherwise this would've been a lot longer.

|i|{let f=||{for _ in 0..i{print!("{}",i)}println!("")};f();if i>1{for _ in 0..i-2{println!("{}{0:1$}",i,i.to_string().len()*(i-1))}f()}}

Unpacked:

|i| {
    let f = || {
        for _ in 0..i {
            print!("{}",i)
        }
        println!("")
    };

    f();

    if i>1 {
        for _ in 0..i-2 {
            println!("{}{0:1$}",i,i.to_string().len()*(i-1))
        }
        f()
    }
}

Playground Link


答:
Labyrinth, <s>54</s> 25 bytes

```<code><#; "#: ={},>
 }=}(.);("@
</code>```

Another collab with @MartinBüttner, who actually did <s>most</s> almost all of the golfing for this one. By revamping the algorithm, we've managed to cut down the program size by quite a bit!

Try it online!

Explanation

A quick Labrinth primer:

Labyrinth is a stack-based 2D  language. There are two stacks, a main and auxiliary stack, and popping from an empty stack yields zero.

At each junction, where there are multiple paths for the instruction pointer to move down, the top of the main stack is  checked to see  where to go next. Negative is turn left, zero is straight ahead and positive is turn right.

The two stacks of arbitrary-precision integers isn't much flexibility in terms of memory options. To perform the counting, this program actually uses the two stacks as a tape, with shifting a value from one stack to the other being akin to moving a memory pointer left/right by a cell. It's not quite the same as that though, since we need to drag a loop counter with us on the way up.

First off, the < and > on either end pop an offset and rotate the row of code that offset away by one either left or right. This mechanism is used to make the code run in a loop - the < pops a zero and rotates the current row left, putting the IP at the right of the code, and the > pops another zero and fixes the row back.

Here's what happens each iteration, in relation to the diagram above:

```<code>[Section 1]
,}    Read char of input and shift to aux - the char will be used as a counter
      to determine how many elements to shift

[Section 2 - shift loop]
{     Shift counter from aux
"     No-op at a junction: turn left to [Section 3] if char was EOF (-1), otherwise
      turn right
(     Decrement counter; go forward to [Section 4] if zero, otherwise turn right
=     Swap tops of main and aux - we've pulled a value from aux and moved the
      decremented counter to aux, ready for the next loop iteration

[Section 3]
@     Terminate

[Section 4]
;     Pop the zeroed counter
)     Increment the top of the main stack, updating the count of the number of times
      we've seen the read char
:     Copy the count, to determine how many chars to output

[Section 5 - output loop]
#.    Output (number of elements on stack) as a char
(     Decrement the count of how many chars to output; go forward to [Section 6]
      if zero, otherwise turn right
"     No-op

[Section 6]
}     Shift the zeroed counter to aux

[Section 7a]
This section is meant to shift one element at a time from main to aux until the main
stack is empty, but the first iteration actually traverses the loop the wrong way!

Suppose the stack state is [... a b c | 0 d e ...].

=     Swap tops of main and aux               [... a b 0 | c d e ...]
}     Move top of main to aux                 [... a b | 0 c d e ...]
#;    Push stack depth and pop it (no-op)
=     Swap tops of main and aux               [... a 0 | b c d e ...]
      Top is 0 at a junction - can't move
      forwards so we bounce back
;     Pop the top 0                           [... a | b c d e ... ]

The net result is that we've shifted two chars from main to aux and popped the
extraneous zero. From here the loop is traversed anticlockwise as intended.

[Section 7b - unshift loop]

#     Push stack depth; if zero, move forward to the <, else turn left
}=    Move to aux and swap main and aux, thus moving the char below (stack depth)
      to aux
;     Pop the stack depth
</code>```

Title: Stretch the word

Body:
Labyrinth, <s>54</s> 25 bytes

<#; "#: ={},>
 }=}(.);("@

Another collab with @MartinBüttner, who actually did <s>most</s> almost all of the golfing for this one. By revamping the algorithm, we've managed to cut down the program size by quite a bit!

Try it online!

Explanation

A quick Labrinth primer:

Labyrinth is a stack-based 2D  language. There are two stacks, a main and auxiliary stack, and popping from an empty stack yields zero.

At each junction, where there are multiple paths for the instruction pointer to move down, the top of the main stack is  checked to see  where to go next. Negative is turn left, zero is straight ahead and positive is turn right.

The two stacks of arbitrary-precision integers isn't much flexibility in terms of memory options. To perform the counting, this program actually uses the two stacks as a tape, with shifting a value from one stack to the other being akin to moving a memory pointer left/right by a cell. It's not quite the same as that though, since we need to drag a loop counter with us on the way up.

First off, the < and > on either end pop an offset and rotate the row of code that offset away by one either left or right. This mechanism is used to make the code run in a loop - the < pops a zero and rotates the current row left, putting the IP at the right of the code, and the > pops another zero and fixes the row back.

Here's what happens each iteration, in relation to the diagram above:

[Section 1]
,}    Read char of input and shift to aux - the char will be used as a counter
      to determine how many elements to shift

[Section 2 - shift loop]
{     Shift counter from aux
"     No-op at a junction: turn left to [Section 3] if char was EOF (-1), otherwise
      turn right
(     Decrement counter; go forward to [Section 4] if zero, otherwise turn right
=     Swap tops of main and aux - we've pulled a value from aux and moved the
      decremented counter to aux, ready for the next loop iteration

[Section 3]
@     Terminate

[Section 4]
;     Pop the zeroed counter
)     Increment the top of the main stack, updating the count of the number of times
      we've seen the read char
:     Copy the count, to determine how many chars to output

[Section 5 - output loop]
#.    Output (number of elements on stack) as a char
(     Decrement the count of how many chars to output; go forward to [Section 6]
      if zero, otherwise turn right
"     No-op

[Section 6]
}     Shift the zeroed counter to aux

[Section 7a]
This section is meant to shift one element at a time from main to aux until the main
stack is empty, but the first iteration actually traverses the loop the wrong way!

Suppose the stack state is [... a b c | 0 d e ...].

=     Swap tops of main and aux               [... a b 0 | c d e ...]
}     Move top of main to aux                 [... a b | 0 c d e ...]
#;    Push stack depth and pop it (no-op)
=     Swap tops of main and aux               [... a 0 | b c d e ...]
      Top is 0 at a junction - can't move
      forwards so we bounce back
;     Pop the top 0                           [... a | b c d e ... ]

The net result is that we've shifted two chars from main to aux and popped the
extraneous zero. From here the loop is traversed anticlockwise as intended.

[Section 7b - unshift loop]

#     Push stack depth; if zero, move forward to the <, else turn left
}=    Move to aux and swap main and aux, thus moving the char below (stack depth)
      to aux
;     Pop the stack depth


答:
Perl 5, 40 bytes

requires -E (free)

```<code>sub a{say"@_";($c,$d)=@_;a($c+$d,$c-$d)}
</code>```

<s>or (same length)

```<code>$_=<>;{say;/ /;$_=$`+$'.$".($`-$');redo}
</code>```

</s>

(I struck through the latter because it should have rounding errors for some iterations.)

Hat-tip.

But I suspect there must be a shorter Perl 5 solution.

Title: The plus-minus sequence

Body:
Perl 5, 40 bytes

requires -E (free)

sub a{say"@_";($c,$d)=@_;a($c+$d,$c-$d)}

<s>or (same length)

$_=<>;{say;/ /;$_=$`+$'.$".($`-$');redo}

</s>

(I struck through the latter because it should have rounding errors for some iterations.)

Hat-tip.

But I suspect there must be a shorter Perl 5 solution.


答:
Ruby, <s>50</s> 48 bytes

Anonymous function.

```<code>->s{i=0
s.chars.map{|c|c*s[0,i+=1].count(c)}*''}
</code>```

Title: Stretch the word

Body:
The input is a word of lowercase letters not separated by whitespace. A newline at the end is optional.

The same word must be output in a modified version: For each character, double it the second time it appears in the original word, triple it the third time etc.

Example input:

```<code>bonobo
</code>```

Example output:

```<code>bonoobbooo
</code>```

Standard I/O rules apply. The shortest code in bytes wins.

Tests provided by @Neil :

```<code>tutu -> tuttuu
queue -> queuuee
bookkeeper -> boookkkeeepeeer
repetitive -> repeetittiiveee
uncopyrightables -> uncopyrightables
abracadabra -> abraacaaadaaaabbrraaaaa
mississippi -> misssiisssssssiiipppiiii
</code>```

Body:
Ruby, <s>50</s> 48 bytes

Anonymous function.

->s{i=0
s.chars.map{|c|c*s[0,i+=1].count(c)}*''}


答:
Javascript ES6 44 bytes

```<code>q=>q.replace(/./g,a=>x[a]=(x[a]||'')+a,x=[])
</code>```

old answer

Javascript ES6 46 bytes

```<code>q=>(x=[...q]).map(a=>x[a]=(x[a]||'')+a).join``

//thanks user81655 for -1 byte
</code>```

Title: Stretch the word

Body:
Javascript ES6 44 bytes

q=>q.replace(/./g,a=>x[a]=(x[a]||'')+a,x=[])

old answer

Javascript ES6 46 bytes

q=>(x=[...q]).map(a=>x[a]=(x[a]||'')+a).join``

//thanks user81655 for -1 byte


答:
Reng v.3.2, 43 bytes

```<code>1#xk#yaïí'1ø ~n-1$\
1+)x(%:1,%1ex+y1-?^#y#x
</code>```

Try it here! This code can be split into three parts: initial, computational, and final.

Initial

```<code>1#xk#yaïí'1ø
</code>```

This stores 1 to x, the length of the input stack k to y, and gets all input (aïí) which is then sorted ('). 1ø goes to the next line, i.e., the next part.

Computational

```<code>1+)x(%:1,%1ex+y1-?^#y#x
</code>```

Reng has no built-in for inequality. Thus, an algorithm must be implemented. The shortest algorithm I found for a < b is %:1,%1e; this looks like this:

```<code>Command | Stack
  ---   | a, b
   %    | a/b
   :    | a/b, a/b
   1    | a/b, a/b, 1
   ,    | a/b, (a/b)%1
   e    | (a/b) == ((a/b)%1)
</code>```

I'm sure that cleared it up! Let me explain further. x % 1, i.e modulus with 1, maps x to (-1,1). We know that (a/b) % 1 is a/b when a < b. Thus, this expression is equal to a < b.

However, this doesn't work quite as well because of problems with modulus with zero. So, we increment every member of the stack and the counter initially.

After we get the inequality Boolean on the stack, x+ adds it to x, but leaves it on the stack for the moment. y1- decrements y, and ?^ goes up iff y == 0 and we proceed to the final phase. Otherwise, we put y-1 into y and the new x into x.

Final

```<code>             ~n-1$\
</code>```

This pops the residual y-1 from the stack, decrements the result, outputs it, and ends the program.

Title: At least h with at least h

Body:
Input

A list of nonnegative integers.

Output

The largest nonnegative integer h such that at least h of the numbers in the list are greater than or equal to h.

Test Cases

```<code>[0,0,0,0] -> 0
[12,312,33,12] -> 4
[1,2,3,4,5,6,7] -> 4
[22,33,1,2,4] -> 3
[1000,2,2,2] -> 2
[23,42,12,92,39,46,23,56,31,12,43,23,54,23,56,73,35,73,42,12,10,15,35,23,12,42] -> 20
</code>```

Rules

You can write either a full program or a function, and anonymous functions are allowed too. This is code-golf, so the fewest byte count wins. Standard loopholes are disallowed.

Background

The h-index is a notion used in academia which aims to capture the impact and productivity of a researcher. According to Wikipedia, a researcher has index h, if he or she has published h scientific articles, each of which has been cited in other articles at least h times. Thus, this challenge is about computing the h-index from a list of citation counts.

Update

Wow, great answers all round! I have accepted the shortest one, but if someone else comes up with an even shorter one, I'll update my choice accordingly.

Winners by language

Here's a table of winners by language that I'll also try to keep up to date. I have included all posts with nonnegative score. Please correct me if I have made a mistake here.

APL: 7 bytes by @MorisZucca

Bash + coreutils: 29 bytes by @DigitalTrauma

C#: 103 bytes by @LegionMammal978

C++: 219 bytes by @user9587

CJam: 15 bytes by @nutki

GolfScript: 13 bytes by @IlmariKaronen

Haskell: 40 bytes by @proudhaskeller

J: 12 bytes by @ɐɔıʇǝɥʇuʎs

Java: 107 bytes by @Ypnypn

JavaScript: 48 bytes by @edc65

Mathematica: 38 bytes by @kukac67

Perl: 32 bytes by @nutki

Pyth: 10 bytes by @isaacg

Python: 49 bytes by @feersum

R: 29 bytes by @MickyT

Ruby: 41 bytes by @daniero

Scala: 62 bytes by @ChadRetz

SQL: 83 bytes by @MickyT

TI-BASIC: 22 bytes by @Timtech

Body:
Reng v.3.2, 43 bytes

1#xk#yaïí'1ø ~n-1$\
1+)x(%:1,%1ex+y1-?^#y#x

Try it here! This code can be split into three parts: initial, computational, and final.

Initial

1#xk#yaïí'1ø

This stores 1 to x, the length of the input stack k to y, and gets all input (aïí) which is then sorted ('). 1ø goes to the next line, i.e., the next part.

Computational

1+)x(%:1,%1ex+y1-?^#y#x

Reng has no built-in for inequality. Thus, an algorithm must be implemented. The shortest algorithm I found for a < b is %:1,%1e; this looks like this:

Command | Stack
  ---   | a, b
   %    | a/b
   :    | a/b, a/b
   1    | a/b, a/b, 1
   ,    | a/b, (a/b)%1
   e    | (a/b) == ((a/b)%1)

I'm sure that cleared it up! Let me explain further. x % 1, i.e modulus with 1, maps x to (-1,1). We know that (a/b) % 1 is a/b when a < b. Thus, this expression is equal to a < b.

However, this doesn't work quite as well because of problems with modulus with zero. So, we increment every member of the stack and the counter initially.

After we get the inequality Boolean on the stack, x+ adds it to x, but leaves it on the stack for the moment. y1- decrements y, and ?^ goes up iff y == 0 and we proceed to the final phase. Otherwise, we put y-1 into y and the new x into x.

Final

             ~n-1$\

This pops the residual y-1 from the stack, decrements the result, outputs it, and ends the program.


问:
Palindromizing the strings

Introduction

For the ones who don't know, a palindrome is when a string is equal to the string backwards (with exception to interpunction, spaces, etc.). An example of a palindrome is:

```<code>abcdcba
</code>```

If you reverse this, you will end up with:

```<code>abcdcba
</code>```

Which is the same. Therefore, we call this a palindrome. To palindromize things, let's take a look at an example of a string:

```<code>adbcb
</code>```

This is not a palindrome. To palindromize this, we need to merge the reversed string into the initial string at the right of the initial string, leaving both versions intact. The shorter, the better.

The first thing we can try is the following:

```<code>adbcb
bcbda
^^ ^^
</code>```

Not all characters match, so this is not the right position for the reversed string. We go one step to the right:

```<code>adbcb
 bcbda
 ^^^^
</code>```

This also doesn't match all characters. We go another step to the right:

```<code>adbcb
  bcbda
</code>```

This time, all characters match. We can merge both string leaving the intact. The final result is:

```<code>adbcbda
</code>```

This is the palindromized string.

The Task

Given a string (with at least one character) containing only lowercase letters (or uppercase, if that fits better), output the palindromized string.

Test cases

```<code>Input     Output

abcb      abcba
hello     hellolleh
bonobo    bonobonob
radar     radar
hex       hexeh
</code>```

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

答:
Pyth - <s>16</s> 12 bytes

4 bytes saved thanks to @FryAmTheEggman.

FGITW, much golfing possible.

```<code>h_I#+R_Q+k._
</code>```

Test Suite.

Title: Palindromizing the strings

Body:
Pyth - <s>16</s> 12 bytes

4 bytes saved thanks to @FryAmTheEggman.

FGITW, much golfing possible.

h_I#+R_Q+k._

Test Suite.


答:
05AB1E, 18 bytes

Code:

```<code>Â©gF¹ðN×®«ðñD®åi,q
</code>```

Uses CP-1252 encoding. Try it online!

Title: Palindromizing the strings

Body:
Introduction

For the ones who don't know, a palindrome is when a string is equal to the string backwards (with exception to interpunction, spaces, etc.). An example of a palindrome is:

```<code>abcdcba
</code>```

If you reverse this, you will end up with:

```<code>abcdcba
</code>```

Which is the same. Therefore, we call this a palindrome. To palindromize things, let's take a look at an example of a string:

```<code>adbcb
</code>```

This is not a palindrome. To palindromize this, we need to merge the reversed string into the initial string at the right of the initial string, leaving both versions intact. The shorter, the better.

The first thing we can try is the following:

```<code>adbcb
bcbda
^^ ^^
</code>```

Not all characters match, so this is not the right position for the reversed string. We go one step to the right:

```<code>adbcb
 bcbda
 ^^^^
</code>```

This also doesn't match all characters. We go another step to the right:

```<code>adbcb
  bcbda
</code>```

This time, all characters match. We can merge both string leaving the intact. The final result is:

```<code>adbcbda
</code>```

This is the palindromized string.

The Task

Given a string (with at least one character) containing only lowercase letters (or uppercase, if that fits better), output the palindromized string.

Test cases

```<code>Input     Output

abcb      abcba
hello     hellolleh
bonobo    bonobonob
radar     radar
hex       hexeh
</code>```

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

Body:
05AB1E, 18 bytes

Code:

Â©gF¹ðN×®«ðñD®åi,q

Uses CP-1252 encoding. Try it online!


问:
Finish a symmetrical map
You are given one-quarter of a map that is symmetrical over the x- and y-axes as input. The program should print the complete map.

The map can contain the following characters: -+/\|., and they should be turned as expected. The in data is always rectangular and small.

Example

```<code>$ cat in
+---
|./.
|/..

$ ./solution < in
+------+
|./..\.|
|/....\|
|\..../|
|.\../.|
+------+
</code>```

Shortest code wins.

答:
Golfscript - 32 chars

```<code>n%{{.-1%{.3%2=115*^}%+}%zip}2*n*
</code>```

Due to the symmetry of the problem, we repeat twice {flip horizontally, transpose (zip)}. As a bonus, you can change the value 2 to a larger number to repeat the image more.

Character transposition is done as x^=155 if x%3==2, due to the restricted character space. There's also {.5^3%(45+} at the same length.

ContentLicense: CC BY-SA 2.5

Title: Finish a symmetrical map

Body:
Golfscript - 32 chars

n%{{.-1%{.3%2=115*^}%+}%zip}2*n*

Due to the symmetry of the problem, we repeat twice {flip horizontally, transpose (zip)}. As a bonus, you can change the value 2 to a larger number to repeat the image more.

Character transposition is done as x^=155 if x%3==2, due to the restricted character space. There's also {.5^3%(45+} at the same length.


答:
Pyke, 15 bytes

```<code>D_Dlhm>m+#D_q)e
</code>```

Try it here!

Title: Palindromizing the strings

Body:
Pyke, 15 bytes

D_Dlhm>m+#D_q)e

Try it here!


答:
CJam, 18

```<code>q__,,{1$>_W%=}#<W%
</code>```

Try it online

Explanation:

```<code>q         read the input
__        make 2 copies
,,        convert the last one to a range [0 … length-1]
{…}#      find the first index that satisfies the condition:
  1$>     copy the input string and take the suffix from that position
  _W%=    duplicate, reverse and compare (palindrome check)
<         take the prefix before the found index
W%        reverse that prefix
          at the end, the stack contains the input string and that reversed prefix
</code>```

Title: Palindromizing the strings

Body:
CJam, 18

q__,,{1$>_W%=}#<W%

Try it online

Explanation:

q         read the input
__        make 2 copies
,,        convert the last one to a range [0 … length-1]
{…}#      find the first index that satisfies the condition:
  1$>     copy the input string and take the suffix from that position
  _W%=    duplicate, reverse and compare (palindrome check)
<         take the prefix before the found index
W%        reverse that prefix
          at the end, the stack contains the input string and that reversed prefix


答:
Retina, 29 25

```<code>$
¶$_
O^#r`.\G
(.+)¶\1
$1
</code>```

Try it online!

Big thanks to Martin for 11 bytes saved!

This just creates a reversed copy of the string and smooshes them together. The only really fancy part of this is the reversing method: O^#r`.\G, which is done by using sort mode. We sort the letters of the second string (the ones that aren't newlines and are consecutive from the end of the string, thanks to the \G) by their numeric value, which, since there are no numbers, is 0. Then we reverse the order of the results of this stable sort with the ^ option. All credit for the fancy use of \G belongs to Martin :)

Title: Palindromizing the strings

Body:
Retina, 29 25

$
¶$_
O^#r`.\G
(.+)¶\1
$1

Try it online!

Big thanks to Martin for 11 bytes saved!

This just creates a reversed copy of the string and smooshes them together. The only really fancy part of this is the reversing method: O^#r`.\G, which is done by using sort mode. We sort the letters of the second string (the ones that aren't newlines and are consecutive from the end of the string, thanks to the \G) by their numeric value, which, since there are no numbers, is 0. Then we reverse the order of the results of this stable sort with the ^ option. All credit for the fancy use of \G belongs to Martin :)


答:
J, 20 bytes

```<code>,[|.@{.~(-:|.)\.i.1:
</code>```

This is a monadic verb. Try it here. Usage:

```<code>   f =: ,[|.@{.~(-:|.)\.i.1:
   f 'race'
'racecar'
</code>```

Explanation

I'm using the fact that the palindromization of S is S + reverse(P), where P is the shortest prefix of S whose removal results in a palindrome.
In J, it's a little clunky to do a search for the first element of an array that satisfies a predicate; hence the indexing.

```<code>,[|.@{.~(-:|.)\.i.1:  Input is S.
        (    )\.      Map over suffixes of S:
         -:             Does it match
           |.           its reversal? This gives 1 for palindromic suffixes and 0 for others.
                i.1:  Take the first (0-based) index of 1 in that array.
 [   {.~              Take a prefix of S of that length: this is P.
  |.@                 Reverse of P.
,                     Concatenate it to S.
</code>```

Title: Palindromizing the strings

Body:
J, 20 bytes

,[|.@{.~(-:|.)\.i.1:

This is a monadic verb. Try it here. Usage:

   f =: ,[|.@{.~(-:|.)\.i.1:
   f 'race'
'racecar'

Explanation

I'm using the fact that the palindromization of S is S + reverse(P), where P is the shortest prefix of S whose removal results in a palindrome.
In J, it's a little clunky to do a search for the first element of an array that satisfies a predicate; hence the indexing.

,[|.@{.~(-:|.)\.i.1:  Input is S.
        (    )\.      Map over suffixes of S:
         -:             Does it match
           |.           its reversal? This gives 1 for palindromic suffixes and 0 for others.
                i.1:  Take the first (0-based) index of 1 in that array.
 [   {.~              Take a prefix of S of that length: this is P.
  |.@                 Reverse of P.
,                     Concatenate it to S.


答:
Pyth (commit b93a874), 11 bytes

```<code>.VkI_IJ+zbB
</code>```

Test suite

This code exploits a bug in the current version of Pyth, commit b93a874. The bug is that _IJ+zb is parsed as if it was q_J+zbJ+zb, which is equivalent to _I+zb+zb, when it should (by the design intention of Pyth) be parsed as q_J+zbJ, which is equivalent to _I+zb. This allows me to save a byte - after the bug is fixed, the correct code will be .VkI_IJ+zbJB. I'll explain that code instead.

Basically, the code brute forces over all possible strings until it finds the shortest string that can be appended to the input to form a palindrome, and outputs the combined string.

```<code>.VkI_IJ+zbJB
                z = input()
.Vk             For b in possible strings ordered by length,
       +zb      Add z and b,
      J         Store it in J,
    _I          Check if the result is a palindrome,
   I            If so,
          J     Print J (This line doesn't actually exist, gets added by the bug.
          B     Break.
</code>```

Title: Palindromizing the strings

Body:
Pyth (commit b93a874), 11 bytes

.VkI_IJ+zbB

Test suite

This code exploits a bug in the current version of Pyth, commit b93a874. The bug is that _IJ+zb is parsed as if it was q_J+zbJ+zb, which is equivalent to _I+zb+zb, when it should (by the design intention of Pyth) be parsed as q_J+zbJ, which is equivalent to _I+zb. This allows me to save a byte - after the bug is fixed, the correct code will be .VkI_IJ+zbJB. I'll explain that code instead.

Basically, the code brute forces over all possible strings until it finds the shortest string that can be appended to the input to form a palindrome, and outputs the combined string.

.VkI_IJ+zbJB
                z = input()
.Vk             For b in possible strings ordered by length,
       +zb      Add z and b,
      J         Store it in J,
    _I          Check if the result is a palindrome,
   I            If so,
          J     Print J (This line doesn't actually exist, gets added by the bug.
          B     Break.


问:
All possible ways to interleave two strings
I recently saw this question on stackoverflow. It's a great question, but there's one fatal problem with the question. They are asking for the best way to do it. E.g, easiest to read, most idiomatic, neatest etc. Don't they know that isn't what matters? You're supposed to ask about how to do it with the fewest bytes of code!

Since I doubt that question will be appreciated on stackoverflow, I decided to ask it here.

The challenge

You must write the shortest possible program or function that generates all possible ways to interleave any two arbitrary strings. For example, if the two strings are 'ab' and 'cd', the output is:

```<code>['abcd', 'acbd', 'acdb', 'cabd', 'cadb', 'cdab']
</code>```

As you can see, a is always before b, and c is always before d.

IO can be in any reasonable format. Use this python code to verify to check your output. (credit: JeD)

```<code>def shuffle(s,t):
    if s=="":
        return [t]
    elif t=="":
        return [s]
    else:
        leftShuffle=[s[0]+val for val in shuffle(s[1:],t)]
        rightShuffle=[t[0]+val for val in shuffle(s,t[1:])]
        leftShuffle.extend(rightShuffle)
        return leftShuffle
</code>```

Sample IO:

```<code>shuffle("$", "1234"):
['$1234', '1$234', '12$34', '123$4', '1234$']

shuffle("az", "by"):
['azby', 'abzy', 'abyz', 'bazy', 'bayz', 'byaz']

shuffle("code", "golf"):
['codegolf', 'codgeolf', 'codgoelf', 'codgolef', 'codgolfe', 'cogdeolf', 'cogdoelf',
'cogdolef', 'cogdolfe', 'cogodelf', 'cogodlef', 'cogodlfe', 'cogoldef', 'cogoldfe',
'cogolfde', 'cgodeolf', 'cgodoelf', 'cgodolef', 'cgodolfe', 'cgoodelf', 'cgoodlef',
'cgoodlfe', 'cgooldef', 'cgooldfe', 'cgoolfde', 'cgoodelf', 'cgoodlef', 'cgoodlfe',
'cgooldef', 'cgooldfe', 'cgoolfde', 'cgolodef', 'cgolodfe', 'cgolofde', 'cgolfode',
'gcodeolf', 'gcodoelf', 'gcodolef', 'gcodolfe', 'gcoodelf', 'gcoodlef', 'gcoodlfe',
'gcooldef', 'gcooldfe', 'gcoolfde', 'gcoodelf', 'gcoodlef', 'gcoodlfe', 'gcooldef',
'gcooldfe', 'gcoolfde', 'gcolodef', 'gcolodfe', 'gcolofde', 'gcolfode', 'gocodelf',
'gocodlef', 'gocodlfe', 'gocoldef', 'gocoldfe', 'gocolfde', 'goclodef', 'goclodfe',
'goclofde', 'goclfode', 'golcodef', 'golcodfe', 'golcofde', 'golcfode', 'golfcode']
</code>```

As usual, standard loopholes apply, and the shortest answer in bytes wins. Since the question was originally about python, I'd love to see the shortest python answer. (And no, pyth is not python). However, answers in any language are encouraged.

答:
Ruby, 83 bytes

A recursive function that returns [a+b] if either of those strings are empty. Otherwise, it returns a list of strings a[0] + every string in v[a[1..-1],b] added to a list of string b[0] + every string in v[a,b[1..-1]]

v=->a,b{a[0]&&b[0]?v[a[1..-1],b].map{|i|a[0]+i}+v[a,b[1..-1]].map{|i|b[0]+i}:[a+b]}
```


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

Loosely inspired in @aditsu's CJam answer.

```<code>`xGt@q:)PhttP=A~
</code>```

Try it online!

Explanation

```<code>`        % Do...while loop
  x      %   Delete top of stack, which contains a not useful result from the
         %   iteration. Takes input implicitly on first iteration, and deletes it
  G      %   Push input
  t      %   Duplicate
  @q:    %   Generate range [1,...,n-1], where n is iteration index. On the  first
         %   iteration this is an empty array
  )      %   Use that as index into copy of input string: get its first n elements
  Ph     %   Flip and concatenate to input string
  t      %   Duplicate. This will be the final result, or will be deleted at the
         %   beginning of next iteration
  tP     %   Duplicate and flip
  =A~    %   Compare element-wise. Is there some element different? If so, the
         %   result is true. This is the loop condition, so go there will be a
         %   new iteration. Else the loop is exited with the stack containing
         %   the contatenated string
         % End loop implicitly
         % Display stack contents implicitly
</code>```

Title: Palindromizing the strings

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

Loosely inspired in @aditsu's CJam answer.

`xGt@q:)PhttP=A~

Try it online!

Explanation

`        % Do...while loop
  x      %   Delete top of stack, which contains a not useful result from the
         %   iteration. Takes input implicitly on first iteration, and deletes it
  G      %   Push input
  t      %   Duplicate
  @q:    %   Generate range [1,...,n-1], where n is iteration index. On the  first
         %   iteration this is an empty array
  )      %   Use that as index into copy of input string: get its first n elements
  Ph     %   Flip and concatenate to input string
  t      %   Duplicate. This will be the final result, or will be deleted at the
         %   beginning of next iteration
  tP     %   Duplicate and flip
  =A~    %   Compare element-wise. Is there some element different? If so, the
         %   result is true. This is the loop condition, so go there will be a
         %   new iteration. Else the loop is exited with the stack containing
         %   the contatenated string
         % End loop implicitly
         % Display stack contents implicitly


问:
Hilbert-Curvify a Matrix
Inspired by this question

Another way to unroll a 2D image into a 1D string is to use an Hilbert Curve.

There are many version of this curve, depending on the number of iterations used while computing it. Below follow example of Hilbert Curves from first order to fifth order.

The way of computing this curve is the following. First we define the first order Hilbert Curve as the one shown in figure (the one for n = 1), so that it fits in a 1x1 square. We than make four copies of this curve, spacing them in a 4x4 square, so that they all present the "concavity" towards the left side. We then flip the two leftmost order 1 curves, so that the top one concavity faces toward the top, while the bottom's faces the bottom. We finally connect the the corners of the adjacent Hilbert Curves. If wanting to obtain a (n+1)-order Curve, we just need to repeat the process with four n-order Curves. We can see a visualisation of the process here (I will also add an image detailing the process soon)

Your task in this challenge is to unroll a matrix of integers along the lowest order Hilbert Curve for that matrix.

For simplicity's sake, we will have the curve starting from the top left corner of the matrix.

You can receive the input either as a list of list of integers, where each
sub-list represents a row of the matrix.

You can assume that the input will be a square matrix (n*n).

For example:

Input:

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

Output:

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

Since we are using the first order Hilbert Curve shown in figure

Input:

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

Output:

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

Using the second order Hilbert Curve

As usual, standard loopholes are not permitted.

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

答:
CJam, 60

```<code>Lq~:A,2mL{:B1f^0B1B2B3f^]:+}*1+{AT=U=\2md'U^_~)@2*-':@+~;}%p
</code>```

Try it online

Explanation:

I'm building the fractal as a series of movement directions: 0=right, 1=down, 2=left, 3=up.

```<code>L          push an empty array (level 0 fractal)
q~:A       read the input, evaluate and store in A
,2mL       get the length (number of rows) and calculate the logarithm in base 2
            (to get the desired level)
{…}*       repeat <level> times
  :B       store the previous-level fractal in B
  1f^      XOR it with 1 (top-left part)
  0        (move right)
  B        copy the fractal (top right part)
  1        (move down)
  B        copy the fractal (bottom right part)
  2        (move left)
  B3f^     copy the fractal and XOR it with 3 (bottom left part)
  ]:+      put everything in an array and concatenate the parts
1+         add a dummy move (needed for the last step)
{…}%       apply to each direction in the array
  AT=U=    push A[T][U] (T and U are initially 0)
  \2md     bring the direction to the top and get the quotient and remainder mod 2
  'U^      XOR the 'U' character with the remainder,
            to get the variable we want to modify
  _~)      make a copy of it, then evaluate it and increment
  @2*-     bring the quotient to the top, multiply by 2 and subtract
  ':@+     concatenate ':' with the variable name
  ~;       evaluate (this updates the variable) and pop the result
p          pretty-print the resulting array
</code>```

Title: Hilbert-Curvify a Matrix

Body:
CJam, 60

Lq~:A,2mL{:B1f^0B1B2B3f^]:+}*1+{AT=U=\2md'U^_~)@2*-':@+~;}%p

Try it online

Explanation:

I'm building the fractal as a series of movement directions: 0=right, 1=down, 2=left, 3=up.

L          push an empty array (level 0 fractal)
q~:A       read the input, evaluate and store in A
,2mL       get the length (number of rows) and calculate the logarithm in base 2
            (to get the desired level)
{…}*       repeat <level> times
  :B       store the previous-level fractal in B
  1f^      XOR it with 1 (top-left part)
  0        (move right)
  B        copy the fractal (top right part)
  1        (move down)
  B        copy the fractal (bottom right part)
  2        (move left)
  B3f^     copy the fractal and XOR it with 3 (bottom left part)
  ]:+      put everything in an array and concatenate the parts
1+         add a dummy move (needed for the last step)
{…}%       apply to each direction in the array
  AT=U=    push A[T][U] (T and U are initially 0)
  \2md     bring the direction to the top and get the quotient and remainder mod 2
  'U^      XOR the 'U' character with the remainder,
            to get the variable we want to modify
  _~)      make a copy of it, then evaluate it and increment
  @2*-     bring the quotient to the top, multiply by 2 and subtract
  ':@+     concatenate ':' with the variable name
  ~;       evaluate (this updates the variable) and pop the result
p          pretty-print the resulting array


问:
Reverse stdin and place on stdout
Requirements:

Take an input on stdin including new lines / carriage returns of unlimited length (only bounded by system memory; that is, there is no inherent limit in the program.)

Output the reverse of the input on stdout.

Example:

Input:

```<code>Quick brown fox
He jumped over the lazy dog
</code>```

Output:

```<code>god yzal eht revo depmuj eH
xof nworb kciuQ
</code>```

Shortest wins.

Leaderboard:

var QUESTION_ID=242,OVERRIDE_USER=61563;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

```

答:
Retina, 6 bytes

Non-competing, since Retina is newer than this challenge.

```<code>O$^s`.
</code>```

Try it online!

With Retina's latest addition (sort stages), this became a lot shorter. Sort stages work by matching a bunch of things via the supplied regex, and then sorting those matches treating everything that wasn't matched like list-delimiters. This stage type comes with a bunch of options that we can (ab)use to reverse a string.

For a start, the regex is simply ., which matches a single character, and the s modifier ensures that it can also match linefeeds. That is, we're sorting all the characters in the input. As for the others:

O just activates sorting.

$ tells Retina that the matches shouldn't be sorted by their actual string value, but that a regex substitution is first applied to them, and they are then sorted by the result of that substitution. Now the program has only a single line (the substitution would go on the second line), so that all matches are just replaced with an empty string. That means, to the sorting function, all matches are equal, and no sorting happens at all.

Finally, ^ tells Retina to reverse the order of the matches after sorting.

Title: Reverse stdin and place on stdout

Body:
Retina, 6 bytes

Non-competing, since Retina is newer than this challenge.

O$^s`.

Try it online!

With Retina's latest addition (sort stages), this became a lot shorter. Sort stages work by matching a bunch of things via the supplied regex, and then sorting those matches treating everything that wasn't matched like list-delimiters. This stage type comes with a bunch of options that we can (ab)use to reverse a string.

For a start, the regex is simply ., which matches a single character, and the s modifier ensures that it can also match linefeeds. That is, we're sorting all the characters in the input. As for the others:

O just activates sorting.

$ tells Retina that the matches shouldn't be sorted by their actual string value, but that a regex substitution is first applied to them, and they are then sorted by the result of that substitution. Now the program has only a single line (the substitution would go on the second line), so that all matches are just replaced with an empty string. That means, to the sorting function, all matches are equal, and no sorting happens at all.

Finally, ^ tells Retina to reverse the order of the matches after sorting.


答:
JavaScript (ES6), 92 bytes

```<code>(s,a=[...s],r=a.reverse().join``)=>s.slice(0,a.findIndex((_,i)=>r.startsWith(s.slice(i))))+r
</code>```

Computes and slices away the overlap between the original string and its reversal.

Title: Palindromizing the strings

Body:
JavaScript (ES6), 92 bytes

(s,a=[...s],r=a.reverse().join``)=>s.slice(0,a.findIndex((_,i)=>r.startsWith(s.slice(i))))+r

Computes and slices away the overlap between the original string and its reversal.


答:
Beam, 32 <s>33</s> <s>42</s> bytes

This should have been smaller, but I lost some bytes initializing the memory slots to 0.  Swapping some flow directions managed to eliminate a lot of empty space.

```<code> >+\
vus/
>rnH
  >g'\
(@v's/
^`<
</code>```

Try it in this snippet

General explanation.

Set all the memory slots from 0-255 to 0

Read in the input ascii value into the beam

If beam is 0 halt (beam = store)

Get the memory[beam] value into the store, increment it and save back

Decrement the store to 0 printing out the beam character

Repeat

Title: Stretch the word

Body:
The input is a word of lowercase letters not separated by whitespace. A newline at the end is optional.

The same word must be output in a modified version: For each character, double it the second time it appears in the original word, triple it the third time etc.

Example input:

```<code>bonobo
</code>```

Example output:

```<code>bonoobbooo
</code>```

Standard I/O rules apply. The shortest code in bytes wins.

Tests provided by @Neil :

```<code>tutu -> tuttuu
queue -> queuuee
bookkeeper -> boookkkeeepeeer
repetitive -> repeetittiiveee
uncopyrightables -> uncopyrightables
abracadabra -> abraacaaadaaaabbrraaaaa
mississippi -> misssiisssssssiiipppiiii
</code>```

Body:
Beam, 32 <s>33</s> <s>42</s> bytes

This should have been smaller, but I lost some bytes initializing the memory slots to 0.  Swapping some flow directions managed to eliminate a lot of empty space.

 >+\
vus/
>rnH
  >g'\
(@v's/
^`<

Try it in this snippet

General explanation.

Set all the memory slots from 0-255 to 0

Read in the input ascii value into the beam

If beam is 0 halt (beam = store)

Get the memory[beam] value into the store, increment it and save back

Decrement the store to 0 printing out the beam character

Repeat


问:
I am passive aggressive and want to insult my boss without him finding out
It's been a rough few months at work and I feel like I just want to scream right to my boss' face. I am, however, not one to directly confront people I have a problem with. I also don't want to lose my job.

So here's an idea: I want to be able to insult him, without him ever finding out. And I realized the perfect way: I need some sort of software that encodes an insult inside an otherwise perfectly fine message. And seeing as how he's known to not see forests for trees, I think I know just how:

Write me a program that takes as input a string of unknown length, but containing no line breaks. This will be the raw message I want to send.

If possible, return the string formatted such that the message "DIE IN A GREASE FIRE" makes up the entire left column. With new paragraphs where spaces in between words should go. Now, as I am very angry, it is equally important that every letter is in upper case.

You may not modify the string in any other way, i.e. you may not turn all of the string into upper case characters.

If the string in question cannot be formatted in this way, you are to return the original string. Read input from standard input.

Normal rules apply: No HTTP requests, no consulting Marvin from THGTTG, etc.

Example input:

Dear Boss, how are things? It has come to my attention that I received
  all the blame for the mishap last Friday. Not just the majority of it.
  Every last bit of it. Is it wrong for me to think that the rest of the
  team were at least in part responsible? After all, all six of us were
  involved from the get-go. Not that I think I should stand without
  blame. Not at all. All I'm saying is this: I do my best. I try hard. I
  improve constantly. And I am constantly taking responsibility.
  Generally speaking, I am very okay with taking full responsibility for
  my actions. But after this spring, it seems I get more than I deserve.
  Remember the Flakenhauser contract? Everything went down just about as
  smooth as one could have hoped. Or so it seemed at first. It was just
  at the very last minute that things fell apart. All of the team agreed
  that it was more akin to a freak accident than sloppy planning or
  mismanaged resources. Still, I - alone - took blame for it. Even
  though I said nothing then, my tolerance level for taking the blame
  took a serious dent then. From that point on, I have felt it necessary
  to always try twice as hard, just to escape scrutiny. And still, here
  we are again. In spite of all my accomplishments. Right where we
  always seem to end up these days. Every single project. It's becoming
  unbearable.

Example output:

Dear Boss, how are things?

  It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it.

  Every last bit of it.

Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go.

  Not that I think I should stand without blame. Not at all.

All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility.

Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve.

  Remember the Flakenhauser contract.

  Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart.

  All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources.

  Still, I - alone - took blame for it.

  Even though I said nothing then, my tolerance level for taking the blame took a serious dent then.

From that point on, I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again.

  In spite of all my accomplishments.

  Right where we always seem to end up these days.

  Every single project. It's becoming unbearable.

This is code golf. Shortest code wins.

答:
PHP, 328 bytes

Given a file named 'G' containing the raw text to "enmessage"

```<code><?php
$a=implode(file("G"));$b=str_split('DIEINAGREASEFIRE');foreach(array_unique($b) as $c){foreach(str_split($a) as $h=>$d){if($c==$d)$l[$c][]=$h;}}$e=-1;$n=$a;foreach($b as $f=>$c){foreach($l as $j=>$m){if($c==$j){foreach($m as $k=>$h){if($h>$e){$n=substr($n,0,$h)."\n".$c.substr($a,$h+1);$e=$h+2;break 2;}}}}}echo nl2br($n);
</code>```

Explanation (~ungolfed && commented code) :

```<code><?php
$string=implode(file("G"));          // raw text to deal with
$msg=str_split('DIEINAGREASEFIRE');  // hidden message (make it an array)

 // 2D array : [letters of the message][corresponding positions in txt]
foreach(array_unique($msg) as $letter) {
    foreach (str_split($string) as $pos=>$let) {
        if ($letter==$let) $l[$letter][]=$pos; //1 array per seeked letter with its positions in the string
    }
}

$currentPos=-1;
$newString=$string;
foreach ($msg as $key=>$letter) { // deal with each letter of the desired message to pass
    foreach($l as $cap=>$arrPos) {// search in letters list with their positions
        if($letter==$cap) {       // array of the current parsed letter of the message
            foreach($arrPos as $kk=>$pos) { // see every position
                if ($pos>$currentPos) {     // ok, use the letter at that position
                    $newString=substr($newString,0,$pos)."\n".$letter.substr($string,$pos+1); // add line break
                    $currentPos=$pos+2; // take new characters into account (\n)
                    break 2;            // parse next letter of the message
                }
            }
        }
    }
}                    /* (note that I could have added some other (random) line breaks management, so that
                      * the message is not TOO obvious... !*/
echo nl2br($newString);
</code>```

Body:
PHP, 328 bytes

Given a file named 'G' containing the raw text to "enmessage"

<?php
$a=implode(file("G"));$b=str_split('DIEINAGREASEFIRE');foreach(array_unique($b) as $c){foreach(str_split($a) as $h=>$d){if($c==$d)$l[$c][]=$h;}}$e=-1;$n=$a;foreach($b as $f=>$c){foreach($l as $j=>$m){if($c==$j){foreach($m as $k=>$h){if($h>$e){$n=substr($n,0,$h)."\n".$c.substr($a,$h+1);$e=$h+2;break 2;}}}}}echo nl2br($n);

Explanation (~ungolfed && commented code) :

<?php
$string=implode(file("G"));          // raw text to deal with
$msg=str_split('DIEINAGREASEFIRE');  // hidden message (make it an array)

 // 2D array : [letters of the message][corresponding positions in txt]
foreach(array_unique($msg) as $letter) {
    foreach (str_split($string) as $pos=>$let) {
        if ($letter==$let) $l[$letter][]=$pos; //1 array per seeked letter with its positions in the string
    }
}

$currentPos=-1;
$newString=$string;
foreach ($msg as $key=>$letter) { // deal with each letter of the desired message to pass
    foreach($l as $cap=>$arrPos) {// search in letters list with their positions
        if($letter==$cap) {       // array of the current parsed letter of the message
            foreach($arrPos as $kk=>$pos) { // see every position
                if ($pos>$currentPos) {     // ok, use the letter at that position
                    $newString=substr($newString,0,$pos)."\n".$letter.substr($string,$pos+1); // add line break
                    $currentPos=$pos+2; // take new characters into account (\n)
                    break 2;            // parse next letter of the message
                }
            }
        }
    }
}                    /* (note that I could have added some other (random) line breaks management, so that
                      * the message is not TOO obvious... !*/
echo nl2br($newString);


答:
Haskell, 68 bytes

```<code>import Data.List
f i=[i++r x|x<-inits i,i++r x==x++r i]!!0
r=reverse
</code>```

Usage example: f "abcb" -> "abcba".

Search through the inits of the input i (e.g. inits "abcb" -> ["", "a", "ab", "abc", "abcb"]) until you find one where it's reverse appended to i builds a palindrome.

Title: Palindromizing the strings

Body:
Haskell, 68 bytes

import Data.List
f i=[i++r x|x<-inits i,i++r x==x++r i]!!0
r=reverse

Usage example: f "abcb" -> "abcba".

Search through the inits of the input i (e.g. inits "abcb" -> ["", "a", "ab", "abc", "abcb"]) until you find one where it's reverse appended to i builds a palindrome.


答:
Python, 46 bytes

f=lambda s:s*(s==s[::-1])or s[0]+f(s[1:])+s[0]
```
<p>If the string is a palindrome, return it. Otherwise, sandwich the first letter around the recursive result for the remainder of the string.</p>
<p>Example breakdown:</p>
<pre class="lang-python prettyprint-override"><code>f(bonobo)
b  f(onobo) b
b o f(nobo) o b
b o n f(obo) n o b
b o n obo n o b
</code>```

Title: Palindromizing the strings

Body:
Python, 46 bytes

f=lambda s:s*(s==s[::-1])or s[0]+f(s[1:])+s[0]

If the string is a palindrome, return it. Otherwise, sandwich the first letter around the recursive result for the remainder of the string.

Example breakdown:

f(bonobo)
b  f(onobo) b
b o f(nobo) o b
b o n f(obo) n o b
b o n obo n o b