答:
Haskell, 19 bytes

```<code>a#0=a
a#b=b#rem a b
</code>```

Usage example: 45 # 35-> 5.

Euclid, again.

PS: of course there's a built-in gcd, too.

Title: Greatest Common Divisor

Body:
Haskell, 19 bytes

a#0=a
a#b=b#rem a b

Usage example: 45 # 35-> 5.

Euclid, again.

PS: of course there's a built-in gcd, too.


问:
Greatest Common Divisor
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

答:
Ruby, 23 bytes

```<code>g=->a,b{b>0?a:g[b,a%b]}
</code>```

remember that ruby blocks are called with g[...] or g.call(...), instead of g(...)

partial credits to voidpigeon

ContentLicense: CC BY-SA 3.0

Title: Greatest Common Divisor

Body:
Ruby, 23 bytes

g=->a,b{b>0?a:g[b,a%b]}

remember that ruby blocks are called with g[...] or g.call(...), instead of g(...)

partial credits to voidpigeon


问:
Split string into n pieces (or pieces of length n)

The Challenge

In this challenge you have to do two different (but related) tasks depending of the order of the input.

Your program will recieve a string s and an integer n as input and will

split s into pieces of length n if s comes first. The last element will be shorter if necessary.

split s into n pieces of equal length if n comes first. If len(s) is not a multiple of n the first len(s) mod n elements will be one longer.

You may only take those 2 inputs. s will never contain only digits.

Notes

You may use the reverse mapping. Note this in your answer if you do that.

s will only contain printable ASCII characters (no newlines).

You may not use any builtins that solve either those two tasks directly. All other builtins are allowed.

You have to take both arguments from the same source.

You may take the arguments in an ordered list or any other format which clearly indicates their order as long as it is unambiguous.

You may take the input as one string/ stream and use a character which is not a valid input (like a nullbyte) to separate them.

n will always be equal or less than the length of s and greater than zero.

You may output the resulting list in any resonable format as long as it clearly indicates the particular pieces and their order.

Example

Input:  programming, 3

The last element contains only 2 characters, because 11 is not divisible by 3.

Output: ["pro", "gra", "mmi", "ng"]

Input: 3, programming

11 is not a multiple of 3, so the first 2 elements will be one longer:

Output: ["prog", "ramm", "ing"]

Rules

Function or full program allowed.

Default rules for input/output.

Standard loopholes apply.

This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases

The test cases got generated with this Pyth program (uses builtins, so no valid answer). Thanks to @FryAmTheEggman for providing the base version of that!

```
3, helloworld -> ['hell', 'owo', 'rld']
helloworld, 3 -> ['hel', 'low', 'orl', 'd']
1, programming -> ['programming']
programming, 1 -> ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
8, programming -> ['pr', 'og', 'ra', 'm', 'm', 'i', 'n', 'g']
programming, 8 -> ['programm', 'ing']
9, code golf -> ['c', 'o', 'd', 'e', ' ', 'g', 'o', 'l', 'f']
code golf, 9 -> ['code golf']
4, 133tspeak -> ['133', 'ts', 'pe', 'ak']
133tspeak, 4 -> ['133t', 'spea', 'k']
```

Happy Coding!

答:
Pyth, 181 bytes

Let's pretend the longest code in bytes wins \o/

```<code>DyGK@G0J:@G1"."1=YJV%lJKW<l@YN.EclJK=YXYN+@YN@YhN=Y.DYhN)FNr%lJK/-lJ%lJK/-lJ%lJKKW<l@YNsclJK=YXYN+@YN@YhN=Y.DYhN))RY)DPG=K@G1=J:@G0"."1=YJV/lJKW<l@YNK=YXYN+@YN@YhN=Y.DYhN))RY).xyQPQ
</code>```

Try it here ! (The online interpreter seem to have a bug, it displays the input while it should not)

Here's the output from the terminal:

```<code>» pyth split.pyth <<<'["helloworld", 3]'
['hel', 'low', 'orl', 'd']
» pyth split.pyth <<<'[3, "Helloworld"]'
['Hell', 'owo', 'rld']
</code>```

Seriously, I am open to new approach. I'm new to python, so I probably missed a few shorthands.

I mean, I think my answer is deseperate from the point it is longer than the javascript answer...

Body:
Pyth, 181 bytes

Let's pretend the longest code in bytes wins \o/

DyGK@G0J:@G1"."1=YJV%lJKW<l@YN.EclJK=YXYN+@YN@YhN=Y.DYhN)FNr%lJK/-lJ%lJK/-lJ%lJKKW<l@YNsclJK=YXYN+@YN@YhN=Y.DYhN))RY)DPG=K@G1=J:@G0"."1=YJV/lJKW<l@YNK=YXYN+@YN@YhN=Y.DYhN))RY).xyQPQ

Try it here ! (The online interpreter seem to have a bug, it displays the input while it should not)

Here's the output from the terminal:

» pyth split.pyth <<<'["helloworld", 3]'
['hel', 'low', 'orl', 'd']
» pyth split.pyth <<<'[3, "Helloworld"]'
['Hell', 'owo', 'rld']

Seriously, I am open to new approach. I'm new to python, so I probably missed a few shorthands.

I mean, I think my answer is deseperate from the point it is longer than the javascript answer...


答:
Ruby, 119 bytes

```<code>->x,y{r=[t=0];x.to_s==x ?(r.push x[t...t+=y]while x[t]):x.times{r.push y[t...t+=y.size/x+(r[y.size%x]? 0:1)]};r[1..-1]}
</code>```

And I take first place by 2 bytes...

Title: Split string into n pieces (or pieces of length n)

Body:
The Challenge

In this challenge you have to do two different (but related) tasks depending of the order of the input.

Your program will recieve a string s and an integer n as input and will

split s into pieces of length n if s comes first. The last element will be shorter if necessary.

split s into n pieces of equal length if n comes first. If len(s) is not a multiple of n the first len(s) mod n elements will be one longer.

You may only take those 2 inputs. s will never contain only digits.

Notes

You may use the reverse mapping. Note this in your answer if you do that.

s will only contain printable ASCII characters (no newlines).

You may not use any builtins that solve either those two tasks directly. All other builtins are allowed.

You have to take both arguments from the same source.

You may take the arguments in an ordered list or any other format which clearly indicates their order as long as it is unambiguous.

You may take the input as one string/ stream and use a character which is not a valid input (like a nullbyte) to separate them.

n will always be equal or less than the length of s and greater than zero.

You may output the resulting list in any resonable format as long as it clearly indicates the particular pieces and their order.

Example

Input:  programming, 3

The last element contains only 2 characters, because 11 is not divisible by 3.

Output: ["pro", "gra", "mmi", "ng"]

Input: 3, programming

11 is not a multiple of 3, so the first 2 elements will be one longer:

Output: ["prog", "ramm", "ing"]

Rules

Function or full program allowed.

Default rules for input/output.

Standard loopholes apply.

This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases

The test cases got generated with this Pyth program (uses builtins, so no valid answer). Thanks to @FryAmTheEggman for providing the base version of that!

```
3, helloworld -> ['hell', 'owo', 'rld']
helloworld, 3 -> ['hel', 'low', 'orl', 'd']
1, programming -> ['programming']
programming, 1 -> ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
8, programming -> ['pr', 'og', 'ra', 'm', 'm', 'i', 'n', 'g']
programming, 8 -> ['programm', 'ing']
9, code golf -> ['c', 'o', 'd', 'e', ' ', 'g', 'o', 'l', 'f']
code golf, 9 -> ['code golf']
4, 133tspeak -> ['133', 'ts', 'pe', 'ak']
133tspeak, 4 -> ['133t', 'spea', 'k']
```

Happy Coding!

Body:
Ruby, 119 bytes

->x,y{r=[t=0];x.to_s==x ?(r.push x[t...t+=y]while x[t]):x.times{r.push y[t...t+=y.size/x+(r[y.size%x]? 0:1)]};r[1..-1]}

And I take first place by 2 bytes...


问:
De-Snakify a String
A regular string looks like this:

```<code>Hello,IAmAStringSnake!
</code>```

And a string snake looks something like this:

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan
</code>```

Your Task

String snakes are dangerous, so you must make a program that takes a string snake as input and outputs it as a regular string.

Specifications

Input can be a multiline string or an array of strings.

Each line of the input will be padded with spaces to form a rectangular grid.

Characters in the snake can only connect to adjacent characters above, below, left or right of them (just like in the game Snake). They cannot go diagonal.

The snake characters will never be adjacent to another part of the snake, only the connected characters.

The first character of the string is the end character with the shortest Manhattan distance from the top-left corner of the input grid (i.e. the minimum number of moves it would take for a snake to go directly from the end character to the top-left corner). Both ends will never have the same distance.

The string can contain any ASCII character between code points 33 and 126 inclusive (no spaces or newlines).

The string will be between 2 and 100 characters long.

Shortest code in bytes wins.

Test Cases

(Input grid, followed by the output string)

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan

Hello,IAmAStringSnake!

----------

Python

Python

----------

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

ProgrammingPuzzlesAndCodeGolf

----------

   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z `ab P
"#$ 6789:; o [ _ c O
  % 5    < n \]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

----------

  tSyrep
  r    p
  in Sli
   g    Sile
   Snakes  n
Ser      ylt
a eh   ilS
fe w   t
   emo h
     Sre

SlipperyStringSnakesSilentlySlitherSomewhereSafe
</code>```

答:
JavaScript (ES6), 195

See explanation inside the test snippet

```<code>s=>[...s].map((c,i)=>{if(c>' '&([n=-1,1,o=-~s.search('\n'),-o].map(d=>n+=s[i+d]>' '&&!!(e=d)),n<1)&m>(w=i/o+i%o|0))for(m=w,r=c,p=i+e;r+=s[i=p],[e,o/e,-o/e].some(d=>s[p=i+(e=d)]>' '););},m=1/0)&&r
</code>```

Test

f=s=>[...s].map((c,i)=>{if(c>' '&([n=-1,1,o=-~s.search('\n'),-o].map(d=>n+=s[i+d]>' '&&!!(e=d)),n<1)&m>(w=i/o+i%o|0))for(m=w,r=c,p=i+e;r+=s[i=p],[e,o/e,-o/e].some(d=>s[p=i+(e=d)]>' '););},m=1/0)&&r

// Less golfed

u=s=>(
  o = -~s.search('\n'), // offset between lines
  m = 1/0, // current min manhattan distance, init at infinity
  // scan input looking for the 2 ends of the string
  [...s].map((c,i)=>{ // for each char c at position i
     if(c > ' ' // check if part of the string
        & ( [-1,1,o,-o] // scan in 4 directions and count neighbors
             .map(d=> n+=s[i+d]>' '&&!!(e=d), n=0), // remember direction in e
          n < 2) // if at end of string will have exactly 1 neighbor
        & (w = i/o + i%o |0) < m) // manhattan distance in w, must be less than current min
       // found one of the ends, follow the path and build the string in r
       for(m = w, r = c, p = i+e;
           r += s[i=p],
           [e,o/e,-o/e] // check 3 directions, avoiding to go back
           .some(d=>s[p=i+(e=d)]>' '); // save candidate position and direction in p and e
          ); // empty for body, all the work is inside the condition
  }),
  r
)

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

;[`Hel
  l      rin
  o,IAmASt g
           S
       !ekan`,
 `   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z \`ab P
"#$ 6789:; o [ _ c O
  % 5    < n \\]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ`].forEach(t=>{
  console.log(t+'\n\n'+f(t)+'\n')
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><pre id=O>``````

Title: De-Snakify a String

Body:
JavaScript (ES6), 195

See explanation inside the test snippet

s=>[...s].map((c,i)=>{if(c>' '&([n=-1,1,o=-~s.search('\n'),-o].map(d=>n+=s[i+d]>' '&&!!(e=d)),n<1)&m>(w=i/o+i%o|0))for(m=w,r=c,p=i+e;r+=s[i=p],[e,o/e,-o/e].some(d=>s[p=i+(e=d)]>' '););},m=1/0)&&r

Test

f=s=>[...s].map((c,i)=>{if(c>' '&([n=-1,1,o=-~s.search('\n'),-o].map(d=>n+=s[i+d]>' '&&!!(e=d)),n<1)&m>(w=i/o+i%o|0))for(m=w,r=c,p=i+e;r+=s[i=p],[e,o/e,-o/e].some(d=>s[p=i+(e=d)]>' '););},m=1/0)&&r

// Less golfed

u=s=>(
  o = -~s.search('\n'), // offset between lines
  m = 1/0, // current min manhattan distance, init at infinity
  // scan input looking for the 2 ends of the string
  [...s].map((c,i)=>{ // for each char c at position i
     if(c > ' ' // check if part of the string
        & ( [-1,1,o,-o] // scan in 4 directions and count neighbors
             .map(d=> n+=s[i+d]>' '&&!!(e=d), n=0), // remember direction in e
          n < 2) // if at end of string will have exactly 1 neighbor
        & (w = i/o + i%o |0) < m) // manhattan distance in w, must be less than current min
       // found one of the ends, follow the path and build the string in r
       for(m = w, r = c, p = i+e;
           r += s[i=p],
           [e,o/e,-o/e] // check 3 directions, avoiding to go back
           .some(d=>s[p=i+(e=d)]>' '); // save candidate position and direction in p and e
          ); // empty for body, all the work is inside the condition
  }),
  r
)

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

;[`Hel
  l      rin
  o,IAmASt g
           S
       !ekan`,
 `   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z \`ab P
"#$ 6789:; o [ _ c O
  % 5    < n \\]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ`].forEach(t=>{
  console.log(t+'\n\n'+f(t)+'\n')
  })

<pre id=O></pre>


问:
Shortest infinite loop producing no output
Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

Each submission must be a full program.

You must create the shortest infinite loop.

Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.

The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.

The program must not write anything to STDERR.

Feel free to use a language (or language version) even if it's newer than this challenge.
-Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. :D

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

This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.

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

There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.

Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)

Please feel free to post in the comments to tell me how this challenge could be  improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

```<code># Language name, X bytes
</code>```

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

```<code>#[Language name](http://link.to/the/language), X bytes
</code>```

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='
'+c.body.replace(OVERRIDE_REG,'')+'
'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery(''+lang+'').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;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">

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Jumper, 2 bytes

```<code>:0
</code>```

Move along, nothing to see here but a simple self-GOTO...

Body:
Jumper, 2 bytes

:0

Move along, nothing to see here but a simple self-GOTO...


答:
Retina, 16

```<code>^(.+)\1* \1+$
$1
</code>```

This doesn't use Euclid's algorithm at all - instead it finds the GCD using regex matching groups.

Try it online. - This example calculates GCD(8,12).

Input as 2 space-separated integers.  Note that the I/O is in unary.  If that is not acceptable, then we can do this:

Retina, 30

```<code>\d+
$*
^(.+)\1* \1+$
$1
1+
$.&
</code>```

Try it online.

As @MartinBüttner points out, this falls apart for large numbers (as is generally the case for anything unary).  At very a minimum, an input of INT_MAX will require allocation of a 2GB string.

Title: Greatest Common Divisor

Body:
Your task is to compute the greatest common divisor (GCD) of two given integers in as few bytes of code as possible.

You may write a program or function, taking input and returning output via any of our accepted standard methods (including STDIN/STDOUT, function parameters/return values, command-line arguments, etc.).

Input will be two non-negative integers. You should be able to handle either the full range supported by your language's default integer type, or the range [0,255], whichever is greater. You are guaranteed that at least one of the inputs will be non-zero.

You are not allowed to use built-ins that compute either the GCD or the LCM (least common multiple).

Standard code-golf rules apply.

Test Cases

```<code>0 2     => 2
6 0     => 6
30 42   => 6
15 14   => 1
7 7     => 7
69 25   => 1
21 12   => 3
169 123 => 1
20 142  => 2
101 202 => 101
</code>```

Body:
Retina, 16

^(.+)\1* \1+$
$1

This doesn't use Euclid's algorithm at all - instead it finds the GCD using regex matching groups.

Try it online. - This example calculates GCD(8,12).

Input as 2 space-separated integers.  Note that the I/O is in unary.  If that is not acceptable, then we can do this:

Retina, 30

\d+
$*
^(.+)\1* \1+$
$1
1+
$.&

Try it online.

As @MartinBüttner points out, this falls apart for large numbers (as is generally the case for anything unary).  At very a minimum, an input of INT_MAX will require allocation of a 2GB string.


问:
Golf the xᵗʰ root of x
While bored in high-school (when I was half my current age...), I found that \$f(x) = x^{x^{-1}}\$ had some interesting properties, including e.g. that the maximum \$f\$ for \$0 ≤ x\$ is \$f(e)\$, and that the binding energy per nucleon of an isotope can be approximated as \$6 × f(x ÷ 21)\$...

Anyway, write the shortest function or program that calculates the xth root of x for any number in your language's domain.

Examples cases

For all languages

```<code>     -1   >       -1
   ¯0.2   >    -3125
   ¯0.5   >        4
    0.5   >     0.25
      1   >        1
      2   >    1.414
      e   >    1.444
      3   >    1.442
    100   >    1.047
  10000   >    1.001
</code>```

For languages that handle complex numbers

```<code>   -2   >        -0.7071i
    i   >            4.81
   2i   >    2.063-0.745i
 1+2i   >   1.820-0.1834i
 2+2i   >   1.575-0.1003i
</code>```

For languages that handle infinities

```<code>-1/∞   >   0    (or ∞ or ̃∞)
   0   >   0    (or 1 or ∞)
 1/∞   >   0
   ∞   >   1
  -∞   >   1
</code>```

For languages that handle both infinities and complex numbers

```<code> -∞-2i   >   1      (or ̃∞)
</code>```

 ̃∞ denotes directed infinity.

答:
Pyth, 1 byte

```<code>@
</code>```

Pyth takes implicit input, so @ is really equivalent to @QQ, where Q is the evaluated input.

Try it online!

ContentLicense: CC BY-SA 4.0

Title: Golf the xᵗʰ root of x

Body:
Pyth, 1 byte

@

Pyth takes implicit input, so @ is really equivalent to @QQ, where Q is the evaluated input.

Try it online!


答:
Haskell, 131 bytes

```<code>import Data.Lists
q(d,m)=splitPlaces$(d+1<$[1..m])++[d,d..]
a#b|all(`elem`['0'..'9'])a=q(divMod(length b)$read a)b|1<2=q(read b,0)a
</code>```

Usage example:

```<code>*Main> "8" # "programming"
["pr","og","ra","m","m","i","n","g"]
*Main> "programming" # "8"
["programm","ing"]
</code>```

How it works: the main work is done by the helper function q which takes a pair of numbers (d,m) and a string s. It first builds a list of m times d+1 followed by infinite many d (e.g (1,3) -> [2,2,2,1,1,1,1,1,...]). It then uses splitPlaces to split s into chunks of lengths given by the list. splitPlaces stops if s runs out of elements, so an infinite list is fine.

The main function # checks which parameter is the number n / string str and calls q with either (div (length str) n, mod (length str) n) or (n, 0) plus str.

Body:
Haskell, 131 bytes

import Data.Lists
q(d,m)=splitPlaces$(d+1<$[1..m])++[d,d..]
a#b|all(`elem`['0'..'9'])a=q(divMod(length b)$read a)b|1<2=q(read b,0)a

Usage example:

*Main> "8" # "programming"
["pr","og","ra","m","m","i","n","g"]
*Main> "programming" # "8"
["programm","ing"]

How it works: the main work is done by the helper function q which takes a pair of numbers (d,m) and a string s. It first builds a list of m times d+1 followed by infinite many d (e.g (1,3) -> [2,2,2,1,1,1,1,1,...]). It then uses splitPlaces to split s into chunks of lengths given by the list. splitPlaces stops if s runs out of elements, so an infinite list is fine.

The main function # checks which parameter is the number n / string str and calls q with either (div (length str) n, mod (length str) n) or (n, 0) plus str.


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

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

The Rules

Each submission must be a full program.

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

The program must not write anything to STDERR.

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

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

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

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

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

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

For inspiration, check the Hello World Collection.

The Catalogue

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

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

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

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

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

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

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

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

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

/* Configuration */

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

/* App */

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

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

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

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

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

getAnswers();

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

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

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

function process() {
  var valid = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

table thead {
  font-weight: bold;
}

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
Cheddar, 20 bytes

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

Yes!!!!!

I have been waiting for this day a long time. After days of banging my head on my desk trying to get Cheddar to work. I have finally made a Cheddar REPL. The REPL is very alpha, so if you'd like to test it out, ping me in chat @Downgoat

Update: To run simply go to cheddar.vihan.org and follow the download instructions

Update 2: Use the experimental online REPL at: cheddar.vihan.org/repl

Title: "Hello, World!"

Body:
Cheddar, 20 bytes

print"Hello, World!"

Yes!!!!!

I have been waiting for this day a long time. After days of banging my head on my desk trying to get Cheddar to work. I have finally made a Cheddar REPL. The REPL is very alpha, so if you'd like to test it out, ping me in chat @Downgoat

Update: To run simply go to cheddar.vihan.org and follow the download instructions

Update 2: Use the experimental online REPL at: cheddar.vihan.org/repl


答:
MATL, 7 bytes

```<code>pG1$Zm/
</code>```

Try it Online!

Explanation

Since we can't explicitly use the builtin GCD function (Zd in MATL), I have exploited the fact that the least common multiple of a and b times the greatest common denominator of a and b is equal to the product of a and b.

```<code>p       % Grab the input implicitly and multiply the two elements
G       % Grab the input again, explicitly this time
1$Zm    % Compute the least-common multiple
/       % Divide the two to get the greatest common denominator
</code>```

Title: Greatest Common Divisor

Body:
MATL, 7 bytes

pG1$Zm/

Try it Online!

Explanation

Since we can't explicitly use the builtin GCD function (Zd in MATL), I have exploited the fact that the least common multiple of a and b times the greatest common denominator of a and b is equal to the product of a and b.

p       % Grab the input implicitly and multiply the two elements
G       % Grab the input again, explicitly this time
1$Zm    % Compute the least-common multiple
/       % Divide the two to get the greatest common denominator


问:
Evolution of OEIS
In this challenge, the goal is to recreate the On-Line Encyclopedia of Integer Sequences one sequence at a time.  Similar to the Evolution of Hello World, each answer depends on a previous answer.

Over time, this challenge will create a "family tree" of the OEIS sequences.  It is simple to add on to this tree.

Find a previous answer, which can be at any depth N of the tree.

Determine the first N numbers generated by that answer's sequence.

Find a sequence in OEIS which starts with those same numbers and which hasn't been used before.

Write a program to generate this new sequence you just found.

Submit your answer as depth N+1

Since the level of your answer influences scoring, you should always add your answer onto the tree at the deepest level possible.  If you cannot fit your answer anywhere on the tree, you can start a new branch of the tree and put your answer as depth 1.

Answer Requirements

There are a few ways to output a sequence.

The first option is to write a program or function that inputs a number (from STDIN or as an argument) and returns the Nth number in your chosen sequence.  You can assume that the sequence will be defined for N and that N and S_N are "reasonably sized" (so it won't cause overflows).  You can also use any reasonable indexing, such as 0 indexing, 1 indexing, or the indexing listed under "offset" on the sequence's OEIS page, that doesn't matter.  The term produced by the first index must match the first term of the OEIS entry.

The second option is to write a program or function that inputs a number and returns the first N terms of the sequence.  The first terms of the output must be the first terms of the OEIS entry (you can't leave off the first few terms).  Consecutive terms must be delimited by arbitrary strings of non-digit characters, so 0,1  1.2/3,5;8,11 works but 011235811 does not count.

The third option is to create a program that outputs a continuous stream of numbers.  Similarly to the second option, there must be delimiters between consecutive terms.

Your answer should contain a header like this to aid Stack Snippet parsing:

```<code> # [language], [number] bytes, depth [number], A[new sequence] from A[old sequence]
</code>```

Your answer should contain the code to generate the sequence, along with the first few terms that any descendants will need to contain.  These few terms should be preceded by the exact word terms: so that the controller can use them as part of the tree diagram.  It is also recommended to write a description of the sequence you chose.

If your post is a depth 1 answer and thus has no ancestor, you should simply omit the from A[number] in your header.

Here is an example answer:

```<code># Perl, 26 bytes, depth 3, A026305 from A084912

    various code here
    and here

The next answer should match the following terms:

    1, 4, 20

This sequence is .... and does ....
</code>```

Chaining Requirements

In order to make this challenge more fair, there are restrictions on which answers you can chain yours to. These rules are mostly to prevent a single person from creating a whole branch of the tree by themselves or owning a lot of "root" nodes.

You cannot chain to yourself.

You cannot directly chain two of your answers to the same ancestor.

You cannot make more than one "Level 1" answer.

Also, if the ancestor was of depth N, your post must have depth N+1, even if more than the required number of terms agree.

Scoring

Your score as a user is the sum of the scores of all of your answers.  The score of a single answer is determined by the following formula:

```<code>Answer Score = Sqrt(Depth) * 1024 / (Length + 256)
</code>```

This scoring system should encourage users to submit a large number of deeper answers.  Shorter answers are preferred over longer answers, but depth has a much larger influence.

Below is a stack snippet that generates a leaderboard as well as a tree diagram of all of the answers.  I would like to thank Martin Büttner and d3noob as the sources for a lot of this code.  You should click "Full screen" to see the complete results.

function answersUrl(t){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+t+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(t){answers.push.apply(answers,t.items),t.has_more?getAnswers():process()}})}function shouldHaveHeading(t){var e=!1,r=t.body_markdown.split("\n");try{e|=/^#/.test(t.body_markdown),e|=["-","="].indexOf(r[1][0])>-1,e&=LANGUAGE_REG.test(t.body_markdown)}catch(a){}return e}function shouldHaveScore(t){var e=!1;try{e|=SIZE_REG.test(t.body_markdown.split("\n")[0])}catch(r){}return e}function getAuthorName(t){return t.owner.display_name}function decodeEntities(t){return $("<textarea>").html(t).text()}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.reverse();var t={},e=[],r=1,a=null,n=1,s=[];answers.forEach(function(t){var r=t.body_markdown.split("\n")[0],a=getAuthorName(t),n=r.match(SEQUENCE_REG)[0];n=n.trim();var o="from A000000";PARENT_REG.test(r)&&(o=r.match(PARENT_REG)[0]),o=o.substring(5).trim(),"A000000"==o&&(o="OEIS");var i="";SEQDATA_REG.test(t.body_markdown)&&(i=t.body_markdown.match(SEQDATA_REG)[1]);for(var u=!0,c=0;c<e.length;++c)u=u&&!(e[c]===n);for(var l=!0,c=0;c<e.length;++c)l=!(!l||e[c]===n||e[c]===n+a||e[c]===o+a);e.push(n),e.push(n+a),e.push(o+a),u&&data.push({name:n,parent:o,term:i+" : ",author:decodeEntities(a),URL:t.share_link}),l&&s.push(t)}),answers.sort(function(t,e){var r=t.body_markdown.split("\n")[0].match(SEQUENCE_REG),a=e.body_markdown.split("\n")[0].match(SEQUENCE_REG);return a>r?-1:r>a?1:void 0}),answers.forEach(function(e){var o=e.body_markdown.split("\n")[0],i=(o.match(NUMBER_REG)[0],(o.match(SIZE_REG)||[0])[0]),u=parseInt((o.match(DEPTH_REG)||[0])[0]).toString(),c=o.match(SEQUENCE_REG)[0],l="from A000000";PARENT_REG.test(o)&&(l=o.match(PARENT_REG)[0]),l=l.substring(5);var d=o.match(LANGUAGE_REG)[1];d.indexOf("]")>0&&(d=d.substring(1,d.indexOf("]")));for(var p=getAuthorName(e),E=!1,h=0;h<s.length;++h)E=E||s[h]===e;if(E){var f=jQuery("#answer-template").html();i!=a&&(n=r),a=i,++r;var m=1024*Math.pow(parseInt(u),.5)/(parseInt(i)+256);f=f.replace("{{SEQUENCE}}",c).replace("{{SEQUENCE}}",c).replace("{{NAME}}",p).replace("{{LANGUAGE}}",d).replace("{{SIZE}}",i).replace("{{DEPTH}}",u).replace("{{LINK}}",e.share_link),f=jQuery(f),jQuery("#answers").append(f),t[p]=t[p]||{lang:d,user:p,size:"0",numanswers:"0",link:e.share_link},t[p].size=(parseFloat(t[p].size)+m).toString(),t[p].numanswers=(parseInt(t[p].numanswers)+1).toString()}});var o=[];for(var i in t)t.hasOwnProperty(i)&&o.push(t[i]);o.sort(function(t,e){return parseFloat(t.size)>parseFloat(e.size)?-1:parseFloat(t.size)<parseFloat(e.size)?1:0});for(var u=0;u<o.length;++u){var c=jQuery("#language-template").html(),i=o[u];c=c.replace("{{RANK}}",u+1+".").replace("{{NAME}}",i.user).replace("{{NUMANSWERS}}",i.numanswers).replace("{{SIZE}}",i.size),c=jQuery(c),jQuery("#languages").append(c)}createTree()}function createTree(){function t(){var t=i.nodes(root).reverse(),e=i.links(t);t.forEach(function(t){t.y=180*t.depth});var r=c.selectAll("g.node").data(t,function(t){return t.id||(t.id=++o)}),a=r.enter().append("g").attr("class","node").attr("transform",function(t){return"translate("+t.y+","+t.x+")"});a.append("a").attr("xlink:href",function(t){return t.URL}).append("circle").attr("r",10).style("fill","#fff"),a.append("text").attr("x",function(){return 0}).attr("y",function(){return 20}).attr("dy",".35em").attr("text-anchor",function(){return"middle"}).text(function(t){return t.term+t.name}).style("fill-opacity",1),a.append("text").attr("x",function(){return 0}).attr("y",function(){return 35}).attr("dy",".35em").attr("text-anchor",function(){return"middle"}).text(function(t){return t.author}).style("fill-opacity",1);var n=c.selectAll("path.link").data(e,function(t){return t.target.id});n.enter().insert("path","g").attr("class","link").attr("d",u)}var e=data.reduce(function(t,e){return t[e.name]=e,t},{}),r=[];data.forEach(function(t){var a=e[t.parent];a?(a.children||(a.children=[])).push(t):r.push(t)});var a={top:20,right:120,bottom:20,left:120},n=3203-a.right-a.left,s=4003-a.top-a.bottom,o=0,i=d3.layout.tree().size([s,n]),u=d3.svg.diagonal().projection(function(t){return[t.y,t.x]}),c=d3.select("body").append("svg").attr("width",n+a.right+a.left).attr("height",s+a.top+a.bottom).append("g").attr("transform","translate("+a.left+","+a.top+")");root=r[0],t(root)}var QUESTION_ID=49223,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",data=[{name:"OEIS",parent:"null",term:"",author:"",URL:"https://oeis.org/"}],answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*,)/,DEPTH_REG=/\d+, A/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/,SEQUENCE_REG=/A\d+/,PARENT_REG=/from\s*A\d+/,SEQDATA_REG=/terms:\s*(?:(?:-)?\d+,\s*)*((?:-)?\d+)/;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align: left !important}#answer-list{padding: 10px; width: 550px; float: left;}#language-list{padding: 10px; width: 290px; float: left;}table thead{font-weight: bold;}table td{padding: 5px;}.node circle{fill: #fff; stroke: steelblue; stroke-width: 3px;}.node text{font: 12px sans-serif;}.link{fill: none; stroke: #ccc; stroke-width: 2px;}</code>```

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

Sequence List

 Sequence	Author	Language	Size	Depth

Leaderboard

 Rank	User	Answers	Score

 {{SEQUENCE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	{{DEPTH}}	Link

 {{RANK}}	{{NAME}}	{{NUMANSWERS}}	{{SIZE}}

```

答:
Mathematica, 98 bytes, depth 10, A175835 from A083912

```<code>Count[Normal@SeriesData[x,0,Reverse@RealDigits[EulerGamma,10,#][[1]],0,#,1]~NRoots~x,_Real,{1,2}]&
</code>```

Pretty random sequence definition. Makes more sense if you read the sequence page. The next answer should start with the terms:

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

Title: Evolution of OEIS

Body:
Mathematica, 98 bytes, depth 10, A175835 from A083912

Count[Normal@SeriesData[x,0,Reverse@RealDigits[EulerGamma,10,#][[1]],0,#,1]~NRoots~x,_Real,{1,2}]&

Pretty random sequence definition. Makes more sense if you read the sequence page. The next answer should start with the terms:

0, 1, 0, 1, 0, 1, 0, 1, 0, 1


问:
Print your code backwards - reverse quine
Write a program that prints its own source code out backwards, in other words an eniuq.

Scoring:

+50 if you use pull data from the Internet.

+25 if you read your own source code.

+1 point per character

Lowest score wins.

Rules:

No using other files (e.g. reverse.txt)

Minimum code length is two characters.

Your program cannot be a palindrome.

答:
Bash, 8 + 25 for reading source = 33 bytes

```<code>rev "$0"
</code>```

31 for no space in path to file

```<code>rev $0
</code>```

Body:
Bash, 8 + 25 for reading source = 33 bytes

rev "$0"

31 for no space in path to file

rev $0


问:
Diamondize a Matrix
Given a matrix, output a representation of the matrix where the top left element is on top, the anti-diagonal is the central row and the bottom right element is at the bottom.

For example, consider the following matrix:

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

The diamond version of this matrix is:

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

Inputs and outputs

An input matrix will be given as a list of lists (or anything similar in your language of choice). The output shall be a list of lists as well.

The matrices will only contain positive integers.

The input matrix will not necessarily be square.

The input matrix will be at least 1×1.

Test Cases

```<code>Input:  [[1]]
Output: [[1]]

Input:  [[1,2],[3,4]]
Output: [[1],[3,2],[4]]

Input:  [[1,2,3],[4,5,6]]
Output: [[1],[4,2],[5,3],[6]]

Input:  [[11,2,5],[3,99,3],[4,8,15],[16,23,42]]
Output: [[11],[3,2],[4,99,5],[16,8,3],[23,15],[42]]
</code>```

Scoring

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

答:
Haskell, <s>83</s> 82 bytes

```<code>r=zip[0..]
\o->fst$span(any(>0))[reverse[e|(x,t)<-r o,(v,e)<-r t,x+v==a]|a<-[0..]]
</code>```

nimi saved a byte. Thanks!

Title: Diamondize a Matrix

Body:
Haskell, <s>83</s> 82 bytes

r=zip[0..]
\o->fst$span(any(>0))[reverse[e|(x,t)<-r o,(v,e)<-r t,x+v==a]|a<-[0..]]

nimi saved a byte. Thanks!


答:
i386 (x86-32) machine code, 8 bytes  (9B for unsigned)

+1B if we need to handle b = 0 on input.

amd64 (x86-64) machine code, 9 bytes (10B for unsigned, or <s>14B</s> 13B for 64b integers signed or unsigned)

<s>10</s> 9B for unsigned on  amd64 that breaks with either input = 0

Inputs are 32bit non-zero signed integers in eax and ecx.  Output in eax.

```<code>## 32bit code, signed integers:  eax, ecx
08048420 <gcd0>:
 8048420:       99                      cdq               ; shorter than xor edx,edx
 8048421:       f7 f9                   idiv   ecx
 8048423:       92                      xchg   edx,eax    ; there's a one-byte encoding for xchg eax,r32.  So this is shorter but slower than a mov
 8048424:       91                      xchg   ecx,eax    ; eax = divisor(from ecx), ecx = remainder(from edx), edx = quotient(from eax) which we discard
    ; loop entry point if we need to handle ecx = 0
 8048425:       41                      inc    ecx        ; saves 1B vs. test/jnz in 32bit mode
 8048426:       e2 f8                   loop   8048420 <gcd0>
08048428 <gcd0_end>:
 ; 8B total
 ; result in eax: gcd(a,0) = a
</code>```

This loop structure fails the test-case where ecx = 0.  (div causes a #DE hardware execption on divide by zero.   (On Linux, the kernel delivers a SIGFPE (floating point exception)).  If the loop entry point was right before the inc, we'd avoid the problem.  The x86-64 version can handle it for free, see below.

Mike Shlanta's answer was the starting point for this.  My loop does the same thing as his, but for signed integers because cdq is one byter shorter than xor edx,edx.  And yes, it does work correctly with one or both inputs negative.  Mike's version will run faster and take less space in the uop cache (xchg is 3 uops on Intel CPUs, and loop is really slow on most CPUs), but this version wins at machine-code size.

I didn't notice at first that the question required unsigned 32bit.  Going back to xor edx,edx instead of cdq would cost one byte.  div is the same size as idiv, and everything else can stay the same (xchg for data movement and inc/loop still work.)

Interestingly, for 64bit operand-size (rax and rcx), signed and unsigned versions are the same size.  The signed version needs a REX prefix for cqo (2B), but the unsigned version can still use 2B xor edx,edx.

In 64bit code, inc ecx is 2B: the single-byte inc r32 and dec r32 opcodes were repurposed as REX prefixes.  inc/loop doesn't save any code-size in 64bit mode, so you might as well test/jnz.  Operating on 64bit integers adds another one byte per instruction in REX prefixes, except for loop or jnz.  It's possible for the remainder to have all zeros in the low 32b (e.g. gcd((2^32), (2^32 + 1))), so we need to test the whole rcx and can't save a byte with test ecx,ecx.  However, the slower jrcxz insn is only 2B, and we can put it at the top of the loop to handle ecx=0 on entry:

```<code>## 64bit code, unsigned 64 integers:  rax, rcx
0000000000400630 <gcd_u64>:
  400630:       e3 0b                   jrcxz  40063d <gcd_u64_end>   ; handles rcx=0 on input, and smaller than test rcx,rcx/jnz
  400632:       31 d2                   xor    edx,edx                ; same length as cqo
  400634:       48 f7 f1                div    rcx                      ; REX prefixes needed on three insns
  400637:       48 92                   xchg   rdx,rax
  400639:       48 91                   xchg   rcx,rax
  40063b:       eb f3                   jmp    400630 <gcd_u64>
000000000040063d <gcd_u64_end>:
## 0xD = 13 bytes of code
## result in rax: gcd(a,0) = a
</code>```

Full runnable test program including a main that runs printf("...", gcd(atoi(argv[1]), atoi(argv[2])) ); source and asm output on the Godbolt Compiler Explorer, for the 32 and 64b versions.  Tested and working for 32bit (-m32), 64bit (-m64), and the x32 ABI (-mx32).

Also included: a version using repeated subtraction only, which is 9B for unsigned, even for x86-64 mode, and can take one of its inputs in an arbitrary register.  However, it can't handle either input being 0 on entry (it detect when sub produces a zero, which x - 0 never does).

GNU C inline asm source for the 32bit version (compile with gcc -m32 -masm=intel)

```<code>int gcd(int a, int b) {
    asm (// ".intel_syntax noprefix\n"
        // "jmp  .Lentry%=\n" // Uncomment to handle div-by-zero, by entering the loop in the middle.  Better: `jecxz / jmp` loop structure like the 64b version
        ".p2align 4\n"                  // align to make size-counting easier
         "gcd0:   cdq\n\t"              // sign extend eax into edx:eax.  One byte shorter than xor edx,edx
         "        idiv    ecx\n"
         "        xchg    eax, edx\n"   // there's a one-byte encoding for xchg eax,r32.  So this is shorter but slower than a mov
         "        xchg    eax, ecx\n"   // eax = divisor(ecx), ecx = remainder(edx), edx = garbage that we will clear later
         ".Lentry%=:\n"
         "        inc     ecx\n"        // saves 1B vs. test/jnz in 32bit mode, none in 64b mode
         "        loop    gcd0\n"
        "gcd0_end:\n"
         : /* outputs */  "+a" (a), "+c"(b)
         : /* inputs */   // given as read-write outputs
         : /* clobbers */ "edx"
        );
    return a;
}
</code>```

Normally I'd write a whole function in asm, but GNU C inline asm seems to be the best way to include a snippet which can have in/outputs in whatever regs we choose.  As you can see, GNU C inline asm syntax makes asm ugly and noisy.  It's also a really difficult way to learn asm.

It would actually compile and work in .att_syntax noprefix mode, because all the insns used are either single/no operand or xchg.  Not really a useful observation.

Title: Greatest Common Divisor

Body:
i386 (x86-32) machine code, 8 bytes  (9B for unsigned)

+1B if we need to handle b = 0 on input.

amd64 (x86-64) machine code, 9 bytes (10B for unsigned, or <s>14B</s> 13B for 64b integers signed or unsigned)

<s>10</s> 9B for unsigned on  amd64 that breaks with either input = 0

Inputs are 32bit non-zero signed integers in eax and ecx.  Output in eax.

## 32bit code, signed integers:  eax, ecx
08048420 <gcd0>:
 8048420:       99                      cdq               ; shorter than xor edx,edx
 8048421:       f7 f9                   idiv   ecx
 8048423:       92                      xchg   edx,eax    ; there's a one-byte encoding for xchg eax,r32.  So this is shorter but slower than a mov
 8048424:       91                      xchg   ecx,eax    ; eax = divisor(from ecx), ecx = remainder(from edx), edx = quotient(from eax) which we discard
    ; loop entry point if we need to handle ecx = 0
 8048425:       41                      inc    ecx        ; saves 1B vs. test/jnz in 32bit mode
 8048426:       e2 f8                   loop   8048420 <gcd0>
08048428 <gcd0_end>:
 ; 8B total
 ; result in eax: gcd(a,0) = a

This loop structure fails the test-case where ecx = 0.  (div causes a #DE hardware execption on divide by zero.   (On Linux, the kernel delivers a SIGFPE (floating point exception)).  If the loop entry point was right before the inc, we'd avoid the problem.  The x86-64 version can handle it for free, see below.

Mike Shlanta's answer was the starting point for this.  My loop does the same thing as his, but for signed integers because cdq is one byter shorter than xor edx,edx.  And yes, it does work correctly with one or both inputs negative.  Mike's version will run faster and take less space in the uop cache (xchg is 3 uops on Intel CPUs, and loop is really slow on most CPUs), but this version wins at machine-code size.

I didn't notice at first that the question required unsigned 32bit.  Going back to xor edx,edx instead of cdq would cost one byte.  div is the same size as idiv, and everything else can stay the same (xchg for data movement and inc/loop still work.)

Interestingly, for 64bit operand-size (rax and rcx), signed and unsigned versions are the same size.  The signed version needs a REX prefix for cqo (2B), but the unsigned version can still use 2B xor edx,edx.

In 64bit code, inc ecx is 2B: the single-byte inc r32 and dec r32 opcodes were repurposed as REX prefixes.  inc/loop doesn't save any code-size in 64bit mode, so you might as well test/jnz.  Operating on 64bit integers adds another one byte per instruction in REX prefixes, except for loop or jnz.  It's possible for the remainder to have all zeros in the low 32b (e.g. gcd((2^32), (2^32 + 1))), so we need to test the whole rcx and can't save a byte with test ecx,ecx.  However, the slower jrcxz insn is only 2B, and we can put it at the top of the loop to handle ecx=0 on entry:

## 64bit code, unsigned 64 integers:  rax, rcx
0000000000400630 <gcd_u64>:
  400630:       e3 0b                   jrcxz  40063d <gcd_u64_end>   ; handles rcx=0 on input, and smaller than test rcx,rcx/jnz
  400632:       31 d2                   xor    edx,edx                ; same length as cqo
  400634:       48 f7 f1                div    rcx                      ; REX prefixes needed on three insns
  400637:       48 92                   xchg   rdx,rax
  400639:       48 91                   xchg   rcx,rax
  40063b:       eb f3                   jmp    400630 <gcd_u64>
000000000040063d <gcd_u64_end>:
## 0xD = 13 bytes of code
## result in rax: gcd(a,0) = a

Full runnable test program including a main that runs printf("...", gcd(atoi(argv[1]), atoi(argv[2])) ); <a href="http://gcc.godbolt.org/#compilers:!((compiler:g510,options:%27-xc+-Wall+-Wextra+-std%3Dgnu11+-fverbose-asm+-O3+-m32+-masm%3Dintel+-mtune%3Dintel%27,sourcez:PTAEEMBtNBLA7Azk0BXRBTAJhATh0DWAFwAsNdREEBzSDAWgHsAHC8eHJygDwGNSNADRUmoMrEQQ%2BxVFEgBPUAHduAaynKSpUADpwxYgH1EC%2BMXA9Q8VvgBmsHgCgQoAEKpioPkwC2LWHoVbVAGX3BEXwBeBGIMGAAjDD5wdAIyAiYMygA3CmomeFAACgQ%2BSFQsbFA7blB7Cgx4PgwAShUmVEgcBPxwNV0XMDDZeAwY83jQGib2OKlIQppQADkAeQAFKQREOPAuO1Bw%2BCVqeDpGBIU41c3EEVrKDNAEhHBcJU7iFk8nIdAAMJ%2BAL0KQcHCqXAabzcfAyRQ1OphADMACYSmjXl4fFVWiI6gA2AAsWJhVQAXKFfDw0aAkb5iYMnLsDLA%2BHBzNM%2BFhSpzwCJYi92gBvJygcUQSIlVwAIl0sXiJjMFisNhY9kcAB14DKxRLQDKAFb%2BcW6AAyTWIHwApFFtTLQK4AKrNPy%2BS3iMSkcFBLCwHIMK4MABeFCYIiuhEmuFo4nIoEWrA5cYIvlgWCw9F04rcGEMFEpAANDckeMHHaBjSxCwmmEndrhUDJUPgE7A1Ol48SEqA8rgCvA/vr9XKWKioLAaEUifaAJDDhfD1wTqeeo79AjUUMMHyocyxjARWAUPWLmU0bkABkp4u5AEdtZriA7FwvXNRVxgeHFOIRLBziDEbAeHJQ8eGzUA1jGF5rk3UhuDiJ5vSKHg6mAoRgNPBcXwXdN/X1Ut7Sw4ccOHfhBAIywRGA%2B0JVcbIMAAcjBOkxkDWCoxxWNHlAcjljAoRcDRCCAGUxAkbYpEQeDcEQl5PCoRZlAoOMOAgI4mByYiR1fPjKJ4ai%2BB4WjxVcMDQCiUA/RySRuGKUs8UIIyLPqDBwgQKpcHsrAeEc4CXJod4EnAGZVK8ZTgmgbx6HeBMDBPec5QtcwbSickiNfA1XzKYdCJ1V933APIpAARjcXtEGzeZiGAQ14HLBBQExEgNKqEQbGgxru1ajBtIlUj9UTFh9QvLBLwys9RsvIwmiwdKdT68VKWAAAqOlPB%2BYgpBWsADQAanAB1inARyZT2vgZWKBJWkW0BlrWhBNu23bHTAGh/SaSVXP2BhlBjG4vie277uipgEiSftQB2g1gN1V9WgAbiw/BZFwIpwCRgBfP4AGJYDsKpDiMIxwF8LBiWJoY8eaCoqlAAAeXY/XMXRSAAPicYgFDYQm0CQScxhwRZzlrEWukgJHXBpdEAEE3AASRKMJpfaXZAhgb0pGarxhZoQZnTOZZUFiCmvHe4rQBYBDwFeSASCUZR3ngWgpDsXA/EtmNzEOJIUjSOBiGYvmP0F0XlkasJiR6kREDEFqsCYDBkEYrxwmIAQU1Aa1xeTdVYkOR406oK0Xb%2BFliDZNAotG1BiWKHP%2BSrxIRSwiJfGlMA5QVSAlXMf81Q1YyFsy0dxzt1cZ2H19z25Ixa6Jea4en19DVwIzy3FUa54p2aTMKi2yoqqqk68NeDLPis6uDERwVAZDMyT%2BojKiS9WI5TbEUoN2MF6kfdLqAiPkMI%2BUfM%2BfUrhQzu0IN%2BWa9R/yxDELgHy5JcBUSoKTTcsBQxfT4HeMQxQABKABRAAGt4LAd4bp/0XNZYcZ8Jpnl0gIZYEpUEGXqCA/K4CwAMSDuAVilwOJNC4iLHiekBJCVRKJcSpBJBwCkjJOSCQFKICUipMgal%2BG%2BE0rdAaEo9KsLQfQrhdEwBsJctZWyXkz6OQvpZfA7lOAUGKEg3yIhXEBSCiFTsBgVAEC0FFcoh5KCQHirgXRK8TQjVnvPBhJEt7zxmpwRewNHRrUBp4Z64ozqHRKCdEQZ0LpXSoa%2BEGj1MlQxeq4c2n0IjfSwL9f6mQNqZNSatUG4N8iVJhj5JeC5EbIzzC2dGWMnA41mvjP4zILAV3ZHuEO1Qt7SVCX3eu/MpzVEbvMgW1RrqgFFPqNuHcDTykmD3UwfdVS2AwA4IeL5XA%2BH8IEfxIQwhtwmHESAi1R4rmnHEkcU0jCbBScvfRACJToRolPbC%2BpaEEQSHc75%2BptE5FylRDACL/n9WRZpXKCLgGItBeKaq8KDIYsJYwiUV9hyAs2ERWcM8xpAo2Ekua9K7r7VycdU6e0EiXWuk4ec5JBUcplLDQVAz9Qo2GRAUZThtkbJwEs1ACQ1kLJwFs9Zoc9kHNMX4qyeZkjhXIEUHsK1fZ%2BCTmtSB4ZrBZDgIcEgfDIB9CwEoG1WEHnkD4GoT%2BAd1pbXTJ2AgRyWDvC8LHfVKQihqyiiS54WRyBfz3DIWAhRNAhFfuUraWF8YlAAIQnVcqjU1SN9R5uKPmvZ0q0ays9WAL8Vp%2BH4DvMbBxlpECUnAPml%2BEYe2XlblKYospTmfN7iqO16oblamhSRXQY5fmgEnnozKerF2AXXB2KgWDGC7n3CLQ81ATzT1GogFVtp5pPj6SRW8USs4AG0EgAF1qKWFAaRd8Kq76NA5LsQ8BxvAmhbW2x%2BmiMxrnwH2TA/rGrPEQI7YavQOACCRZWcABBzQ2Hg%2BAFgtp32oYMQJB9z733cO8BwFONRJwtmaV4fhjslAbuw8NLQZBAO4sanYDAylKBXHmN8zDTBmMXvw6Cs9PZxTWkfS%2Bv8Q8r2obqgQTe3JxN4dnQClTKrWUifUxKEGGStrdM5UdfJoBpP7VwPy9or0XhWUTsnLw3o8hriSMmUsMcxD0DNnwOZ0HlDejiH2f1jtzCIEWmU%2BAT0jM2ZqejKQrrGkkFo0DUpaSOkQ2eotSVrChm1oxk4bGuMyi0wIIzYgfomCsw5tTcolRStMztgkKrYzit1YZhETAslmuCkcbyOjuALwiAEO8Fa7waA5HvU%2Bm6urxQdYoMQY6A2%2BBs1RNl8Ugp%2BGWQMEwWAi3xv3pKlNiMLltu7bGxN1EU2y0Sjzt7YojLijWiwCIJ77RLJPbpJQbOn2s6oHtDfCMIhRrHSENdIHs9lkcAsCDsHXIsAmBVTD9oAy8YExuaAYmpNyZEkpvqHOoSXINkAuLPbE3DsiBWE6M0ZoRCXkcpAHslkiedGgKT%2B9l2KdU5p6AOn13xS3eIHYe7wPrTQFQC9sXb2s5i9AFz/7cURAM/B1geexRQlCAZ8jpG4zOCTKlblool5RlAAAA%3D)),filterAsm:(binary:!t,commentOnly:!t,directives:!t,intel:!t,labels:!t),version:3" rel="noreferrer">source and asm output on the Godbolt Compiler Explorer, for the 32 and 64b versions.  Tested and working for 32bit (-m32), 64bit (-m64), and the x32 ABI (-mx32).

Also included: a version using repeated subtraction only, which is 9B for unsigned, even for x86-64 mode, and can take one of its inputs in an arbitrary register.  However, it can't handle either input being 0 on entry (it detect when sub produces a zero, which x - 0 never does).

GNU C inline asm source for the 32bit version (compile with gcc -m32 -masm=intel)

int gcd(int a, int b) {
    asm (// ".intel_syntax noprefix\n"
        // "jmp  .Lentry%=\n" // Uncomment to handle div-by-zero, by entering the loop in the middle.  Better: `jecxz / jmp` loop structure like the 64b version
        ".p2align 4\n"                  // align to make size-counting easier
         "gcd0:   cdq\n\t"              // sign extend eax into edx:eax.  One byte shorter than xor edx,edx
         "        idiv    ecx\n"
         "        xchg    eax, edx\n"   // there's a one-byte encoding for xchg eax,r32.  So this is shorter but slower than a mov
         "        xchg    eax, ecx\n"   // eax = divisor(ecx), ecx = remainder(edx), edx = garbage that we will clear later
         ".Lentry%=:\n"
         "        inc     ecx\n"        // saves 1B vs. test/jnz in 32bit mode, none in 64b mode
         "        loop    gcd0\n"
        "gcd0_end:\n"
         : /* outputs */  "+a" (a), "+c"(b)
         : /* inputs */   // given as read-write outputs
         : /* clobbers */ "edx"
        );
    return a;
}

Normally I'd write a whole function in asm, but GNU C inline asm seems to be the best way to include a snippet which can have in/outputs in whatever regs we choose.  As you can see, GNU C inline asm syntax makes asm ugly and noisy.  It's also a really difficult way to learn asm.

It would actually compile and work in .att_syntax noprefix mode, because all the insns used are either single/no operand or xchg.  Not really a useful observation.


答:
C# (LINQPAD) - 335 bytes

```<code>var y=Util.ReadLine().Split(',');int x,j=0;var t=int.TryParse(y[0].Trim(),out x);x=x==0?int.Parse(y[1].Trim()):x;var i=t?y[1].Trim():y[0];var z="";if(!t){while(i.Substring(j).Length>x){z+=i.Substring(j).Length>x?i.Substring(j,x)+", ":"";j+=x;}z+=i.Substring(j);}else z=string.Join(", ",i.Split(x).Select(s=>string.Concat(s)));z.Dump();
</code>```

The input reading part took up a bit of space. Winner of longest answer.

Usage #1:

```<code>$ 3, helloworld

>> hell, owo, rld
</code>```

Usage #2:

```<code>$ helloworld, 3

>>hel, low, orl, d
</code>```

Body:
C# (LINQPAD) - 335 bytes

var y=Util.ReadLine().Split(',');int x,j=0;var t=int.TryParse(y[0].Trim(),out x);x=x==0?int.Parse(y[1].Trim()):x;var i=t?y[1].Trim():y[0];var z="";if(!t){while(i.Substring(j).Length>x){z+=i.Substring(j).Length>x?i.Substring(j,x)+", ":"";j+=x;}z+=i.Substring(j);}else z=string.Join(", ",i.Split(x).Select(s=>string.Concat(s)));z.Dump();

The input reading part took up a bit of space. Winner of longest answer.

Usage #1:

$ 3, helloworld

>> hell, owo, rld

Usage #2:

$ helloworld, 3

>>hel, low, orl, d


问:
Find the first word starting with each letter
Given a string, find the first word starting with each letter (case insensitive).

Sample

Using Ferulas flourish in gorgeous gardens. as input:

```<code>"Ferulas flourish in gorgeous gardens."
 ^^^^^^^          ^^ ^^^^^^^^
 |                |  |
 |                |  --> is the first word starting with `g`
 |                --> is the first word starting with `i`
 --> is the first word starting with `f`
</code>```

Then, the output for this sample should be the matched words joined by one single space:

```<code>"Ferulas in gorgeous"
</code>```

Challenge

Both input and output must be a string representation, or the closest alternative in your language.

Program or function allowed.

You can consider a word being at least one of: lowercase or uppercase letters, digits, underscore.

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

Another samples:

```<code>input: "Take all first words for each letter... this is a test"
output: "Take all first words each letter is"
</code>```

```<code>input: "Look ^_^ .... There are 3 little dogs :)"
output: "Look _ There are 3 dogs"
</code>```

```<code>input: "...maybe some day 1 plus 2 plus 20 could result in 3"
output: "maybe some day 1 plus 2 could result in 3"
</code>```

答:
Seriously, 43 bytes

```<code>6╙¬▀'_+,;)-@s`;0@Eùk`M┬i;╗;lrZ`i@╜í=`M@░' j
</code>```

Try it online!

The lack of regex capabilities made this much more difficult than it needed to be.

Explanation:

```<code>6╙¬▀'_+,;)-@s`;0@Eùk`M┬i;╗;lrZ`i@╜í=`M@░' j
6╙¬▀                                         push digits in base 62 (uppercase and lowercase letters and numbers)
    '_+                                      prepend underscore
       ,;)                                   push two copies of input, move one to bottom of stack
          -                                  get all characters in input that are not letters, numbers, or underscores
           @s                                split input on all occurrences of non-word characters
             `;0@Eùk`M                       for each word: push the first letter (lowercased)
                      ┬i                     transpose and flatten (TOS is list of first letters, then list of words)
                        ;╗                   push a copy of the first letters list to register 0
                          ;lrZ               zip the list of first letters with their positions in the list
                              `i@╜í=`M       for each first letter: push 1 if that is the first time the letter has been encountered (first index of the letter matches its own index) else 0
                                      @░     filter words (take words where corresponding element in the previous list is truthy)
                                        ' j  join on spaces
</code>```

Body:
Seriously, 43 bytes

6╙¬▀'_+,;)-@s`;0@Eùk`M┬i;╗;lrZ`i@╜í=`M@░' j

Try it online!

The lack of regex capabilities made this much more difficult than it needed to be.

Explanation:

6╙¬▀'_+,;)-@s`;0@Eùk`M┬i;╗;lrZ`i@╜í=`M@░' j
6╙¬▀                                         push digits in base 62 (uppercase and lowercase letters and numbers)
    '_+                                      prepend underscore
       ,;)                                   push two copies of input, move one to bottom of stack
          -                                  get all characters in input that are not letters, numbers, or underscores
           @s                                split input on all occurrences of non-word characters
             `;0@Eùk`M                       for each word: push the first letter (lowercased)
                      ┬i                     transpose and flatten (TOS is list of first letters, then list of words)
                        ;╗                   push a copy of the first letters list to register 0
                          ;lrZ               zip the list of first letters with their positions in the list
                              `i@╜í=`M       for each first letter: push 1 if that is the first time the letter has been encountered (first index of the letter matches its own index) else 0
                                      @░     filter words (take words where corresponding element in the previous list is truthy)
                                        ' j  join on spaces


答:
Pyth, <s>41</s> 17 bytes

```<code>tm_<dx+dYk.T+LaYk
</code>```

Try it online!

Inspired by @Doorknob's solution to another problem.

How it works:

```<code>tm_<dx+dYk.T+LaYk
            +L      prepend to each subarray...
              aYk   (Y += ''). Y is initialized to [],
                    so this prepends [''] to the first
                    subarray, ['', ''] to the second, etc.
                    ['' 1  2  3
                     '' '' 4  5  6
                     '' '' '' 7  8  9
                     '' '' '' '' 10 11 12
                     '' '' '' '' '' 13 14 15]
          .T        transpose, giving us
                    ['' '' '' '' ''
                     1  '' '' '' ''
                     2  4  '' '' ''
                     3  5  7  '' ''
                     6  8  10 ''
                     9  11 13
                     12 14
                     15]
 m_<dx+dYk          removes all empty strings in the
                    subarrays while reversing each one
t                   remove the first subarray
</code>```

Previous attempt:

```<code>JlQKlhQm_m@@Qk-dk}h.MZ,0-dtKh.mb,tJdUt+JK
</code>```

Try it online!

How it works:

```<code>JlQKlhQm_m@@Qk-dk}h.MZ,0-dtKh.mb,tJdUt+JK    input array stored as Q
JlQ                                          J = len(Q)
   KlhQ                                      K = len(Q[0])
       m                            Ut+JK    list for d from 0 to J+K-1:
        _m       }AAAAAAAAAABBBBBBBB             reversed list for k from A to B, where:
                  h.MZ,0-dtK                       A = max(0, d-(K-1))
                       0-dtK                               0  d-(K-1)
                            h.mb,tJd               B = min(J-1, d)
                                 tJd                       J-1  d
          @@Qk-dk                                    Q[k][d-k]
</code>```

Title: Diamondize a Matrix

Body:
Given a matrix, output a representation of the matrix where the top left element is on top, the anti-diagonal is the central row and the bottom right element is at the bottom.

For example, consider the following matrix:

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

The diamond version of this matrix is:

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

Inputs and outputs

An input matrix will be given as a list of lists (or anything similar in your language of choice). The output shall be a list of lists as well.

The matrices will only contain positive integers.

The input matrix will not necessarily be square.

The input matrix will be at least 1×1.

Test Cases

```<code>Input:  [[1]]
Output: [[1]]

Input:  [[1,2],[3,4]]
Output: [[1],[3,2],[4]]

Input:  [[1,2,3],[4,5,6]]
Output: [[1],[4,2],[5,3],[6]]

Input:  [[11,2,5],[3,99,3],[4,8,15],[16,23,42]]
Output: [[11],[3,2],[4,99,5],[16,8,3],[23,15],[42]]
</code>```

Scoring

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

Body:
Pyth, <s>41</s> 17 bytes

tm_<dx+dYk.T+LaYk

Try it online!

Inspired by @Doorknob's solution to another problem.

How it works:

tm_<dx+dYk.T+LaYk
            +L      prepend to each subarray...
              aYk   (Y += ''). Y is initialized to [],
                    so this prepends [''] to the first
                    subarray, ['', ''] to the second, etc.
                    ['' 1  2  3
                     '' '' 4  5  6
                     '' '' '' 7  8  9
                     '' '' '' '' 10 11 12
                     '' '' '' '' '' 13 14 15]
          .T        transpose, giving us
                    ['' '' '' '' ''
                     1  '' '' '' ''
                     2  4  '' '' ''
                     3  5  7  '' ''
                     6  8  10 ''
                     9  11 13
                     12 14
                     15]
 m_<dx+dYk          removes all empty strings in the
                    subarrays while reversing each one
t                   remove the first subarray

Previous attempt:

JlQKlhQm_m@@Qk-dk}h.MZ,0-dtKh.mb,tJdUt+JK

Try it online!

How it works:

JlQKlhQm_m@@Qk-dk}h.MZ,0-dtKh.mb,tJdUt+JK    input array stored as Q
JlQ                                          J = len(Q)
   KlhQ                                      K = len(Q[0])
       m                            Ut+JK    list for d from 0 to J+K-1:
        _m       }AAAAAAAAAABBBBBBBB             reversed list for k from A to B, where:
                  h.MZ,0-dtK                       A = max(0, d-(K-1))
                       0-dtK                               0  d-(K-1)
                            h.mb,tJd               B = min(J-1, d)
                                 tJd                       J-1  d
          @@Qk-dk                                    Q[k][d-k]


答:
JavaScript (Firefox), <s>88</s> 87 bytes

a=>b=>(s=+b?a:b,i=x=0,l=s.length,[for(c of s)if(r=s.slice(x,x+=+b||l/a+(i++<l%a)|0))r])
```

Call it like (...)("programming")(3) using Firefox 30+.

Body:
The Challenge

In this challenge you have to do two different (but related) tasks depending of the order of the input.

Your program will recieve a string s and an integer n as input and will

split s into pieces of length n if s comes first. The last element will be shorter if necessary.

split s into n pieces of equal length if n comes first. If len(s) is not a multiple of n the first len(s) mod n elements will be one longer.

You may only take those 2 inputs. s will never contain only digits.

Notes

You may use the reverse mapping. Note this in your answer if you do that.

s will only contain printable ASCII characters (no newlines).

You may not use any builtins that solve either those two tasks directly. All other builtins are allowed.

You have to take both arguments from the same source.

You may take the arguments in an ordered list or any other format which clearly indicates their order as long as it is unambiguous.

You may take the input as one string/ stream and use a character which is not a valid input (like a nullbyte) to separate them.

n will always be equal or less than the length of s and greater than zero.

You may output the resulting list in any resonable format as long as it clearly indicates the particular pieces and their order.

Example

Input:  programming, 3

The last element contains only 2 characters, because 11 is not divisible by 3.

Output: ["pro", "gra", "mmi", "ng"]

Input: 3, programming

11 is not a multiple of 3, so the first 2 elements will be one longer:

Output: ["prog", "ramm", "ing"]

Rules

Function or full program allowed.

Default rules for input/output.

Standard loopholes apply.

This is code-golf, so lowest byte-count wins. Tiebreaker is earlier submission.

Test cases

The test cases got generated with this Pyth program (uses builtins, so no valid answer). Thanks to @FryAmTheEggman for providing the base version of that!

```
3, helloworld -> ['hell', 'owo', 'rld']
helloworld, 3 -> ['hel', 'low', 'orl', 'd']
1, programming -> ['programming']
programming, 1 -> ['p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
8, programming -> ['pr', 'og', 'ra', 'm', 'm', 'i', 'n', 'g']
programming, 8 -> ['programm', 'ing']
9, code golf -> ['c', 'o', 'd', 'e', ' ', 'g', 'o', 'l', 'f']
code golf, 9 -> ['code golf']
4, 133tspeak -> ['133', 'ts', 'pe', 'ak']
133tspeak, 4 -> ['133t', 'spea', 'k']
```

Happy Coding!

Body:
JavaScript (Firefox), <s>88</s> 87 bytes

a=>b=>(s=+b?a:b,i=x=0,l=s.length,[for(c of s)if(r=s.slice(x,x+=+b||l/a+(i++<l%a)|0))r])

Call it like (...)("programming")(3) using Firefox 30+.


答:
MATL, <s>46</s> <s>26</s> <s>21</s> <s>27</s> <s>29</s> 42 bytes

```<code>jtU?jtbUe!tn2Gn>?0t(]tgbw(}ie]!2t$X{Oc''Zt
</code>```

Try it Online! (Updated slightly to work with the latest version of the language)

Explanation

```<code>j           % Explicitly grab the first input as a string
t           % Duplicate
U           % Attempt to convert it to a number
?           % If the conversion to a number was successful
    j       % Explicitly grab the second input as a string
    t       % Duplicate the value
    b       % Bubble-up the first element in the stack
    U       % Convert to a number from a string
    e       % Reshape the string into a nGroup x nPerGroup matrix
    !       % Take the transpose
    t       % Duplicate the result
    n       % Number of characters in the repmat result
    2Gn     % Number of characters in the string
    >?      % If chars in repmat > chars in string
        O   % Zero
        t   % Duplicate
        (   % Assign the last element to a null character (bug in MATL)
    ]       % End if statement
    t       % Duplicate this matrix
    g       % Convert to a logical matrix
    b       % Bubble-up the original string
    w       % Flip the top two elements
    (       % Assign the non-empty characters to the chars from the input string
}           % Else the string comes first
    i       % Explicitly grab the second input (the number)
    e       % Reshape the characters into an nPerGroup x nGroup 2D array
]           % End of if statement
!           % Take the transpose so it reads left-to-right
2           % Number literal
t           % Duplicate
$X{         % Call num2cell to convert to a cell array
Oc          % Null character
''          % Empty string
Zt          % Replace null chars with empty strings
            % Implicit display of stack contents
</code>```

Body:
MATL, <s>46</s> <s>26</s> <s>21</s> <s>27</s> <s>29</s> 42 bytes

jtU?jtbUe!tn2Gn>?0t(]tgbw(}ie]!2t$X{Oc''Zt

Try it Online! (Updated slightly to work with the latest version of the language)

Explanation

j           % Explicitly grab the first input as a string
t           % Duplicate
U           % Attempt to convert it to a number
?           % If the conversion to a number was successful
    j       % Explicitly grab the second input as a string
    t       % Duplicate the value
    b       % Bubble-up the first element in the stack
    U       % Convert to a number from a string
    e       % Reshape the string into a nGroup x nPerGroup matrix
    !       % Take the transpose
    t       % Duplicate the result
    n       % Number of characters in the repmat result
    2Gn     % Number of characters in the string
    >?      % If chars in repmat > chars in string
        O   % Zero
        t   % Duplicate
        (   % Assign the last element to a null character (bug in MATL)
    ]       % End if statement
    t       % Duplicate this matrix
    g       % Convert to a logical matrix
    b       % Bubble-up the original string
    w       % Flip the top two elements
    (       % Assign the non-empty characters to the chars from the input string
}           % Else the string comes first
    i       % Explicitly grab the second input (the number)
    e       % Reshape the characters into an nPerGroup x nGroup 2D array
]           % End of if statement
!           % Take the transpose so it reads left-to-right
2           % Number literal
t           % Duplicate
$X{         % Call num2cell to convert to a cell array
Oc          % Null character
''          % Empty string
Zt          % Replace null chars with empty strings
            % Implicit display of stack contents


答:
C <s> 198 </s> <s> 190 </s> <s> 179 </s> <s> 180 </s> 181 bytes

Edit: Used the tip by user81655 and removed the parenthesis in the ternary operator, thanks! I also changed the cumbersome (S&1) test for evenness for the more appropriate (and shorter!) S%2.

Edit2: Using the *a addressing style heavily, made me blind to the obvious optimizations in the definition of S, i.e., replacing *(a+m) by a[m] etc. I then replaced S itself by T, which essentially does half of what S does. The code also now takes advantage of the return value of putchar.

Edit3: Fixed bug that has been around from the beginning, the Manhattan-search stopping criteria a < b+m is correct only if a has already been decremented. This adds 2 bytes, but one is regained by making the definition of m global.

Edit4: My golfing has passed the minimum and is going the wrong way now. Another bug fix related to the Manhattan-search. I originally had in-bound checks in place and without those the search continues for large input arrays (somewhere round 50x50) beyond the array b. Hence that array has to be expanded to at least twice the previous size, which adds one more byte.

```<code>#define T(x)+x*((a[x]>32)-(a[-x]>32))
m=103;main(){char b[m<<8],*e=b,*a=e+m;while(gets(e+=m));for(e=a;(T(1)T(m))%2**a<33;a=a<b+m?e+=m:a)a-=m-1;for(;*a;a+=T(1)T(m))*a-=putchar(*a);}
</code>```

Ungolfed and explained:

```<code>/* T(1)T(m) (formerly S) is used in two ways (we implicitly assume that each cell has
   one or two neighbors to begin with):
   1. (in the first for-loop) T(1)T(m) returns an odd (even) number if cell a has one (two)
      neighbors with ASCII value > 32. For this to work m must be odd.
   2. (in the second for-loop) at this stage each cell a in the array at which T(1)T(m) is
      evaluated has at most one neighboring cell with ASCII value > 32. T(1)T(m) returns the
      offset in memory to reach this cell from a or 0 if there is no such cell.
      Putting the + in front of x here saves one byte (one + here replaces two
      + in the main part)

#define T(x)+x*((a[x]>32)-(a[-x]>32))

  /* A snake of length 100 together with the newlines (replaced by 0:s in memory) fits
     an array of size 100x101, but to avoid having to perform out-of-bounds checks we
     want to have an empty line above and the array width amount of empty lines below
     the input array. Hence an array of size 202x101 would suffice. However, we save
     a (few) bytes if we express the array size as m<<8, and since m must be odd
     (see 1. above), we put m = 103. Here b and e point to the beginning of the (now)
     256x103 array and a points to the beginning of the input array therein */

m=103;
main()
{

  char b[m<<8],*e=b,*a=e+m;

  /* This reads the input array into the 256x103 array */

  while(gets(e+=m));

  /* Here we traverse the cells in the input array one
     constant-Manhattan-distance-from-top-left diagonal at a time starting at the top-left
     singleton. Each diagonal is traversed from bottom-left to top-right since the starting point
     (memory location e) is easily obtained by moving one line downwards for each diagonal
     (+m) and the stopping point is found by comparing the present location a to the input array
     starting position (b+m). The traversal is continued as long as the cell has either
     an ASCII value < 33 or it has two neighbors with ASCII value > 32 each (T(1)T(m)
     is even so that (T(1)T(m))%2=0).
     Note that the pointer e will for wide input arrays stray way outside (below) the
     input array itself, so that for a 100 cell wide (the maximum width) input array
     with only two occupied cells in the bottom-right corner, the starting cell
     will be discovered 98 lines below the bottom line of the input array.
     Note also that in these cases the traversal of the diagonals will pass through the
     right-hand side of the 103-wide array and enter on the left-hand side. This, however,
     is not a problem since the cells that the traversal then passes have a lower
     Manhattan distance and have thereby already been analyzed and found not to contain
     the starting cell. */

  for(e=a;(T(1)T(m))%2**a<33;a=a<b+m?e+=m:a)a-=m-1;

  /* We traverse the snake and output each character as we find them, beginning at the
     previously found starting point. Here we utilize the function T(1)T(m), which
     gives the offset to the next cell in the snake (or 0 if none), provided that
     the current cell has at most one neighbor. This is automatically true for the
     first cell in the snake, and to ensure it for the rest of the cells we put the
     ASCII value of the current cell to 0 (*a-=putchar(*a)), where we use the fact
     that putchar returns its argument. The value 0 is convenient, since it makes the
     stopping condition (offset = 0, we stay in place) easy to test for (*a == 0). */

  for(;*a;a+=T(1)T(m))
    *a-=putchar(*a);
}
</code>```

Title: De-Snakify a String

Body:
A regular string looks like this:

```<code>Hello,IAmAStringSnake!
</code>```

And a string snake looks something like this:

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan
</code>```

Your Task

String snakes are dangerous, so you must make a program that takes a string snake as input and outputs it as a regular string.

Specifications

Input can be a multiline string or an array of strings.

Each line of the input will be padded with spaces to form a rectangular grid.

Characters in the snake can only connect to adjacent characters above, below, left or right of them (just like in the game Snake). They cannot go diagonal.

The snake characters will never be adjacent to another part of the snake, only the connected characters.

The first character of the string is the end character with the shortest Manhattan distance from the top-left corner of the input grid (i.e. the minimum number of moves it would take for a snake to go directly from the end character to the top-left corner). Both ends will never have the same distance.

The string can contain any ASCII character between code points 33 and 126 inclusive (no spaces or newlines).

The string will be between 2 and 100 characters long.

Shortest code in bytes wins.

Test Cases

(Input grid, followed by the output string)

```<code>Hel
  l      rin
  o,IAmASt g
           S
       !ekan

Hello,IAmAStringSnake!

----------

Python

Python

----------

P  ngPu  Code
r  i  z  d  G
o  m  z  n  o
gram  lesA  lf

ProgrammingPuzzlesAndCodeGolf

----------

   ~ zyx tsr XWVUTSR
   }|{ wvu q Y     Q
!          p Z `ab P
"#$ 6789:; o [ _ c O
  % 5    < n \]^ d N
('& 432  = m     e M
)     1  > lkjihgf L
*+,-./0  ?         K
         @ABCDEFGHIJ

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

----------

  tSyrep
  r    p
  in Sli
   g    Sile
   Snakes  n
Ser      ylt
a eh   ilS
fe w   t
   emo h
     Sre

SlipperyStringSnakesSilentlySlitherSomewhereSafe
</code>```

Body:
C <s> 198 </s> <s> 190 </s> <s> 179 </s> <s> 180 </s> 181 bytes

Edit: Used the tip by user81655 and removed the parenthesis in the ternary operator, thanks! I also changed the cumbersome (S&1) test for evenness for the more appropriate (and shorter!) S%2.

Edit2: Using the *a addressing style heavily, made me blind to the obvious optimizations in the definition of S, i.e., replacing *(a+m) by a[m] etc. I then replaced S itself by T, which essentially does half of what S does. The code also now takes advantage of the return value of putchar.

Edit3: Fixed bug that has been around from the beginning, the Manhattan-search stopping criteria a < b+m is correct only if a has already been decremented. This adds 2 bytes, but one is regained by making the definition of m global.

Edit4: My golfing has passed the minimum and is going the wrong way now. Another bug fix related to the Manhattan-search. I originally had in-bound checks in place and without those the search continues for large input arrays (somewhere round 50x50) beyond the array b. Hence that array has to be expanded to at least twice the previous size, which adds one more byte.

#define T(x)+x*((a[x]>32)-(a[-x]>32))
m=103;main(){char b[m<<8],*e=b,*a=e+m;while(gets(e+=m));for(e=a;(T(1)T(m))%2**a<33;a=a<b+m?e+=m:a)a-=m-1;for(;*a;a+=T(1)T(m))*a-=putchar(*a);}

Ungolfed and explained:

/* T(1)T(m) (formerly S) is used in two ways (we implicitly assume that each cell has
   one or two neighbors to begin with):
   1. (in the first for-loop) T(1)T(m) returns an odd (even) number if cell a has one (two)
      neighbors with ASCII value > 32. For this to work m must be odd.
   2. (in the second for-loop) at this stage each cell a in the array at which T(1)T(m) is
      evaluated has at most one neighboring cell with ASCII value > 32. T(1)T(m) returns the
      offset in memory to reach this cell from a or 0 if there is no such cell.
      Putting the + in front of x here saves one byte (one + here replaces two
      + in the main part)

#define T(x)+x*((a[x]>32)-(a[-x]>32))

  /* A snake of length 100 together with the newlines (replaced by 0:s in memory) fits
     an array of size 100x101, but to avoid having to perform out-of-bounds checks we
     want to have an empty line above and the array width amount of empty lines below
     the input array. Hence an array of size 202x101 would suffice. However, we save
     a (few) bytes if we express the array size as m<<8, and since m must be odd
     (see 1. above), we put m = 103. Here b and e point to the beginning of the (now)
     256x103 array and a points to the beginning of the input array therein */

m=103;
main()
{

  char b[m<<8],*e=b,*a=e+m;

  /* This reads the input array into the 256x103 array */

  while(gets(e+=m));

  /* Here we traverse the cells in the input array one
     constant-Manhattan-distance-from-top-left diagonal at a time starting at the top-left
     singleton. Each diagonal is traversed from bottom-left to top-right since the starting point
     (memory location e) is easily obtained by moving one line downwards for each diagonal
     (+m) and the stopping point is found by comparing the present location a to the input array
     starting position (b+m). The traversal is continued as long as the cell has either
     an ASCII value < 33 or it has two neighbors with ASCII value > 32 each (T(1)T(m)
     is even so that (T(1)T(m))%2=0).
     Note that the pointer e will for wide input arrays stray way outside (below) the
     input array itself, so that for a 100 cell wide (the maximum width) input array
     with only two occupied cells in the bottom-right corner, the starting cell
     will be discovered 98 lines below the bottom line of the input array.
     Note also that in these cases the traversal of the diagonals will pass through the
     right-hand side of the 103-wide array and enter on the left-hand side. This, however,
     is not a problem since the cells that the traversal then passes have a lower
     Manhattan distance and have thereby already been analyzed and found not to contain
     the starting cell. */

  for(e=a;(T(1)T(m))%2**a<33;a=a<b+m?e+=m:a)a-=m-1;

  /* We traverse the snake and output each character as we find them, beginning at the
     previously found starting point. Here we utilize the function T(1)T(m), which
     gives the offset to the next cell in the snake (or 0 if none), provided that
     the current cell has at most one neighbor. This is automatically true for the
     first cell in the snake, and to ensure it for the rest of the cells we put the
     ASCII value of the current cell to 0 (*a-=putchar(*a)), where we use the fact
     that putchar returns its argument. The value 0 is convenient, since it makes the
     stopping condition (offset = 0, we stay in place) easy to test for (*a == 0). */

  for(;*a;a+=T(1)T(m))
    *a-=putchar(*a);
}


问:
Insert semi-sorted into unsorted array
Welcome to your first day at PPCG Inc. As our newest junior assistant document sorter, you are responsible for making sure all documents we sent down to you are archived in alphabetical order. It's so easy a monkey can do it. Well, metaphorically speaking, as we did hire a monkey to do it. Guess what? Turns out monkeys lack an understanding of our alphabet. Anyway, there's no time to fix the mess there is right now, so just try to not make the situation any worse, ok? Then get to it! If you get hungry, there's bananas over by the water cooler. Good luck!

Job Description

Input

You will receive a list of strings (the archive) and a string that needs to be added to that list (the document)

All strings will contain only uppercase letters, lowercase letters and spaces

Strings will always start and end with a letter

Task

Determine the target position of the document: the position it should receive in the archive. The target position can be determined as follows:

For each position:

Count the amount of strings in the archive before that position that are alphabetically before the document

Count the amount of strings in the archive after that position that are alphabetically after the document

Define the score of the position as the sum of the above two counts

The target position of the document is the position with the highest score

In case of a tie, all positions with the highest score are equally valid as target position. Only one needs to be selected.

When sorting:

Uppercase and lowercase letters are equivalent

Spaces come before letters

Output

The archive with the document added to it in any form

OR

The target position of the document, in either a 0-based or 1-based index

Job evaluation

Fewest bytes wins!

Example I/O

```<code>Archive:
    Applebuck Season
    Friendship is Magic
    The Ticket Master
    Griffon the BrushOff
    Boast Busters
    Bridle Gossip

Document: Dragonshy

Position scores (0-based index):
0: 0 + 3 = 3
1: 1 + 3 = 4
2: 1 + 2 = 3
3: 1 + 1 = 2
4: 1 + 0 = 1
5: 2 + 0 = 2
6: 3 + 0 = 3

Target position: 1
</code>```

答:
Pyth, <s>40</s> 38 bytes

Credits to @Katenkyo for teaching me that A xnor B is basically A==B. (A xor B is also A!=B)

```<code>AQJ+],k0.e,rb0hkGteh.Msmq<hdrH0<edeZJJ
</code>```

Try it online!

How it works:

It sums the XNOR of whether the entry is smaller than the document, and whether the entry's index is smaller than the document's index.

It finds the position in which this sum is the maximum, then outputs it.

Title: Insert semi-sorted into unsorted array

Body:
Pyth, <s>40</s> 38 bytes

Credits to @Katenkyo for teaching me that A xnor B is basically A==B. (A xor B is also A!=B)

AQJ+],k0.e,rb0hkGteh.Msmq<hdrH0<edeZJJ

Try it online!

How it works:

It sums the XNOR of whether the entry is smaller than the document, and whether the entry's index is smaller than the document's index.

It finds the position in which this sum is the maximum, then outputs it.


答:
Ruby, 97 bytes

Anonymous function, returns the target position.

```<code>->a,d{d.upcase!;(0...a.size).max_by{|i|a[0,i].count{|s|s.upcase<d}+a[i..-1].count{|s|s.upcase>d}}}
</code>```

When actually inserting into the archive, 110 bytes:

```<code>->a,d{t=d.upcase;a.insert (0...a.size).max_by{|i|a[0,i].count{|s|s.upcase<d}+a[i..-1].count{|s|s.upcase>d}},d}
</code>```

Title: Insert semi-sorted into unsorted array

Body:
Welcome to your first day at PPCG Inc. As our newest junior assistant document sorter, you are responsible for making sure all documents we sent down to you are archived in alphabetical order. It's so easy a monkey can do it. Well, metaphorically speaking, as we did hire a monkey to do it. Guess what? Turns out monkeys lack an understanding of our alphabet. Anyway, there's no time to fix the mess there is right now, so just try to not make the situation any worse, ok? Then get to it! If you get hungry, there's bananas over by the water cooler. Good luck!

Job Description

Input

You will receive a list of strings (the archive) and a string that needs to be added to that list (the document)

All strings will contain only uppercase letters, lowercase letters and spaces

Strings will always start and end with a letter

Task

Determine the target position of the document: the position it should receive in the archive. The target position can be determined as follows:

For each position:

Count the amount of strings in the archive before that position that are alphabetically before the document

Count the amount of strings in the archive after that position that are alphabetically after the document

Define the score of the position as the sum of the above two counts

The target position of the document is the position with the highest score

In case of a tie, all positions with the highest score are equally valid as target position. Only one needs to be selected.

When sorting:

Uppercase and lowercase letters are equivalent

Spaces come before letters

Output

The archive with the document added to it in any form

OR

The target position of the document, in either a 0-based or 1-based index

Job evaluation

Fewest bytes wins!

Example I/O

```<code>Archive:
    Applebuck Season
    Friendship is Magic
    The Ticket Master
    Griffon the BrushOff
    Boast Busters
    Bridle Gossip

Document: Dragonshy

Position scores (0-based index):
0: 0 + 3 = 3
1: 1 + 3 = 4
2: 1 + 2 = 3
3: 1 + 1 = 2
4: 1 + 0 = 1
5: 2 + 0 = 2
6: 3 + 0 = 3

Target position: 1
</code>```

Body:
Ruby, 97 bytes

Anonymous function, returns the target position.

->a,d{d.upcase!;(0...a.size).max_by{|i|a[0,i].count{|s|s.upcase<d}+a[i..-1].count{|s|s.upcase>d}}}

When actually inserting into the archive, 110 bytes:

->a,d{t=d.upcase;a.insert (0...a.size).max_by{|i|a[0,i].count{|s|s.upcase<d}+a[i..-1].count{|s|s.upcase>d}},d}


答:
Ruby, <s>68</s> 66 bytes

Anonymous function.

```<code>->l{i=-1;k=[];l.map{|r|i-=j=-1;r.map{|e|k[i+j+=1]=[e,*k[i+j]]}};k}
</code>```

Because of how the splat operator works, I was able to save 2 bytes by forgoing the array addition.

Title: Diamondize a Matrix

Body:
Ruby, <s>68</s> 66 bytes

Anonymous function.

->l{i=-1;k=[];l.map{|r|i-=j=-1;r.map{|e|k[i+j+=1]=[e,*k[i+j]]}};k}

Because of how the splat operator works, I was able to save 2 bytes by forgoing the array addition.