Title: List all ordered partitions of n

Body:
The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer n. These are the lists of numbers from 1 to n whose sum is n. For example, given input n = 4, the result should be:

4

  1, 3

  3, 1

  2, 2

  2, 1, 1

  1, 2, 1

  1, 1, 2

  1, 1, 1, 1

The result can be in any order, but must contain each ordered partition once. This means that for n = 4, [1, 1, 2], [1, 2, 1] and [2, 1, 1] must all be part of the result.

Here's my own JavaScript code which achieves this:

```<code>function range(n) {
    for (var range = [], i = 0; i < n; range.push(++i));
    return range;
}

function composition(n) {
    return n < 1 ? [[]] : range(n).map(function(i) {
        return composition(n - i).map(function(j) {
            return [i].concat(j);
        });
    }).reduce(function(a, b) {
        return a.concat(b);
    });
}
</code>```

Golfed, ES6 (<s>169</s> <s>167</s> <s>119</s> <s>109</s> <s>105</s> <s>89</s> 85 bytes):

```<code>n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]
</code>```

Body:
Jelly, <s>7</s> 6 bytes

-1 byte thanks to @Dennis (convert from unary ḅ1, rather than sum for each for each S€€)

1ẋŒṖḅ1

TryItOnline

How?

1ẋŒṖḅ1 - Main link: n          e.g. 4
1ẋ     - repeat 1 n times          [1,1,1,1]
  ŒṖ   - partitions of a list     [[[1],[1],[1],[1]], [[1],[1],[1,1]], [[1],[1,1],[1]],
                                   [[1],[1,1,1]],     [[1,1],[1],[1]], [[1,1],[1,1]],
                                   [[1,1,1],[1]],     [[1,1,1,1]]]
    ḅ1 - from base 1 (vectorises)  [[1,1,1,1],        [1,1,2],         [1,2,1],
                                   [1,3],             [2,1,1],         [2,2],
                                   [3,1],             [4]]


问:
The Decanting Problem
Given N decanters (0 < N < 10) with that can hold C0 ... CN-1 liters (0 < C < 50) and a goal G liters, please determine if it is possible to reach that goal using only the following actions:

Fill a decanter

Empty a decanter

Pour from one decanter to another until the one being poured to is full or the one being poured from is empty

The goal amount G must be the amount of water in one of the containers at the end. You cannot have a 'output decanter'.

Examples

N: 2

C0: 5

C1: 12

G: 1

Result: Yes

N: 3

C0: 6

C1: 9

C2: 21

G: 5

Result: No

Hint: To calculate if it is possible, check to see if G is divisible by the GCD of the capacities. Also, make sure it will fit in a container.

Remember, this is code-golf, so the code with the lowest number of bytes wins.

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Excel: 43 bytes

=AND(MOD(A10,GCD(A1:A9))=0,A10<=MAX(A1:A9))

Try it online!

How to use:

Put this formula anywhere Except A1-A10.

Then input your Decant holding volumes in cells A1:A9 (because the number of decants is fixed) and the goal in A10. cells without decants should be left blank. Wherever you put the formula will contain the result. TRUE if you can achieve the goal, FALSE if you cannot.

ContentLicense: CC BY-SA 3.0

Title: The Decanting Problem


问:
Create a pyramidal matrix
A pyramidal matrix is a square matrix where all numbers increase or decrease from the center point, like the two matrices below:

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

Or:

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

Given a non-zero integer n, create a pyramidal matrix where the numbers goes from 1 to n either in increasing order (if n<0), or decreasing order (if n>0) from the center. If n is even, then there will be 4 center numbers (see the examples).

As always:

Optional input and output format

Number of spaces, delimiter etc. is optional

Test cases:

```<code>1
1

-1
1

5
1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  1
1  2  3  3  3  3  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  4  5  4  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  3  3  3  3  2  1
1  2  2  2  2  2  2  2  1
1  1  1  1  1  1  1  1  1

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

```<code>2
1  1  1  1
1  2  2  1
1  2  2  1
1  1  1  1

-2
2  2  2  2
2  1  1  2
2  1  1  2
2  2  2  2

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

Title: Create a pyramidal matrix

Body:
PHP, 215 Bytes

for($i=0;$i<$m=($r=($s=abs($n=$argv[1]))*2-$s%2)**2;){$i%$r?:print"\n";$l=min(($x=$i%$r+1)<$s?$x:$x=$r-$x+1,($z=1+floor($i++/$r))<$s?$z:$z=$r-$z+1);$o=($n>0)?$l:$s+1-$l;echo str_pad(" ",1+strlen($s)-strlen($o)).$o;}


问:
Emulate a 7-segment display

Task

The task is to display any of the 128 possible states of a
7-segment display.

Your program should accept a string of 7 characters ("bits") that are either 0 or 1.
First bit of input corresponds to segment A of the following illustration, the
second to B, etc (ignore dp):

How you represent the display is up to you -- a single Unicode or ASCII symbol,
ASCII art, grafically, or whatever you can come up with. However, each
input must have it's own distinct output. If you come up with something fancy I'm sure you can harvest upvotes by showing off some examples.

All 128 possible states of the display are:

Rules

Codegolf

As I said, any kind of output is allowed, but it would be nice if you specified it.

Input can be stdin or command line argument.

Examples

Input

```<code>1101101
</code>```

Output

As ASCII/Unicode:

```<code>2
</code>```

Different kinds of ASCII art (I'm not too good at this)

```<code> _   ╺┓  ╒╗   ---
 _|  ┏┛  ╔╝     |
|_   ┗╸  ╚╛   ---
              |
              ---
</code>```

答:
R (65 chars):

```<code>plot((3^(1i*1.5:-4.5)*(1:7!=7)),col=strsplit(readline(),'')[[1]])
</code>```

Relies on some loose approximations for some transcendental nuumbers ...

Title: Emulate a 7-segment display

Body:
R (65 chars):

plot((3^(1i*1.5:-4.5)*(1:7!=7)),col=strsplit(readline(),'')[[1]])

Relies on some loose approximations for some transcendental nuumbers ...


Title: Create a pyramidal matrix

Body:
A pyramidal matrix is a square matrix where all numbers increase or decrease from the center point, like the two matrices below:

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

Or:

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

Given a non-zero integer n, create a pyramidal matrix where the numbers goes from 1 to n either in increasing order (if n<0), or decreasing order (if n>0) from the center. If n is even, then there will be 4 center numbers (see the examples).

As always:

Optional input and output format

Number of spaces, delimiter etc. is optional

Test cases:

```<code>1
1

-1
1

5
1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  1
1  2  3  3  3  3  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  4  5  4  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  3  3  3  3  2  1
1  2  2  2  2  2  2  2  1
1  1  1  1  1  1  1  1  1

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

```<code>2
1  1  1  1
1  2  2  1
1  2  2  1
1  1  1  1

-2
2  2  2  2
2  1  1  2
2  1  1  2
2  2  2  2

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

Body:
Haskell, <s>191</s> <s>183</s> <s>173</s> <s>169</s> 168 bytes

r=reverse;m=map
x!y=(((++)<*>(x.r)).).zipWith(++).m y
g n|n<0=m(m$abs.((n-1)+)).g$abs n|1<2=[id!id,tail!init]!!mod n 2=<<m r$r$m(\x->(x<$[1..x])++[x+1..n])[1..n]
g.(0-)

Usage:

mapM_ print $ (g.(0-)) 3

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

Thanks to nimi for <s>2</s> <s>10</s> <s>20</s> 24 bytes!


问:
String Concatenation
The Challenge

Given two strings containing only lowercase letters and no spaces, the result should be the shorter string, followed by an underscore, followed by the longer string with the first instance of a character removed for each character it contains that is in the shorter string.

You can assume the strings will always be different lengths.

Test Cases:

```<code>sale
salinewater
Result: sale_inwater (only the first 'a' in salinewater is removed)

jostling
juggle
Result: juggle_ostin (juggle is the shorter string)

juggle
juggler
Result: juggle_r (a 'g' is removed for every 'g' in the shorter string)
</code>```

Rules

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

答:
Python 2, <s>81</s> 72 bytes

a,b=sorted(input(),key=len)
for c in a:b=b.replace(c,"",1)
print a+"_"+b
```

Try it online

Title: String Concatenation

Body:
Python 2, <s>81</s> 72 bytes

a,b=sorted(input(),key=len)
for c in a:b=b.replace(c,"",1)
print a+"_"+b

Try it online


问:
List all ordered partitions of n
The challenge is to list all ordered partitions (composition (combinatorics)) of a given positive integer n. These are the lists of numbers from 1 to n whose sum is n. For example, given input n = 4, the result should be:

4

  1, 3

  3, 1

  2, 2

  2, 1, 1

  1, 2, 1

  1, 1, 2

  1, 1, 1, 1

The result can be in any order, but must contain each ordered partition once. This means that for n = 4, [1, 1, 2], [1, 2, 1] and [2, 1, 1] must all be part of the result.

Here's my own JavaScript code which achieves this:

```<code>function range(n) {
    for (var range = [], i = 0; i < n; range.push(++i));
    return range;
}

function composition(n) {
    return n < 1 ? [[]] : range(n).map(function(i) {
        return composition(n - i).map(function(j) {
            return [i].concat(j);
        });
    }).reduce(function(a, b) {
        return a.concat(b);
    });
}
</code>```

Golfed, ES6 (<s>169</s> <s>167</s> <s>119</s> <s>109</s> <s>105</s> <s>89</s> 85 bytes):

```<code>n=>n?[].concat(...[...Array(n)].map((x,i)=>i+1).map(b=>m(n-b).map(a=>[b,...a]))):[[]]
</code>```

答:
Perl, 44 bytes

Includes +3 for -n (code uses $' and $0 so it can't be run as a -e commandline)

Give number to partition on STDIN:

```<code>partitions.pl <<< 4
</code>```

partitions.pl

```<code>#!/usr/bin/perl -n
$_=$&-$_.",$_$'",do$0for/\d+/..$&-1;print
</code>```

If you don't mind extra spaces at the end of a line and an extra newline this 42 byte solution works too (run as perl -M5.010 partitions.pl):

```<code>#!/usr/bin/perl -n
$_=$`-$_." $_ $'",do$0for/\s/..$_-1;say
</code>```

Title: List all ordered partitions of n

Body:
Perl, 44 bytes

Includes +3 for -n (code uses $' and $0 so it can't be run as a -e commandline)

Give number to partition on STDIN:

partitions.pl <<< 4

partitions.pl

#!/usr/bin/perl -n
$_=$&-$_.",$_$'",do$0for/\d+/..$&-1;print

If you don't mind extra spaces at the end of a line and an extra newline this 42 byte solution works too (run as perl -M5.010 partitions.pl):

#!/usr/bin/perl -n
$_=$`-$_." $_ $'",do$0for/\s/..$_-1;say


答:
PHP, 125 Bytes

```<code>for($i=$n=$argv[1];$i<=str_repeat(1,$n);$i++)if(array_sum($a=str_split($i))==$n&!strpos($i,"0"))$r[]=$a;echo json_encode($r);
</code>```

-4 Bytes for print_r($r); instead of echo json_encode($r); for the output

a recursive solution with 250 Bytes

```<code>function f($n){global$a;foreach($a as$x)foreach(range(1,$n)as$y)$a[]=array_merge((array)$x,[$y]);if(--$n)f($n);}$a=range(1,$w=$argv[1]);f($w-1);foreach($a as$z)if(array_sum((array)$z)==$w)$c[join("-",(array)$z)]=$z;echo json_encode(array_values($c));
</code>```

Title: List all ordered partitions of n

Body:
PHP, 125 Bytes

for($i=$n=$argv[1];$i<=str_repeat(1,$n);$i++)if(array_sum($a=str_split($i))==$n&!strpos($i,"0"))$r[]=$a;echo json_encode($r);

-4 Bytes for print_r($r); instead of echo json_encode($r); for the output

a recursive solution with 250 Bytes

function f($n){global$a;foreach($a as$x)foreach(range(1,$n)as$y)$a[]=array_merge((array)$x,[$y]);if(--$n)f($n);}$a=range(1,$w=$argv[1]);f($w-1);foreach($a as$z)if(array_sum((array)$z)==$w)$c[join("-",(array)$z)]=$z;echo json_encode(array_values($c));


问:
Invert a boolean array
A nice simple one

Input

Given a boolean array (Or an acceptable alternative), you can assume the array will never be more than 32 elements long.

```<code>[false, false, true, false, false]
</code>```

Output

Invert every element of the array and output it.

```<code>[true, true, false, true, true]
</code>```

Rules

You can write a full program or just a function

Standard loopholes apply

Shortest code in bytes, per language, wins!

Test cases

```<code>Input:
[true, false]
Output:
[false, true]

Input: //Example of acceptable alternative
[0,1,1]
Output:
[1,0,0]
</code>```

答:
Brainfuck, <s>72</s> <s>69</s> 61 bytes

```<code>,>++++++++[<------>-]<>+<[->-<]>[<+>-]<>++++++++[<++++++>-]<.
</code>```

Closest i managed to get as BF dosent have Array support

Formatting is stupid, i will fix it when i get a pc... Somehow it wont let me post it as a snippet

Title: Invert a boolean array

Body:
Brainfuck, <s>72</s> <s>69</s> 61 bytes

,>++++++++[<------>-]<>+<[->-<]>[<+>-]<>++++++++[<++++++>-]<.

Closest i managed to get as BF dosent have Array support

Formatting is stupid, i will fix it when i get a pc... Somehow it wont let me post it as a snippet


问:
Implement tab completion
Tab completion is a useful feature that auto-completes partially written commands.  You're going to be implementing it.

For example, if the available commands were ['apply','apple','apple pie','eat'], then a would complete to  appl, as all of the commands that start with a also start with appl.

Input/Output

You need to input a string, A, and a set of strings, B.

You need to output the longest common prefix of all B that starts with A.

If none of the options starts with A, then return A

You can assume that B is nonempty, and that all strings are nonempty

You cannot assume that any of the options start with A, nor that the common prefix will be longer than A

You can be case sensitive or case insensitive.

You only need to handle printable ASCII

Built-ins that explicitly do this task are allowed

Test cases:

```<code>'a'       ['apply','apple','apple pie','eat'] => 'appl'
'a'       ['apple pie']                       => 'apple pie'
'apple'   ['eat','dine']                      => 'apple'
'program' ['programa','programb']             => 'program'
'*%a('    ['*%a()-T>','*%a()-T<','@Da^n&']    => '*%a()-T'
'a'       ['abs','absolute','answer']         => 'a'
'a'       ['a','abs']                         => 'a'
'one to'  ['one to one','one to many']        => 'one to '
</code>```

Note the trailing space on the last test case

This is a code-golf, so make your answers as short as possible!

答:
Pyth, <s>14</s> 13 bytes

Thanks to @isaacg for -1 byte

```<code>.xe@F/#z._MQz
</code>```

A program that takes the list of strings, and then the string, on STDIN and prints the result.

Verify all test cases

How it works

```<code>.xe@F/#z._MQz  Program. Inputs: Q, z
        ._MQ   Map prefixes over Q
     /#z       Filter that by count(z)>0, removing the prefixes corresponding to elements
               in Q that do not start with z
   @F          Fold intersection over that. This yields all the common prefixes
  e            Yield the last element of that, giving the longest common prefix, since the
               prefixes are already sorted by length
.x             But if that throws an exception since no elements of Q start with z:
            z  Yield z instead
               Implicitly print
</code>```

Title: Implement tab completion

Body:
Pyth, <s>14</s> 13 bytes

Thanks to @isaacg for -1 byte

.xe@F/#z._MQz

A program that takes the list of strings, and then the string, on STDIN and prints the result.

Verify all test cases

How it works

.xe@F/#z._MQz  Program. Inputs: Q, z
        ._MQ   Map prefixes over Q
     /#z       Filter that by count(z)>0, removing the prefixes corresponding to elements
               in Q that do not start with z
   @F          Fold intersection over that. This yields all the common prefixes
  e            Yield the last element of that, giving the longest common prefix, since the
               prefixes are already sorted by length
.x             But if that throws an exception since no elements of Q start with z:
            z  Yield z instead
               Implicitly print


答:
Perl, 61 bytes

Includes +2 for -0p

Run with the first word followed by the dictionary words on STDIN:

```<code>tabcompletion.pl
a
apply
apple
apple pie
eat
^D
</code>```

tabcompletion.pl:

```<code>#!/usr/bin/perl -0p
/^(.+)
((?!\1).*
)*(\1.*).*
((?!\1).*
|\3.*
)*$|
/;$_=$3||$`
</code>```

Title: Implement tab completion

Body:
Tab completion is a useful feature that auto-completes partially written commands.  You're going to be implementing it.

For example, if the available commands were ['apply','apple','apple pie','eat'], then a would complete to  appl, as all of the commands that start with a also start with appl.

Input/Output

You need to input a string, A, and a set of strings, B.

You need to output the longest common prefix of all B that starts with A.

If none of the options starts with A, then return A

You can assume that B is nonempty, and that all strings are nonempty

You cannot assume that any of the options start with A, nor that the common prefix will be longer than A

You can be case sensitive or case insensitive.

You only need to handle printable ASCII

Built-ins that explicitly do this task are allowed

Test cases:

```<code>'a'       ['apply','apple','apple pie','eat'] => 'appl'
'a'       ['apple pie']                       => 'apple pie'
'apple'   ['eat','dine']                      => 'apple'
'program' ['programa','programb']             => 'program'
'*%a('    ['*%a()-T>','*%a()-T<','@Da^n&']    => '*%a()-T'
'a'       ['abs','absolute','answer']         => 'a'
'a'       ['a','abs']                         => 'a'
'one to'  ['one to one','one to many']        => 'one to '
</code>```

Note the trailing space on the last test case

This is a code-golf, so make your answers as short as possible!

Body:
Perl, 61 bytes

Includes +2 for -0p

Run with the first word followed by the dictionary words on STDIN:

tabcompletion.pl
a
apply
apple
apple pie
eat
^D

tabcompletion.pl:

#!/usr/bin/perl -0p
/^(.+)
((?!\1).*
)*(\1.*).*
((?!\1).*
|\3.*
)*$|
/;$_=$3||$`


问:
Write the longest sentence using keywords of a programming language
As the title said, the challenge is to write the longest sentence by only using the keywords of 1 programming language.

For instance, using the keywords of C++, it is possible to write this sentence:

do not try this float

What can you come up with?

答:
While making sentences is not really my strong suite, here goes nothing -

Python 20 words

Finally, continue with import and raise global yield while class lambda is in break and try and print exec pass.

To help with checking, I wrote some code to check whether the words are in the keyword list or not.

```<code>from keyword import kwlist
from re import findall

def kwcheck(sentence):
    """Check whether all the words of a sentence are Python keywords"""
    words= findall(r'\w+', sentence)
    for word in words:
        if word.lower() not in kwlist:
            return False
    return True, len(words)

if __name__ == '__main__':
    sen= raw_input("Enter your sentence: ")
    print kwcheck(sen)
</code>```

Body:
While making sentences is not really my strong suite, here goes nothing -

Python 20 words

Finally, continue with import and raise global yield while class lambda is in break and try and print exec pass.

To help with checking, I wrote some code to check whether the words are in the keyword list or not.

from keyword import kwlist
from re import findall

def kwcheck(sentence):
    """Check whether all the words of a sentence are Python keywords"""
    words= findall(r'\w+', sentence)
    for word in words:
        if word.lower() not in kwlist:
            return False
    return True, len(words)

if __name__ == '__main__':
    sen= raw_input("Enter your sentence: ")
    print kwcheck(sen)


问:
Is this string prime?

A string is called a "prime string" if it can't be written as a concatenation of more than one of the same string.

Your task is to write a program that, given a sequence of letters of length N (5 < N < 100), determines if it is prime or not.

Examples

Input: AABBAA

Output: not prime, false, 0, etc.

Input: FDFJKEHKLJHDSUS

Output: prime, true, 1, etc.

Uppercase and lowercase letters count as the same letter.

Remember, this is code-golf, so the code with the smallest number of bytes wins.

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

答:
Ruby, 16 + 1 (n flag)` = <s>36</s> 17 bytes

Basically the prime-checking regex for unary numbers. Probably shorter in Retina. If you want a newline after the output, add the newline for 1 bytes.

Edited to a shorter version only for the sake of posterity, since there's not much point in answers to dupe questions.

```<code>p ! ~/^(.+)\1+$/
</code>```

Title: Is this string prime?

Body:
Ruby, 16 + 1 (n flag)` = <s>36</s> 17 bytes

Basically the prime-checking regex for unary numbers. Probably shorter in Retina. If you want a newline after the output, add the newline for 1 bytes.

Edited to a shorter version only for the sake of posterity, since there's not much point in answers to dupe questions.

p ! ~/^(.+)\1+$/


答:
D, 88 bytes

```<code>S f(S)(S p,S[]q){try p=q.filter!(a=>a.startsWith(p)).fold!commonPrefix;catch{}return p;}
</code>```

Usage:

```<code>assert(f("a", ["apply","apple","apple pie","eat"]) ==  "appl");
</code>```

The code simply removes all elements from q that don't start with p, then computes the largest common initial subsequence of the remaining elements.

The templated parameters save us two repetitions of string and one of auto.  The exception misuse lets us avoid the temporary variable and conditional that would otherwise be necessary to handle the case where no elements of q start with p.

Title: Implement tab completion

Body:
D, 88 bytes

S f(S)(S p,S[]q){try p=q.filter!(a=>a.startsWith(p)).fold!commonPrefix;catch{}return p;}

Usage:

assert(f("a", ["apply","apple","apple pie","eat"]) ==  "appl");

The code simply removes all elements from q that don't start with p, then computes the largest common initial subsequence of the remaining elements.

The templated parameters save us two repetitions of string and one of auto.  The exception misuse lets us avoid the temporary variable and conditional that would otherwise be necessary to handle the case where no elements of q start with p.


问:
Is it an Odd Word?

Challenge

Given a single word as input, determine if the word is odd or even.

Odd and Even words

Assume the general rules:

```<code>odd + odd = even
even + odd = odd
odd + even = odd
even + even = even
</code>```

In the alphabet, the odd letters are:

```<code>aeiou
</code>```

And the even letters are:

```<code>bcdfghjklmnpqrstvwxyz
</code>```

The same applies to capital letters (AEIOU are odd and BCDFGHJKLMNPQRSTVWXYZ are even).

You then 'add' each of the letters in the word together. For example, the word cats is equivalent to:

```<code>even + odd + even + even
</code>```

Which simplifies to:

```<code>odd + even
</code>```

Which simplifies further to:

```<code>odd
</code>```

So the word cats is odd.

Examples

```<code>Input:  trees
Output: even
</code>```

```<code>Input:  brush
Output: odd
</code>```

```<code>Input:  CAts
Output: odd
</code>```

```<code>Input:  Savoie
Output: even
</code>```

```<code>Input:  rhythm
Output: even
</code>```

Rules

All input will be a single word which will only contain alphabetical characters.

If the word is odd, output a truthy value. If the word is even, output a falsey value.

Winning

The shortest code in bytes wins.

Title: Is it an Odd Word?

Body:
O, 27 bytes

Q_e\'a-'e-'i-'o-'u-e\;-e01?


答:
JavaScript (ES6), 107 bytes

```<code>(n,l=Math.abs(n+n-n%2))=>[...Array(l--)].map((_,i,a)=>a.map((_,j)=>(j=Math.min(i,l-i,j,l-j),n<0?-n-j:j+1)))
</code>```

l is the size of the array. The n<0?-n-j:j+1 seems awkward but I can't find anything better.

Title: Create a pyramidal matrix

Body:
JavaScript (ES6), 107 bytes

(n,l=Math.abs(n+n-n%2))=>[...Array(l--)].map((_,i,a)=>a.map((_,j)=>(j=Math.min(i,l-i,j,l-j),n<0?-n-j:j+1)))

l is the size of the array. The n<0?-n-j:j+1 seems awkward but I can't find anything better.


问:
Wave-Particle Duality Laterally Programmatically
Write a program or function that takes in a nonempty single-line string. The string will either be zero or more spaces followed by one period (a particle), such as . or          ., or the string will be a sequence of one or more alternating forward and back slashes (a wave) that could start with either one, such as \ or /\/ or \/\/\/\/\/\/.

In either case, propagate the particle/wave to the right by one unit.

Specifically, in the particle case, insert a space before the ., moving it one place to the right, then output the resulting string. For example:

. →  .

 . →   .

  . →    .

   . →     .

    . →      .

     . →       .

      . →        .

       . →         .

In the wave case, append either / or \ appropriately so the wave keeps alternating and it's length increases by one, then output the resulting string. For example:

/ → /\

\ → \/

/\ → /\/

\/ → \/\

/\/ → /\/\

\/\ → \/\/

/\/\ → /\/\/

\/\/ → \/\/\

In either case, the output may not have trailing spaces but an optional trailing newline is allowed.

The shortest code in bytes wins.

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

```<code>f z@(x:_)|x<'/'=' ':z|x<'0'='\\':z|1<2='/':z
</code>```

Takes advantage of the fact that  < . < / < 0 < \ in the ASCII table to save two bytes

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

f z@(x:_)|x<'/'=' ':z|x<'0'='\\':z|1<2='/':z

Takes advantage of the fact that  < . < / < 0 < \ in the ASCII table to save two bytes


答:
Jelly, <s>14</s> 12 bytes

```<code>ḣJ$€ċÐff\ṪṪȯ
</code>```

Try it online! or verify all test cases.

How it works

```<code>ḣJ$€ċÐff\ṪṪȯ  Main link. Left argument: B. Right argument: A

  $€          Convert the two links to the left into a monadic chain and apply it
              to each string s in B.
 J              Generate the indices of s, i.e., [1, ..., len(s)].
ḣ               Head; for each index i, take the first i characters of s.
              This generates the prefixes of all strings in B.
     Ðf       Filter; keep prefixes for which the link to the left returns 1.
   ċ            Count the number of times A appears in the prefixes of that string.
       f\     Do a cumulative (i.e., keeping all intermediate values) reduce by
              filter, keeping only common prefixes. f/ is a more obvious choice,
              but it errors on an empty array, i.e., when A isn't a prefix of any
              string in B.
         Ṫ    Tail; take the last prefix array (if any) or return 0.
          Ṫ   Tail; take the last common prefix (if any) or return 0.
           ȯ  Logical OR (flat); replace 0 with A, leave strings untouched.
</code>```

Title: Implement tab completion

Body:
Jelly, <s>14</s> 12 bytes

ḣJ$€ċÐff\ṪṪȯ

Try it online! or verify all test cases.

How it works

ḣJ$€ċÐff\ṪṪȯ  Main link. Left argument: B. Right argument: A

  $€          Convert the two links to the left into a monadic chain and apply it
              to each string s in B.
 J              Generate the indices of s, i.e., [1, ..., len(s)].
ḣ               Head; for each index i, take the first i characters of s.
              This generates the prefixes of all strings in B.
     Ðf       Filter; keep prefixes for which the link to the left returns 1.
   ċ            Count the number of times A appears in the prefixes of that string.
       f\     Do a cumulative (i.e., keeping all intermediate values) reduce by
              filter, keeping only common prefixes. f/ is a more obvious choice,
              but it errors on an empty array, i.e., when A isn't a prefix of any
              string in B.
         Ṫ    Tail; take the last prefix array (if any) or return 0.
          Ṫ   Tail; take the last common prefix (if any) or return 0.
           ȯ  Logical OR (flat); replace 0 with A, leave strings untouched.


答:
J, <s>29</s> 26 bytes

```<code>1+**[:<./~**i.,2&|1&}.i.@-
</code>```

Usage

```<code>   f =: 1+**[:<./~**i.,2&|1&}.i.@-
   f 1
1
   f _1
1
   f 2
1 1 1 1
1 2 2 1
1 2 2 1
1 1 1 1
   f _2
2 2 2 2
2 1 1 2
2 1 1 2
2 2 2 2
   f 3
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
   f _3
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
</code>```

Explanation

The range i. verb outputs [0, 1, ..., n-1] for positive n and [n-1, n-2, ..., 0] for negative n which is useful here.

```<code>1+**[:<./~**i.,2&|1&}.i.@-  Input: integer n
                         -  Negate n
                      i.@   Creates range for -n
               2&|          Take n modulo 2, returns 0 or 1
                  1&}.      If n is odd, drop the first value from the range for -n
                            Else do nothing and pass it unmodified
              ,             Append it to
            i.              The range for n
          *                 Get the sign of n
           *                Multiply elementwise with the joined ranges
    [:<./~                  Form a table of the minimum values of the range
  *                         Get the sign of n
   *                        Multiply elementwise with the joined ranges
1+                          Add 1 to each and return
</code>```

Title: Create a pyramidal matrix

Body:
J, <s>29</s> 26 bytes

1+**[:<./~**i.,2&|1&}.i.@-

Usage

   f =: 1+**[:<./~**i.,2&|1&}.i.@-
   f 1
1
   f _1
1
   f 2
1 1 1 1
1 2 2 1
1 2 2 1
1 1 1 1
   f _2
2 2 2 2
2 1 1 2
2 1 1 2
2 2 2 2
   f 3
1 1 1 1 1
1 2 2 2 1
1 2 3 2 1
1 2 2 2 1
1 1 1 1 1
   f _3
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3

Explanation

The range i. verb outputs [0, 1, ..., n-1] for positive n and [n-1, n-2, ..., 0] for negative n which is useful here.

1+**[:<./~**i.,2&|1&}.i.@-  Input: integer n
                         -  Negate n
                      i.@   Creates range for -n
               2&|          Take n modulo 2, returns 0 or 1
                  1&}.      If n is odd, drop the first value from the range for -n
                            Else do nothing and pass it unmodified
              ,             Append it to
            i.              The range for n
          *                 Get the sign of n
           *                Multiply elementwise with the joined ranges
    [:<./~                  Form a table of the minimum values of the range
  *                         Get the sign of n
   *                        Multiply elementwise with the joined ranges
1+                          Add 1 to each and return


答:
Brainfuck, 24 bytes

```<code>,[>++[->++[<]>-]>-.>>>,]
</code>```

Try it online!

The same as my answer to a similar question.

Relies on 8-bit wrapping cells, the cell size might not matter (untested) but wrapping definitely is. The main part the program is the >++[->++[<]>-]>- does some rather convoluted things to flip the last bit of the number.

A shorter solution of 19 bytes is

```<code>,[+[<[-->>]<--]<.,]
</code>```

but this requires the < to noop if the data index is 0, instead of the more typical implementation of going into negative indeces.

Title: Invert a boolean array

Body:
A nice simple one

Input

Given a boolean array (Or an acceptable alternative), you can assume the array will never be more than 32 elements long.

```<code>[false, false, true, false, false]
</code>```

Output

Invert every element of the array and output it.

```<code>[true, true, false, true, true]
</code>```

Rules

You can write a full program or just a function

Standard loopholes apply

Shortest code in bytes, per language, wins!

Test cases

```<code>Input:
[true, false]
Output:
[false, true]

Input: //Example of acceptable alternative
[0,1,1]
Output:
[1,0,0]
</code>```

Body:
Brainfuck, 24 bytes

,[>++[->++[<]>-]>-.>>>,]

Try it online!

The same as my answer to a similar question.

Relies on 8-bit wrapping cells, the cell size might not matter (untested) but wrapping definitely is. The main part the program is the >++[->++[<]>-]>- does some rather convoluted things to flip the last bit of the number.

A shorter solution of 19 bytes is

,[+[<[-->>]<--]<.,]

but this requires the < to noop if the data index is 0, instead of the more typical implementation of going into negative indeces.


答:
c#, 17 words

This looks like pretty reasonable technical mumbo-jumbo.

I guess it can be extended a bit.

foreach is a bit stretching the rules.

Used this keyword list.

Try explicit operator, in case implicit string foreach virtual struct is as unsafe as this volatile lock.

Title: Write the longest sentence using keywords of a programming language

Body:
As the title said, the challenge is to write the longest sentence by only using the keywords of 1 programming language.

For instance, using the keywords of C++, it is possible to write this sentence:

do not try this float

What can you come up with?


问:
The shortest code to invert bit-wise a binary string
Me thinks there aren't enough easy questions on here that beginners can attempt!

The challenge: Given a random input string of 1's and 0's such as:

```<code>10101110101010010100010001010110101001010
</code>```

Write the shortest code that outputs the bit-wise inverse like so:

```<code>01010001010101101011101110101001010110101
</code>```

答:
Racket 71 bytes

```<code>(λ(s)(list->string(map(λ(x)(if(eq? x #\0)#\1 #\0))(string->list s))))
</code>```

Detailed version:

```<code>(define f
  (λ(s)
    (list->string
     (map
      (λ(x)
        (if(eq? x #\0)
           #\1
           #\0))
      (string->list s)))))

(f "1010111")
</code>```

Output:

```<code>"0101000"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Racket 71 bytes

(λ(s)(list->string(map(λ(x)(if(eq? x #\0)#\1 #\0))(string->list s))))

Detailed version:

(define f
  (λ(s)
    (list->string
     (map
      (λ(x)
        (if(eq? x #\0)
           #\1
           #\0))
      (string->list s)))))

(f "1010111")

Output:

"0101000"


答:
Vim, <s>152</s> 143 bytes

I'm sure this could be golfed more, especially those last two lines, but my brain is fried.

```<code>D:let@z=@-/abs(@-)
a"nywYp:s/\d/x/g<C-v>
YggP:%s/.*/x \0 x<C-v>
:%s/x\+/\=@n-@z/g<C-v>
<Esc>v0"qda<C-r>=@z<0?1:@-*@z
<Esc>@=@-%2?"":"YPJYp"
@=@-*@z-1.(@-*@z>1?"@q":"")
</code>```

Try it online!

Here it is in xxd format with unprintable characters:

```<code>0000000: 443a 6c65 7440 7a3d 402d 2f61 6273 2840  D:let@z=@-/abs(@
0000010: 2d29 0a61 226e 7977 5970 3a73 2f5c 642f  -).a"nywYp:s/\d/
0000020: 782f 6716 0a59 6767 503a 2573 2f2e 2a2f  x/g..YggP:%s/.*/
0000030: 7820 5c30 2078 160a 3a25 732f 785c 2b2f  x \0 x..:%s/x\+/
0000040: 5c3d 406e 2d40 7a2f 6716 0a1b 7630 2271  \=@n-@z/g...v0"q
0000050: 6461 123d 407a 3c30 3f31 3a40 2d2a 407a  da.=@z<0?1:@-*@z
0000060: 0a1b 403d 402d 2532 3f22 223a 2259 504a  ..@=@-%2?"":"YPJ
0000070: 5970 220a 403d 402d 2a40 7a2d 312e 2840  Yp".@=@-*@z-1.(@
0000080: 2d2a 407a 3e31 3f22 4071 223a 2222 29    -*@z>1?"@q":"")
</code>```

Explanation

It builds the pyramid from the center out, surrounding the center number with xes:

```<code>x x x
x 5 x
x x x
</code>```

Then it replaces the xes with the next number and surrounds it with xes again:

```<code>x x x x x
x 4 4 4 x
x 4 5 4 x
x 4 4 4 x
x x x x x
</code>```

...and so on. For even numbers it does the same thing but starts with a 2x2 base.

Here's the code "ungolfed." It's somewhat unconventional in that I "record" a macro by typing it into a buffer (hence all the <C-v>s) and then deleting it into a register, which is the best way I found to compose a macro without actually executing the keystrokes.

```<code>D:let@z=@-/abs(@-)<CR>       " Delete the input (into @-) and set @z to -1 if @- is negative; otherwise 1
a                            " Enter insert mode to compose the macro
  "nyw                         " Copy the number under the cursor to @n
  Yp                           " Copy this line and paste it below
  :s/\d/x/g<C-v><CR>           " Replace digits in the copy with 'x'
  YggP                         " Copy this line and paste it at the top of the buffer
  :%s/.*/x \0 x<C-v><CR>       " Add an 'x' before and after each line
  :%s/x\+/\=@n-@z/g<C-v><CR>   " Replace all 'x'es (and 'xx'es etc.) with the next number
<Esc>v0"qd                   " Done composing macro; delete it into @q (buffer is now empty)
a<C-r>=@z<0?1:@-*@z          " Append the center number (1 or abs(@-)) to the buffer
<Esc>@=@-%2?"":"YPJYp"       " If the input is even, make a 2x2 square
@=@-*@z-1.(@-*@z>1?"@q":"")  " Execute the macro abs(@-)-1 times if it's > 1
</code>```

Title: Create a pyramidal matrix

Body:
A pyramidal matrix is a square matrix where all numbers increase or decrease from the center point, like the two matrices below:

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

Or:

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

Given a non-zero integer n, create a pyramidal matrix where the numbers goes from 1 to n either in increasing order (if n<0), or decreasing order (if n>0) from the center. If n is even, then there will be 4 center numbers (see the examples).

As always:

Optional input and output format

Number of spaces, delimiter etc. is optional

Test cases:

```<code>1
1

-1
1

5
1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  1
1  2  3  3  3  3  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  4  5  4  3  2  1
1  2  3  4  4  4  3  2  1
1  2  3  3  3  3  3  2  1
1  2  2  2  2  2  2  2  1
1  1  1  1  1  1  1  1  1

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

```<code>2
1  1  1  1
1  2  2  1
1  2  2  1
1  1  1  1

-2
2  2  2  2
2  1  1  2
2  1  1  2
2  2  2  2

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

Body:
Vim, <s>152</s> 143 bytes

I'm sure this could be golfed more, especially those last two lines, but my brain is fried.

D:let@z=@-/abs(@-)
a"nywYp:s/\d/x/g<C-v>
YggP:%s/.*/x \0 x<C-v>
:%s/x\+/\=@n-@z/g<C-v>
<Esc>v0"qda<C-r>=@z<0?1:@-*@z
<Esc>@=@-%2?"":"YPJYp"
@=@-*@z-1.(@-*@z>1?"@q":"")

Try it online!

Here it is in xxd format with unprintable characters:

0000000: 443a 6c65 7440 7a3d 402d 2f61 6273 2840  D:let@z=@-/abs(@
0000010: 2d29 0a61 226e 7977 5970 3a73 2f5c 642f  -).a"nywYp:s/\d/
0000020: 782f 6716 0a59 6767 503a 2573 2f2e 2a2f  x/g..YggP:%s/.*/
0000030: 7820 5c30 2078 160a 3a25 732f 785c 2b2f  x \0 x..:%s/x\+/
0000040: 5c3d 406e 2d40 7a2f 6716 0a1b 7630 2271  \=@n-@z/g...v0"q
0000050: 6461 123d 407a 3c30 3f31 3a40 2d2a 407a  da.=@z<0?1:@-*@z
0000060: 0a1b 403d 402d 2532 3f22 223a 2259 504a  ..@=@-%2?"":"YPJ
0000070: 5970 220a 403d 402d 2a40 7a2d 312e 2840  Yp".@=@-*@z-1.(@
0000080: 2d2a 407a 3e31 3f22 4071 223a 2222 29    -*@z>1?"@q":"")

Explanation

It builds the pyramid from the center out, surrounding the center number with xes:

x x x
x 5 x
x x x

Then it replaces the xes with the next number and surrounds it with xes again:

x x x x x
x 4 4 4 x
x 4 5 4 x
x 4 4 4 x
x x x x x

...and so on. For even numbers it does the same thing but starts with a 2x2 base.

Here's the code "ungolfed." It's somewhat unconventional in that I "record" a macro by typing it into a buffer (hence all the <C-v>s) and then deleting it into a register, which is the best way I found to compose a macro without actually executing the keystrokes.

D:let@z=@-/abs(@-)<CR>       " Delete the input (into @-) and set @z to -1 if @- is negative; otherwise 1
a                            " Enter insert mode to compose the macro
  "nyw                         " Copy the number under the cursor to @n
  Yp                           " Copy this line and paste it below
  :s/\d/x/g<C-v><CR>           " Replace digits in the copy with 'x'
  YggP                         " Copy this line and paste it at the top of the buffer
  :%s/.*/x \0 x<C-v><CR>       " Add an 'x' before and after each line
  :%s/x\+/\=@n-@z/g<C-v><CR>   " Replace all 'x'es (and 'xx'es etc.) with the next number
<Esc>v0"qd                   " Done composing macro; delete it into @q (buffer is now empty)
a<C-r>=@z<0?1:@-*@z          " Append the center number (1 or abs(@-)) to the buffer
<Esc>@=@-%2?"":"YPJYp"       " If the input is even, make a 2x2 square
@=@-*@z-1.(@-*@z>1?"@q":"")  " Execute the macro abs(@-)-1 times if it's > 1


答:
Haskell, 67 bytes

(a:b)?(c:d)|a==c=a:(b?d)
_?_=""
s%l=foldr1(?)$max[s][x|x<-l,x?s==s]
```

The auxiliary function ? finds the longest common prefix of two strings by recursively taking the first character as long as it's the same for both strings and the strings are non-empty.

The main function % first keeps only the strings in the list that start with the given one s, checked by the longest common prefix with s being s. To handle there being no valid competitions, it adds s to an empty result via max. Then, it finds the longest common prefix of those by folding the binary function ?.

Title: Implement tab completion

Body:
Haskell, 67 bytes

(a:b)?(c:d)|a==c=a:(b?d)
_?_=""
s%l=foldr1(?)$max[s][x|x<-l,x?s==s]

The auxiliary function ? finds the longest common prefix of two strings by recursively taking the first character as long as it's the same for both strings and the strings are non-empty.

The main function % first keeps only the strings in the list that start with the given one s, checked by the longest common prefix with s being s. To handle there being no valid competitions, it adds s to an empty result via max. Then, it finds the longest common prefix of those by folding the binary function ?.


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

s,x=input();r='';q=1
for c in zip(*[t for t in x if s<=t<s+'ÿ']):q/=len(set(c));r+=c[0]*q
print r or s
```

For scoring purposes, ÿ can be replaced with a DEL byte. Test it on Ideone.

Thanks to @xnor for saving 5 bytes!

Title: Implement tab completion

Body:
Tab completion is a useful feature that auto-completes partially written commands.  You're going to be implementing it.

For example, if the available commands were ['apply','apple','apple pie','eat'], then a would complete to  appl, as all of the commands that start with a also start with appl.

Input/Output

You need to input a string, A, and a set of strings, B.

You need to output the longest common prefix of all B that starts with A.

If none of the options starts with A, then return A

You can assume that B is nonempty, and that all strings are nonempty

You cannot assume that any of the options start with A, nor that the common prefix will be longer than A

You can be case sensitive or case insensitive.

You only need to handle printable ASCII

Built-ins that explicitly do this task are allowed

Test cases:

```<code>'a'       ['apply','apple','apple pie','eat'] => 'appl'
'a'       ['apple pie']                       => 'apple pie'
'apple'   ['eat','dine']                      => 'apple'
'program' ['programa','programb']             => 'program'
'*%a('    ['*%a()-T>','*%a()-T<','@Da^n&']    => '*%a()-T'
'a'       ['abs','absolute','answer']         => 'a'
'a'       ['a','abs']                         => 'a'
'one to'  ['one to one','one to many']        => 'one to '
</code>```

Note the trailing space on the last test case

This is a code-golf, so make your answers as short as possible!

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

s,x=input();r='';q=1
for c in zip(*[t for t in x if s<=t<s+'ÿ']):q/=len(set(c));r+=c[0]*q
print r or s

For scoring purposes, ÿ can be replaced with a DEL byte. Test it on Ideone.

Thanks to @xnor for saving 5 bytes!


答:
Jelly, <s>9 8</s> 7 bytes

-1 byte thanks to @Dennis (use integer division, :, rather than not less than, <¬)

```<code>Ṁ:a⁸g/ḍ
</code>```

TryItOnline

How?

```<code>Ṁ:a⁸g/ḍ - Main link: capacities, goal
Ṁ       - maximum capacity
 :      - integer division with goal (effectively not less than goal since non-0 is True)
  a     - and
   ⁸    - left argument (capacities)
    g/  - gcd reduce over list (gcd of capacities)
      ḍ - divides
</code>```

Title: The Decanting Problem

Body:
Given N decanters (0 < N < 10) with that can hold C0 ... CN-1 liters (0 < C < 50) and a goal G liters, please determine if it is possible to reach that goal using only the following actions:

Fill a decanter

Empty a decanter

Pour from one decanter to another until the one being poured to is full or the one being poured from is empty

The goal amount G must be the amount of water in one of the containers at the end. You cannot have a 'output decanter'.

Examples

N: 2

C0: 5

C1: 12

G: 1

Result: Yes

N: 3

C0: 6

C1: 9

C2: 21

G: 5

Result: No

Hint: To calculate if it is possible, check to see if G is divisible by the GCD of the capacities. Also, make sure it will fit in a container.

Remember, this is code-golf, so the code with the lowest number of bytes wins.

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Jelly, <s>9 8</s> 7 bytes

-1 byte thanks to @Dennis (use integer division, :, rather than not less than, <¬)

Ṁ:a⁸g/ḍ

TryItOnline

How?

Ṁ:a⁸g/ḍ - Main link: capacities, goal
Ṁ       - maximum capacity
 :      - integer division with goal (effectively not less than goal since non-0 is True)
  a     - and
   ⁸    - left argument (capacities)
    g/  - gcd reduce over list (gcd of capacities)
      ḍ - divides


问:
String Distance

Challenge

Given an input of an all-lowercase string [a-z], output the total distance between the letters.

Example

```<code>Input: golf

Distance from g to o : 8
Distance from o to l : 3
Distance from l to f : 6

Output: 17
</code>```

Rules

Standard loopholes forbidden

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

The alphabet can be traversed from either direction. You must always use the shortest path. (i.e the distance between x and c is 5).

Test cases

```<code>Input: aa
Output: 0

Input: stack
Output: 18

Input: zaza
Output: 3

Input: valleys
Output: 35
</code>```

答:
C, <s>82 86 83</s> 76 bytes

```<code>t,u;f(char*s){for(t=0;*++s;u=*s-s[-1],t+=(u=u<0?-u:u)>13?26-u:u);return t;}
</code>```

Assumes input string is at least one character long. This doesn't require #include<stdlib.h>

Edit: Argh, sequence points!

Try it on Ideone

Title: String Distance

Body:
C, <s>82 86 83</s> 76 bytes

t,u;f(char*s){for(t=0;*++s;u=*s-s[-1],t+=(u=u<0?-u:u)>13?26-u:u);return t;}

Assumes input string is at least one character long. This doesn't require #include<stdlib.h>

Edit: Argh, sequence points!

Try it on Ideone


答:
Haskell, <s>56</s> 55 bytes

import Data.List
x%y|(0<$y)<(0<$x)=y%x|z<-y\\x=x++'_':z
```

-1 byte thanks to @xnor

Title: String Concatenation

Body:
The Challenge

Given two strings containing only lowercase letters and no spaces, the result should be the shorter string, followed by an underscore, followed by the longer string with the first instance of a character removed for each character it contains that is in the shorter string.

You can assume the strings will always be different lengths.

Test Cases:

```<code>sale
salinewater
Result: sale_inwater (only the first 'a' in salinewater is removed)

jostling
juggle
Result: juggle_ostin (juggle is the shorter string)

juggle
juggler
Result: juggle_r (a 'g' is removed for every 'g' in the shorter string)
</code>```

Rules

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

Body:
Haskell, <s>56</s> 55 bytes

import Data.List
x%y|(0<$y)<(0<$x)=y%x|z<-y\\x=x++'_':z

-1 byte thanks to @xnor


问:
Sylvester's sequence
Sylvester's sequence, OEIS A000058, is an integer sequence defined as follows:

Each member is the product of all previous members plus one.  The first member of the sequence is 2.

Task

Create a program to calculate the nth term of Sylvester's Sequence.  Standard input, output and loopholes apply.

Standard sequence rules apply.

This is code-golf, so the goal is to minimize the size of your source code as measured in bytes.

Test Cases

You may use either zero or one indexing. (Here I use zero indexing)

```<code>>>0
2
>>1
3
>>2
7
>>3
43
>>4
1807
</code>```

Title: Sylvester's sequence

Body:
Racket 74 bytes

(define(f n(l'(2)))(if(< n 2)(reverse l)(f(- n 1)(cons(+(apply * l)1)l))))

Detailed version:

(define (f n (l '(2)))
  (if (< n 2)
      (reverse l)
      (f (- n 1) (cons (+ 1 (apply * l)) l))))

Testing:

(f 7)

Output:

'(2 3 7 43 1807 3263443 10650056950807)


答:
Ruby, 41 words

True self, do not begin class break, end class break, ensure class break, redo
  and redo class break, retry class break, rescue class break, or yield
  class break, until next class end (or next class module or next class
  return), or else!

That's just using words listed as actual keywords. There are a lot of other words that act like keywords because they're methods of the kernel or instance methods of Class.

A cheesier approach would start

Do not def "alias","begin","break",...


问:
The Base in the mix
Input:

A list/array of integers for which each item is in the range of 2-36.

Output:

The sum of the integers (as base 10), where each next integer is in the base of the previous value (starting with a regular base 10).

Example:

Let's say we have an input like this: [4, 12, 34, 20, 14, 6, 25, 13, 33]

Then we have a sum like this:

```<code>4    (4  in base-10) +
6    (12 in base-4 ) +
40   (34 in base-12) +
68   (20 in base-34) +
24   (14 in base-20) +
6    (6  in base-14) +
17   (25 in base-6 ) +
28   (13 in base-26) +
42   (33 in base-13)
= 235
</code>```

Mathematical base explained:

I considered assuming everyone knows how base works, but I'll give a brief example of how it works anyway, just in case. Let's take the 34 in base-12 for example, how did we get 40?

```<code>1-34 in regular base-10:
 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34
 So, from 1 to 34 is 34 steps in base-10

1-34 in base-12:
 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 2A, 2B, 30, 31, 32, 33, 34
 So, from 1 to 34 is 40 steps in base-12
</code>```

Here is perhaps a useful calculator.

Challenge rules:

Array size will be in reasonable range (like 1-100 / see test cases).

The test cases will never contain integers of which the current value is invalid for it's previous base (i.e. You will never have something like 19 in base-6 or 6 in base-6, because base-6 only contains the digits 0-5).

You can take the input any way you'd like. Can be as an int-array, as a comma/space-separated string, etc. Your call. (You are also allowed to take the int-array reversed, which could be useful for stack-based programming languages.)

General Rules:

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

Don't let code-golf languages discourage you from posting answers with non-golfing languages. Try to come up with as short an answer as possible for any programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>[4, 12, 34, 20, 14, 6, 25, 13, 33]                            ->   235
 4+ 6+  40+ 68+ 24+ 6+ 17+ 28+ 42

[5, 14, 2, 11, 30, 18]                                        ->   90
 5+ 9+  2+ 3+  33+ 38

[12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 12, 2, 11, 3, 10, 2, 10]    ->   98
 12+ 13+ 11+ 9+ 8+ 7+ 6+ 5+ 4+ 3+ 5+  2+ 3+  3+ 3+  2+ 2

[36, 36]                                                      ->   150
 36+ 114
</code>```

答:
Java 7, <s>109</s> <s>89</s> 86 bytes

```<code>int c(int[]a){for(Byte i=1;i<a.length;a[0]+=i.valueOf(a[i]+"",a[++i-2]));return a[0];}
</code>```

Golfed 20 bytes thanks to @cliffroot (of which 12 because of a stupid mistake I made myself).

Ungolfed & test code:

Try it here.

```<code>class M{
  static int c(int[] a){
     for(Byte i = 1; i < a.length; a[0] += i.valueOf(a[i]+"", a[++i-2]));
     return a[0];
  }

  public static void main(String[] a){
    System.out.println(c(new int[]{ 4, 12, 34, 20, 14, 6, 25, 13, 33 }));
    System.out.println(c(new int[]{ 5, 14, 2, 11, 30, 18 }));
    System.out.println(c(new int[]{ 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 12, 2, 11, 3, 10, 2, 10 }));
    System.out.println(c(new int[]{ 36, 36 }));
  }
}
</code>```

Output:

```<code>235
90
98
150
</code>```

Title: The Base in the mix

Body:
Java 7, <s>109</s> <s>89</s> 86 bytes

int c(int[]a){for(Byte i=1;i<a.length;a[0]+=i.valueOf(a[i]+"",a[++i-2]));return a[0];}

Golfed 20 bytes thanks to @cliffroot (of which 12 because of a stupid mistake I made myself).

Ungolfed & test code:

Try it here.

class M{
  static int c(int[] a){
     for(Byte i = 1; i < a.length; a[0] += i.valueOf(a[i]+"", a[++i-2]));
     return a[0];
  }

  public static void main(String[] a){
    System.out.println(c(new int[]{ 4, 12, 34, 20, 14, 6, 25, 13, 33 }));
    System.out.println(c(new int[]{ 5, 14, 2, 11, 30, 18 }));
    System.out.println(c(new int[]{ 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 12, 2, 11, 3, 10, 2, 10 }));
    System.out.println(c(new int[]{ 36, 36 }));
  }
}

Output:

235
90
98
150


答:
Python 2, 75 bytes

import os
lambda s,x:os.path.commonprefix([t for t in x if s<=t<s+'ÿ'])or s
```

Thanks to @xnor for suggesting the built-in, originally used by  @BetaDecay in this answer.

For scoring purposes, ÿ can be replaced with a DEL byte. Test it on Ideone.

Title: Implement tab completion

Body:
Python 2, 75 bytes

import os
lambda s,x:os.path.commonprefix([t for t in x if s<=t<s+'ÿ'])or s

Thanks to @xnor for suggesting the built-in, originally used by  @BetaDecay in this answer.

For scoring purposes, ÿ can be replaced with a DEL byte. Test it on Ideone.


答:
05AB1E, <s>7</s> <s>6</s> 5 bytes

Uses the 05AB1E encoding.

Saved 1 byte using the new built-in š as suggested by Kevin Cruijssen

```<code>TšüöO
</code>```

Explanation

Input list is taken reversed, as allowed by challenge specification.

```<code>Tš     # prepend a 10 to the list
  üö   # reduce by conversion to base-10
    O  # sum
</code>```

Try it online!

Modified testsuite

Title: The Base in the mix

Body:
Input:

A list/array of integers for which each item is in the range of 2-36.

Output:

The sum of the integers (as base 10), where each next integer is in the base of the previous value (starting with a regular base 10).

Example:

Let's say we have an input like this: [4, 12, 34, 20, 14, 6, 25, 13, 33]

Then we have a sum like this:

```<code>4    (4  in base-10) +
6    (12 in base-4 ) +
40   (34 in base-12) +
68   (20 in base-34) +
24   (14 in base-20) +
6    (6  in base-14) +
17   (25 in base-6 ) +
28   (13 in base-26) +
42   (33 in base-13)
= 235
</code>```

Mathematical base explained:

I considered assuming everyone knows how base works, but I'll give a brief example of how it works anyway, just in case. Let's take the 34 in base-12 for example, how did we get 40?

```<code>1-34 in regular base-10:
 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34
 So, from 1 to 34 is 34 steps in base-10

1-34 in base-12:
 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 2A, 2B, 30, 31, 32, 33, 34
 So, from 1 to 34 is 40 steps in base-12
</code>```

Here is perhaps a useful calculator.

Challenge rules:

Array size will be in reasonable range (like 1-100 / see test cases).

The test cases will never contain integers of which the current value is invalid for it's previous base (i.e. You will never have something like 19 in base-6 or 6 in base-6, because base-6 only contains the digits 0-5).

You can take the input any way you'd like. Can be as an int-array, as a comma/space-separated string, etc. Your call. (You are also allowed to take the int-array reversed, which could be useful for stack-based programming languages.)

General Rules:

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

Don't let code-golf languages discourage you from posting answers with non-golfing languages. Try to come up with as short an answer as possible for any programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>[4, 12, 34, 20, 14, 6, 25, 13, 33]                            ->   235
 4+ 6+  40+ 68+ 24+ 6+ 17+ 28+ 42

[5, 14, 2, 11, 30, 18]                                        ->   90
 5+ 9+  2+ 3+  33+ 38

[12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 12, 2, 11, 3, 10, 2, 10]    ->   98
 12+ 13+ 11+ 9+ 8+ 7+ 6+ 5+ 4+ 3+ 5+  2+ 3+  3+ 3+  2+ 2

[36, 36]                                                      ->   150
 36+ 114
</code>```

Body:
05AB1E, <s>7</s> <s>6</s> 5 bytes

Uses the 05AB1E encoding.

Saved 1 byte using the new built-in š as suggested by Kevin Cruijssen

TšüöO

Explanation

Input list is taken reversed, as allowed by challenge specification.

Tš     # prepend a 10 to the list
  üö   # reduce by conversion to base-10
    O  # sum

Try it online!

Modified testsuite


答:
Actually, 12 bytes

```<code>;p(dX(♂$♀¿Σ+
</code>```

Try it online!

Explanation:

```<code>;p(dX(♂$♀¿Σ+
;             dupe input
 p            pop first element from list
  (dX         pop and discard last element from other copy
     (♂$      stringify all elements in first copy
        ♀¿    for each pair of elements in the two lists, interpret the first element as a base-(second element) integer
          Σ   sum
           +  add first element of original list
</code>```

Title: The Base in the mix

Body:
Actually, 12 bytes

;p(dX(♂$♀¿Σ+

Try it online!

Explanation:

;p(dX(♂$♀¿Σ+
;             dupe input
 p            pop first element from list
  (dX         pop and discard last element from other copy
     (♂$      stringify all elements in first copy
        ♀¿    for each pair of elements in the two lists, interpret the first element as a base-(second element) integer
          Σ   sum
           +  add first element of original list


Title: String Distance

Body:
Challenge

Given an input of an all-lowercase string [a-z], output the total distance between the letters.

Example

```<code>Input: golf

Distance from g to o : 8
Distance from o to l : 3
Distance from l to f : 6

Output: 17
</code>```

Rules

Standard loopholes forbidden

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

The alphabet can be traversed from either direction. You must always use the shortest path. (i.e the distance between x and c is 5).

Test cases

```<code>Input: aa
Output: 0

Input: stack
Output: 18

Input: zaza
Output: 3

Input: valleys
Output: 35
</code>```

Body:
PHP, 79 bytes

for($w=$argv[1];$w[++$i];)$s+=13-abs(13-abs(ord($w[$i-1])-ord($w[$i])));echo$s;


答:
Jelly, 7 bytes

```<code>ṙ1DḅṖḌS
</code>```

Try it online!

Title: The Base in the mix

Body:
Jelly, 7 bytes

ṙ1DḅṖḌS

Try it online!


答:
Perl, 54 bytes

Includes +2 for -Xp (can be combined with -e) and +3 for -i (cannot be combined)

Give dictionary on STDIN and the word after the -i option, e.g.:

```<code>perl -ia -Xpe '/^\Q$^I\E.*?(?{$F[$a{$&}++]=$&})^/}{$_=pop@F||$^I'
apply
apple
apple pie
eat
^D
</code>```

Just the code:

```<code>/^\Q$^I\E.*?(?{$F[$a{$&}++]=$&})^/}{$_=pop@F||$^I
</code>```

Title: Implement tab completion

Body:
Perl, 54 bytes

Includes +2 for -Xp (can be combined with -e) and +3 for -i (cannot be combined)

Give dictionary on STDIN and the word after the -i option, e.g.:

perl -ia -Xpe '/^\Q$^I\E.*?(?{$F[$a{$&}++]=$&})^/}{$_=pop@F||$^I'
apply
apple
apple pie
eat
^D

Just the code:

/^\Q$^I\E.*?(?{$F[$a{$&}++]=$&})^/}{$_=pop@F||$^I


答:
CJam, 15 bytes

```<code>l~{A\:A10bb}%:+
</code>```

Try it online!

Explanation

```<code>l~     e# Read and evaluate input.
{      e# Map this block over the input...
  A    e#   Push A. Initially this is 10, afterwards it will be the value of the
       e#   last iteration.
  \:A  e#   Swap with current value and store that in A for the next iteration.
  10b  e#   Convert to base 10 to get its decimal digits.
  b    e#   Interpret those in the base of the previous A.
}%
:+     e# Sum all of those values.
</code>```

Title: The Base in the mix

Body:
CJam, 15 bytes

l~{A\:A10bb}%:+

Try it online!

Explanation

l~     e# Read and evaluate input.
{      e# Map this block over the input...
  A    e#   Push A. Initially this is 10, afterwards it will be the value of the
       e#   last iteration.
  \:A  e#   Swap with current value and store that in A for the next iteration.
  10b  e#   Convert to base 10 to get its decimal digits.
  b    e#   Interpret those in the base of the previous A.
}%
:+     e# Sum all of those values.


答:
Java 8, 156 Bytes

```<code>String a(String x,String y){int l=x.length(),m=y.length();String b=l>m?x:y,s=m<l?y:x;for(char c:s.toCharArray()){b=b.replaceFirst(""+c,"");}return s+"_"+b;}
</code>```

This can probably be golfed some more.

Ungolfed & test cases

```<code>interface A {
    static String a(String x,String y){
        int l=x.length(),m=y.length();
        String b=l>m?x:y,s=m<l?y:x;
        for(char c:s.toCharArray()){
            b=b.replaceFirst(""+c,"");
        }
        return s+"_"+b;
    }

    static void main(String[]a) {
        System.out.println(a("sale","salinewater"));
        System.out.println(a("jostling","juggle"));
        System.out.println(a("juggle","juggler"));
    }
}
</code>```

Title: String Concatenation

Body:
Java 8, 156 Bytes

String a(String x,String y){int l=x.length(),m=y.length();String b=l>m?x:y,s=m<l?y:x;for(char c:s.toCharArray()){b=b.replaceFirst(""+c,"");}return s+"_"+b;}

This can probably be golfed some more.

Ungolfed & test cases

interface A {
    static String a(String x,String y){
        int l=x.length(),m=y.length();
        String b=l>m?x:y,s=m<l?y:x;
        for(char c:s.toCharArray()){
            b=b.replaceFirst(""+c,"");
        }
        return s+"_"+b;
    }

    static void main(String[]a) {
        System.out.println(a("sale","salinewater"));
        System.out.println(a("jostling","juggle"));
        System.out.println(a("juggle","juggler"));
    }
}


答:
Python 2, 52 bytes

f=lambda x:x[1:]and int(`x.pop()`,x[-1])+f(x)or x[0]
```

Test it on Ideone.

Title: The Base in the mix

Body:
Python 2, 52 bytes

f=lambda x:x[1:]and int(`x.pop()`,x[-1])+f(x)or x[0]

Test it on Ideone.


答:
Mathematica  <s>100</s> 80 unique words

Here's a start.  All standard words in Mathematica begin with upper case.
this includes I, the square root of negative 1.

On Sunday, And For All Times-- Assuming, On Opening Clear Dynamic Interactive Notebooks For Setting Contours,  I Do Not Translate  Missing Blue Arrays Which Span Temporary, Asynchronous, And Invisible Characters, Nor Do I Remove Undefined Arrowheads With Editable And Sound Outer Orange Roots Which Magnify Shallow Names Together With False Attributes (Because Most Axes Split Full Inner Kernels In Reverse Order)-- And While I Animate Undefined Quiet Ticks, I Begin With  Tolerance And Operate On All Manual Matrices, Interleaving Circle With Cylinder, Boxed Skeleton With Compiled Cuboid, Red Cross With Nearest Timing Pattern,
And Join Repeated Unique White Links With Heads ...

In case anyone is interested, here are 500+ words recognized by Mathematica (no additional libraries required). They are not all keywords, but experienced Mathematica programers will know and have used just about all of them.

{Abort, Above, Abs, Accumulate, Accuracy, AddTo, After, Alignment,
All, Alternatives, Analytic, And, Animate, Animator, Annotation,
Annuity, Antialiasing, Antisymmetric, Apart, Appearance, Append,
Apply, Array, Arrays, Arrow, Arrowheads, Assert, Assuming,
Assumptions, Asynchronous, Attributes, Automatic, Axes, Axis, Back,
Background, Backslash, Backward, Band, Baseline, Because, Beep,
Before, Begin, Below, Binarize, Binomial, Blank, Blend, Block, Blur,
Bookmarks, Booleans, Bottom, Bounds, Boxed, Break, Button, Byte,
Cancel, Cap, Cases, Cashflow, Catch, Ceiling, Cell, Cells, Censoring,
Center, Character, Characters, Check, Checkbox, Chop, Circle, Clear,
Clip, Clock, Close, Closed, Closing, Coarse, Coefficient, Collect,
Colon, Colorize, Column, Commonest, Compile, Compiled, Complement,
Complex, Compose, Composition, Compress, Condition, Cone, Congruent,
Conjunction, Connect, Constant, Constants, Context, Contexts,
Continue, Contours, Control, Convergents, Convolve, Copyable,
Correlation, Cot, Count, Covariance, Cross, Cumulant, Cup, Curl,
Cycles, Cylinder, Darker, Date, Debug, Decrement, Default, Defer,
[Degree], Deinitialization, Deletable, Delimiter, Delimiters,
Denominator, Deploy, Deployed, Depth, Derivative, Diagonal, Dialog,
Diamond, Differences, Dilation, Dimensions, Direction, Directive,
Disjunction, Disk, Dispatch, Display, Distribute, Distributed,
Dithering, Divide, Dividers, Divisible, Divisors, Do, Dot, Down,
Drop, Dynamic, Editable, Eigenvalues, Element, Eliminate, Empty,
Enabled, Encode, End, Enter, Epilog, Equal, Equivalent, Evaluator,
Except, Exists, Exit, Expand, Expectation, Exponent, Export,
Expression, Extract, Factor, Factorial, Fail, False, File, Filling,
Find, First, Fit, Flat, Flatten, Floor, Fold, Font, For, Forward,
Frame, Front, Full, Function, Gather, General, Generic, Get, Graph,
Graphics, Greater, Grid, Hash, Head, Heads, Histogram, Hold, Hue,
Hyperlink, Hyphenation, I, Identity, If, Image, Implies, In,
Increment, Inherited, Inner, Input, Insert, Inset, Install, Integer,
Integers, Integral, Integrate, Interactive, Interleaving, Interval,
Invisible, Item, Join, Joined, Kernels, Label, Labeled, Large,
Larger, Last, Latitude, Launch, Left, Legended, Length, Less, Level,
Lighting, Limit, Line, Links, List, Listable, Listen, Literal,
Locked, Log, Longest, Longitude, Magnification, Magnify, Majority,
Manipulate, Manual, Map, Masking, Material, Matrices, Maximize, Mean,
Median, Medium, Menu, Mesh, Message, Messages, Method, Minimize,
Minors, Missing, Modal, Mode, Modular, Module, Modulus, Moment,
Monday, Monitor, Most, Mouseover, Multinomial, Multiplicity,
Multiselection, Names, Nearest, Needs, Negative, Nest, Next, None,
Nor, Norm, Normal, Normalize, Not, Notebook, Notebooks, Null, Number,
Numerator, Off, Offset, On, Opacity, Open, Opening, Operate,
Optional, Options, Or, Order, Ordering, Orderless, Orthogonalize,
Out, Outer, Over, Overflow, Paclet, Pane, Panel, Paneled,
Parallelize, Parameter, Parenthesize, Part, Partition, Paste, Path,
Pattern, Pause, Permutations, Permute, Perpendicular, [Pi],
Piecewise, Pivoting, Placed, Placeholder, Plain, Play, Plot, Plus,
Point, Polygon, Polynomials, Position, Positive, Power, Precedence,
Precedes, Precision, Prefix, Prepend, Previous, Print, Probability,
Projection, Prolog, Properties, Property, Proportion, Protect,
Protected, Pruning, Put, Pyramid, Quantile, Quantity, Quartics,
Quartiles, Queueing, Quiet, Quit, Quotient, Radon, Random, Range, Raster, Rasterize, Rational, Rationals, Read, Real, Reap, Record,
Rectangle, Reduce, Refine, Refresh, Reinstall, Release, Remove,
Removed, Repeated, Replace, Resampling, Rescale, Residue, Resolve,
Rest, Return, Reverse, Riffle, Right, Root, Roots, Rotate, Round,
Row, Rule, Saturday, Save, Saveable, Scale, Scaled, Scan, Scrollbars,
Select, Selection, Sequence, Series, Set, Setbacks, Setter, Setting,
Shading, Shallow, Share, Sharpen, Short, Show, Sidebar, Sign,
Signature, Simplify, Skeleton, Skip, Slot, Smaller, Socket, Solve,
Sound, Sow, Spacer, Spacings, Span, Speak, Sphere, Splice, Split,
Square, Stack, Star, Streams, String, Stub, Subfactorial, Subgraph,
Subscripted, Subset, Subtract, Sum, Superset, Surd, Syntax, Table,
Take, Tally, Temporary, Text, Texture, Therefore, Thread, Threshold,
Through, Ticks, Times, Timing, Together, Toggle, Toggler, Tolerance,
Tooltip, Top, Total, Trace, Tracers, Translate, Transpose, True,
Tube, Tuples, Undefined, Underlined, Underscript, Unequal, Uninstall,
Union, Unique, Unitize, Unset, Up, Variables, Vertical, Wedge,
Weights, Which, While, Whitespace, With, Word, Write}

Body:
As the title said, the challenge is to write the longest sentence by only using the keywords of 1 programming language.

For instance, using the keywords of C++, it is possible to write this sentence:

do not try this float

What can you come up with?


Title: The Base in the mix

Body:
JavaScript ES6, <s>45</s> <s>42</s> 41 Bytes

const g =
     a=>a.map(v=>s+=parseInt(v,p,p=v),s=p=0)|s
;

console.log(g.toString().length);                                            // 42
console.log(g([4, 12, 34, 20, 14, 6, 25, 13, 33]));                          // 235
console.log(g([5, 14, 2, 11, 30, 18]  ));                                    // 90
console.log(g([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 12, 2, 11, 3, 10, 2, 10] )); // 98

Conventiently parseInt(x,0) === parseInt(x,10).

edit: Saved 1 byte thanks to @ETHproductions


答:
Retina, 39 bytes

```<code>\d+
$*
^(?>(1+)(,?\1)*;)(\1+)$(?<=\3.+)
</code>```

Input should be a comma-separated list of the decanters, followed by a semicolon, followed by the target volume. E.g.:

```<code>6,9,21;5
</code>```

Output is 0 (falsy) or 1 (truthy).

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

```<code>\d+
$*
</code>```

This just converts the input to unary. Afterwards we simply match valid inputs with a single regex:

```<code>^(?>(1+)(,?\1)*;)(\1+)$(?<=\3.+)
</code>```

The part inside (?>...) finds the GCD. We do this by finding the largest substring 1+ with which we can match all the decanters (allowing an optional , only after a full match of the GCD). The atomic group (the (?>...)) itself so that the regex engine doesn't backtrack to divisors of the GCD if the target volume can't be matched (otherwise group 1 will at some point be reduced to matching a single 1 and all inputs will be truthy).

Once we've found the GCD, we try to match the target volume as a multiple of it with a simple (\1+)$.

Finally, we check that the target volume not greater than the largest decanter's capacity, by ensuring that the volume can be matched inside any decanter with (?<=\3.+).

Title: The Decanting Problem

Body:
Given N decanters (0 < N < 10) with that can hold C0 ... CN-1 liters (0 < C < 50) and a goal G liters, please determine if it is possible to reach that goal using only the following actions:

Fill a decanter

Empty a decanter

Pour from one decanter to another until the one being poured to is full or the one being poured from is empty

The goal amount G must be the amount of water in one of the containers at the end. You cannot have a 'output decanter'.

Examples

N: 2

C0: 5

C1: 12

G: 1

Result: Yes

N: 3

C0: 6

C1: 9

C2: 21

G: 5

Result: No

Hint: To calculate if it is possible, check to see if G is divisible by the GCD of the capacities. Also, make sure it will fit in a container.

Remember, this is code-golf, so the code with the lowest number of bytes wins.

Leaderboards

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

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

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

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

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

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

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

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

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

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

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

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

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

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

```

Body:
Retina, 39 bytes

\d+
$*
^(?>(1+)(,?\1)*;)(\1+)$(?<=\3.+)

Input should be a comma-separated list of the decanters, followed by a semicolon, followed by the target volume. E.g.:

6,9,21;5

Output is 0 (falsy) or 1 (truthy).

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

\d+
$*

This just converts the input to unary. Afterwards we simply match valid inputs with a single regex:

^(?>(1+)(,?\1)*;)(\1+)$(?<=\3.+)

The part inside (?>...) finds the GCD. We do this by finding the largest substring 1+ with which we can match all the decanters (allowing an optional , only after a full match of the GCD). The atomic group (the (?>...)) itself so that the regex engine doesn't backtrack to divisors of the GCD if the target volume can't be matched (otherwise group 1 will at some point be reduced to matching a single 1 and all inputs will be truthy).

Once we've found the GCD, we try to match the target volume as a multiple of it with a simple (\1+)$.

Finally, we check that the target volume not greater than the largest decanter's capacity, by ensuring that the volume can be matched inside any decanter with (?<=\3.+).


问:
Compute the Carmichael function

Task description

In number theory, the Carmichael function λ takes a positive integer n and returns the least positive integer k so that the k-th power of each integer coprime to n equals 1 modulo n.

Given a positive integer n, your solution must compute λ(n). The shortest code in bytes wins.

Your program should theoretically work for arbitrarily large inputs, but doesn’t need to be efficient.

Tips

The sequence of all λ(n) is OEIS A002322.

An ungolfed Python implementation would look like

```<code>from fractions import gcd

def carmichael(n):
    coprimes = [x for x in range(1, n) if gcd(x, n) == 1]
    k = 1
    while not all(pow(x, k, n) == 1 for x in coprimes):
        k += 1
    return k
</code>```

(In Python, pow(A, B, C) efficiently computes pow(A, B) % C.)

Test cases

```<code>Input    Output
1        1
2        1
3        2
10       4
35       12
101      100
530      52
3010     84
6511     3056
10000    500
</code>```

答:
C++, <s>208 200 149 144 140</s> 134 bytes

```<code>[](int n){int k=1,x,a,b,t,d=1;for(;d;)for(d=x=0;++x<n;d=a<2&t>1?k++:d){for(a=x,b=n;t=b;a=t)b=a%b;for(t=1,b=k;b--;t=t*x%n);}return k;};
</code>```

A port of my C implementation.

Try it on Ideone

Title: Compute the Carmichael function

Body:
C++, <s>208 200 149 144 140</s> 134 bytes

[](int n){int k=1,x,a,b,t,d=1;for(;d;)for(d=x=0;++x<n;d=a<2&t>1?k++:d){for(a=x,b=n;t=b;a=t)b=a%b;for(t=1,b=k;b--;t=t*x%n);}return k;};

A port of my C implementation.

Try it on Ideone


答:
JavaScript (ES6), <s>54</s> <s>48</s> 40 bytes

I used a recursive approach.

```<code>f=([b,...a],c)=>b?parseInt(b,c)+f(a,b):0
</code>```

Saved 6 bytes, thanks to Lmis!

Saved 8 more bytes, thanks to Neil!

Title: The Base in the mix

Body:
JavaScript (ES6), <s>54</s> <s>48</s> 40 bytes

I used a recursive approach.

f=([b,...a],c)=>b?parseInt(b,c)+f(a,b):0

Saved 6 bytes, thanks to Lmis!

Saved 8 more bytes, thanks to Neil!


答:
Python 2, 48 bytes

```<code>lambda a:sum(int(`x`,y)for x,y in zip(a,[10]+a))
</code>```

Tests are at ideone

zip(a,[10]+a) traverses pairs of the values in a, and the previous value or 10 for the first

the backticks in the int call convert x to a string, s

int(s, y) converts the string s from the integer base y (if y is in [2,36] and s is valid)

sum does what it says on the tin

Title: The Base in the mix

Body:
Python 2, 48 bytes

lambda a:sum(int(`x`,y)for x,y in zip(a,[10]+a))

Tests are at ideone

zip(a,[10]+a) traverses pairs of the values in a, and the previous value or 10 for the first

the backticks in the int call convert x to a string, s

int(s, y) converts the string s from the integer base y (if y is in [2,36] and s is valid)

sum does what it says on the tin


答:
PHP, <s>53</s> 51 bytes

```<code>for(;$x=$argv[++$i];$b=$x)$s+=intval($x,$b);echo$s;
</code>```

Iterates over the input, converting each input to string variant. Then takes the integer value using the previous number as base. For the first number, the base will not be set, PHP will then start off with 10 (inferred from the number format).

Run like this (-d added for aesthetics only):

```<code>php -d error_reporting=30709 -r 'for(;$x=$argv[++$i];$b=$x)$s+=intval($x,$b);echo$s;' -- 12 11 10 9 8 7 6 5 4 3 12 2 11 3 10 2 10;echo
</code>```

Tweaks

Actually, no need to convert to string, as CLI arguments are already string. Saved 2 bytes.

Title: The Base in the mix

Body:
PHP, <s>53</s> 51 bytes

for(;$x=$argv[++$i];$b=$x)$s+=intval($x,$b);echo$s;

Iterates over the input, converting each input to string variant. Then takes the integer value using the previous number as base. For the first number, the base will not be set, PHP will then start off with 10 (inferred from the number format).

Run like this (-d added for aesthetics only):

php -d error_reporting=30709 -r 'for(;$x=$argv[++$i];$b=$x)$s+=intval($x,$b);echo$s;' -- 12 11 10 9 8 7 6 5 4 3 12 2 11 3 10 2 10;echo

Tweaks

Actually, no need to convert to string, as CLI arguments are already string. Saved 2 bytes.


答:
Python 3, 40 bytes

lambda a:sum(map(int,map(str,a),[10]+a))
```

Tests are at ideone

map(str, a) creates a generator, G, that calls str on each value in a, converting to strings

map(int, G, [10]+a) creates a generator that calls int(g, v) for pairs across G and [10]+a

int(g, v) converts the string g from the integer base v (if v is in [2,36] and g is valid)

sum does what it says on the tin

Title: The Base in the mix

Body:
Input:

A list/array of integers for which each item is in the range of 2-36.

Output:

The sum of the integers (as base 10), where each next integer is in the base of the previous value (starting with a regular base 10).

Example:

Let's say we have an input like this: [4, 12, 34, 20, 14, 6, 25, 13, 33]

Then we have a sum like this:

```<code>4    (4  in base-10) +
6    (12 in base-4 ) +
40   (34 in base-12) +
68   (20 in base-34) +
24   (14 in base-20) +
6    (6  in base-14) +
17   (25 in base-6 ) +
28   (13 in base-26) +
42   (33 in base-13)
= 235
</code>```

Mathematical base explained:

I considered assuming everyone knows how base works, but I'll give a brief example of how it works anyway, just in case. Let's take the 34 in base-12 for example, how did we get 40?

```<code>1-34 in regular base-10:
 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34
 So, from 1 to 34 is 34 steps in base-10

1-34 in base-12:
 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 1A, 1B, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 2A, 2B, 30, 31, 32, 33, 34
 So, from 1 to 34 is 40 steps in base-12
</code>```

Here is perhaps a useful calculator.

Challenge rules:

Array size will be in reasonable range (like 1-100 / see test cases).

The test cases will never contain integers of which the current value is invalid for it's previous base (i.e. You will never have something like 19 in base-6 or 6 in base-6, because base-6 only contains the digits 0-5).

You can take the input any way you'd like. Can be as an int-array, as a comma/space-separated string, etc. Your call. (You are also allowed to take the int-array reversed, which could be useful for stack-based programming languages.)

General Rules:

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

Don't let code-golf languages discourage you from posting answers with non-golfing languages. Try to come up with as short an answer as possible for any programming language.

Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters, full programs. Your call.

Default Loopholes are forbidden.

If possible, please add a link with a test for your code.

Also, please add an explanation if necessary.

Test cases:

```<code>[4, 12, 34, 20, 14, 6, 25, 13, 33]                            ->   235
 4+ 6+  40+ 68+ 24+ 6+ 17+ 28+ 42

[5, 14, 2, 11, 30, 18]                                        ->   90
 5+ 9+  2+ 3+  33+ 38

[12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 12, 2, 11, 3, 10, 2, 10]    ->   98
 12+ 13+ 11+ 9+ 8+ 7+ 6+ 5+ 4+ 3+ 5+  2+ 3+  3+ 3+  2+ 2

[36, 36]                                                      ->   150
 36+ 114
</code>```

Body:
Python 3, 40 bytes

lambda a:sum(map(int,map(str,a),[10]+a))

Tests are at ideone

map(str, a) creates a generator, G, that calls str on each value in a, converting to strings

map(int, G, [10]+a) creates a generator that calls int(g, v) for pairs across G and [10]+a

int(g, v) converts the string g from the integer base v (if v is in [2,36] and g is valid)

sum does what it says on the tin


Title: String Concatenation

Body:
The Challenge

Given two strings containing only lowercase letters and no spaces, the result should be the shorter string, followed by an underscore, followed by the longer string with the first instance of a character removed for each character it contains that is in the shorter string.

You can assume the strings will always be different lengths.

Test Cases:

```<code>sale
salinewater
Result: sale_inwater (only the first 'a' in salinewater is removed)

jostling
juggle
Result: juggle_ostin (juggle is the shorter string)

juggle
juggler
Result: juggle_r (a 'g' is removed for every 'g' in the shorter string)
</code>```

Rules

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

Body:
PHP, 154 Bytes

list($f,$s)=strlen($b=$argv[2])<strlen($a=$argv[1])?[$b,$a]:[$a,$b];foreach(str_split($f)as$x)$s=preg_replace("#(.*?)".$x."(.*)#","$1$2",$s);echo$f."_$s";

Instead of $s=preg_replace("#(.*?)".$x."(.*)#","$1$2",$s); you can also use if($z=strstr($s,$x))$s=strstr($s,$x,1).substr($z,1);


答:
Java, 86 bytes

```<code>s->{int[]b={10};return s.reduce(0,(r,n)->{r+=n.valueOf(""+n,b[0]);b[0]=n;return r;});}
</code>```

Testing and ungolfed

```<code>import java.util.function.ToIntFunction;
import java.util.stream.Stream;

public class Main {

  public static void main(String[] args) {
    ToIntFunction<Stream<Integer>> f = s -> {
      int[] b = {10};                 // Base, initialized with 10
      return s.reduce(0, (r, n) -> {  // Typical use of reduction, sum starts with 0.
        r += n.valueOf("" + n, b[0]); // Add the value in the previous base.
        b[0] = n;                     // Assign the new base;
        return r;
      });
    };

    System.out.println(f.applyAsInt(Stream.of(new Integer[]{4, 12, 34, 20, 14, 6, 25, 13, 33})));
  }
}
</code>```

Title: The Base in the mix

Body:
Java, 86 bytes

s->{int[]b={10};return s.reduce(0,(r,n)->{r+=n.valueOf(""+n,b[0]);b[0]=n;return r;});}

Testing and ungolfed

import java.util.function.ToIntFunction;
import java.util.stream.Stream;

public class Main {

  public static void main(String[] args) {
    ToIntFunction<Stream<Integer>> f = s -> {
      int[] b = {10};                 // Base, initialized with 10
      return s.reduce(0, (r, n) -> {  // Typical use of reduction, sum starts with 0.
        r += n.valueOf("" + n, b[0]); // Add the value in the previous base.
        b[0] = n;                     // Assign the new base;
        return r;
      });
    };

    System.out.println(f.applyAsInt(Stream.of(new Integer[]{4, 12, 34, 20, 14, 6, 25, 13, 33})));
  }
}


答:
C++, 25 unique words, 28 total

True friend, do goto register for this new short public class for
  private auto operator (while inline, return this signed template),
  else break & void this long volatile union.


答:
Haskell, <s>65</s> 59 bytes

b%x|x<1=x|y<-div x 10=b*b%y+x-10*y
sum.((10:)>>=zipWith(%))
```

Test it on Ideone.

Title: The Base in the mix

Body:
Haskell, <s>65</s> 59 bytes

b%x|x<1=x|y<-div x 10=b*b%y+x-10*y
sum.((10:)>>=zipWith(%))

Test it on Ideone.