问:
The plus-minus sequence

The plus-minus sequence

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

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

Test cases

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

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

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

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

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
C#, 50 bytes

```<code>f=(a,b)=>{Console.WriteLine(a+" "+b);f(a+b,a-b);};
</code>```

Full source, including test case:

```<code>using System;
using System.Numerics;

namespace PlusMinusSequence
{
    class Program
    {
        static void Main(string[] args)
        {
            Action<BigInteger,BigInteger>f=null;
            f=(a,b)=>{Console.WriteLine(a+" "+b);f(a+b,a-b);};
            BigInteger x=10, y=2;
            f(x,y);
        }
    }
}
</code>```

The BigInteger data type is used so the numbers don't overflow and become 0.
However, since it is a recursive solution, expect a stack overflow.

Title: The plus-minus sequence

Body:
C#, 50 bytes

f=(a,b)=>{Console.WriteLine(a+" "+b);f(a+b,a-b);};

Full source, including test case:

using System;
using System.Numerics;

namespace PlusMinusSequence
{
    class Program
    {
        static void Main(string[] args)
        {
            Action<BigInteger,BigInteger>f=null;
            f=(a,b)=>{Console.WriteLine(a+" "+b);f(a+b,a-b);};
            BigInteger x=10, y=2;
            f(x,y);
        }
    }
}

The BigInteger data type is used so the numbers don't overflow and become 0.
However, since it is a recursive solution, expect a stack overflow.


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

答:
Lua 214 203 182 bytes

function g(m, l, n,c)for i=1,m do if i+n < m then l[#l+1]=i;g(m,l,n+i,c+1)elseif i+n == m then l[#l+1]=i;print(unpack(l))end end for k=c,#l do l[k]=nil end end g(io.read()*1,{},0,0)
```
<p>Ungolved version.</p>
<pre class="lang-lua prettyprint-override"><code>function g(m, l, n,c)
    for i=1,m do
        if i+n < m then
            l[#l+1]=i
            g(m,l,n+i,c+1)
        elseif i+n == m then
            l[#l+1]=i
            print(unpack(l))
        end
    end
    for k=c,#l do
        l[k]=nil
    end
end
g(io.read()*1,{},0,0)
</code>```

Found a stray whitespace and removed an unnecessary variable to safe 11 bytes.
as it turns out, table.insert() is byte inefficient

ContentLicense: CC BY-SA 3.0

Title: List all ordered partitions of n

Body:
Lua 214 203 182 bytes

function g(m, l, n,c)for i=1,m do if i+n < m then l[#l+1]=i;g(m,l,n+i,c+1)elseif i+n == m then l[#l+1]=i;print(unpack(l))end end for k=c,#l do l[k]=nil end end g(io.read()*1,{},0,0)

Ungolved version.

function g(m, l, n,c)
    for i=1,m do
        if i+n < m then
            l[#l+1]=i
            g(m,l,n+i,c+1)
        elseif i+n == m then
            l[#l+1]=i
            print(unpack(l))
        end
    end
    for k=c,#l do
        l[k]=nil
    end
end
g(io.read()*1,{},0,0)

Found a stray whitespace and removed an unnecessary variable to safe 11 bytes.
as it turns out, table.insert() is byte inefficient


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

答:
PHP, <s>167</s> <s>160</s> <s>157</s> 152 bytes

```<code><?for($r=preg_grep("$^".preg_quote($s=$_GET[s])."$",$a=$_GET[a]);$r[0]>$s&&preg_grep("$^".preg_quote($t=$s.$r[0][strlen($s)])."$",$a)==$r;)$s=$t;echo$s;
</code>```

I could save 3 more bytes by assigning variables with preg_grep and preg_quote, but eh.

breakdown

```<code>for(
    // find items in $a that start with $s
    $r=preg_grep("$^".preg_quote($s=$_GET[s])."$",$a=$_GET[a]);
    // while the first match is longer than $s
    $r[0]>$s
    // and appending the next character of the first match
    &&preg_grep("$^".preg_quote($t=$s.$r[0][strlen($s)])."$",$a)
    // does not change the matches
    ==$r
;)
    // keep appending
    $s=$t;
return$s;
</code>```

Title: Implement tab completion

Body:
PHP, <s>167</s> <s>160</s> <s>157</s> 152 bytes

<?for($r=preg_grep("$^".preg_quote($s=$_GET[s])."$",$a=$_GET[a]);$r[0]>$s&&preg_grep("$^".preg_quote($t=$s.$r[0][strlen($s)])."$",$a)==$r;)$s=$t;echo$s;

I could save 3 more bytes by assigning variables with preg_grep and preg_quote, but eh.

breakdown

for(
    // find items in $a that start with $s
    $r=preg_grep("$^".preg_quote($s=$_GET[s])."$",$a=$_GET[a]);
    // while the first match is longer than $s
    $r[0]>$s
    // and appending the next character of the first match
    &&preg_grep("$^".preg_quote($t=$s.$r[0][strlen($s)])."$",$a)
    // does not change the matches
    ==$r
;)
    // keep appending
    $s=$t;
return$s;


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

答:
Perl, <s>35</s> <s>34</s> 33 bytes

Includes +2 for -ap

Run with the list of numbers on STDIN:

```<code>basemix.pl <<< "4 12 34 20 14 6 25 13 33";echo
</code>```

basemix.pl:

```<code>#!/usr/bin/perl -ap
$\+=$&+"$`$& 10"*/.$/*$`for@F}{
</code>```

I've been waiting for ages for a chance to use this abuse...

Explanation

The input numbers can have at most 2 digits. A number xy in base b is simply b*x+y. I'm going to use the regex /.$/ so the first digit ends up in $`</code> and the last digit in <code>$&</code>, so the contribution to the sum is <code>$&+$b*$`.

I abuse the fact that for does not properly localize the regex variables (like for example map and while do) so the results of a match in the previous loop is still available in the current loop. So if I'm careful about the order in which I do the operations the base is available as "$`$&"</code>, except for the very first loop where I need the base to be 10. So I use <code>"$`$& 10" instead

The way the first $& works is an abuse too since it is actually changed by the /.$/ while it is already on the stack waiting to be added.

The final abuse is the }{ at the end which changes the loop implied by -p from

```<code>LINE: while (defined($_ = <ARGV>)) {
    ...code..
}
continue {
    die "-p destination: $!\n" unless print $_;
}
</code>```

to

```<code>LINE: while (defined($_ = <ARGV>)) {
    ...code..
}
{
}
continue {
    die "-p destination: $!\n" unless print $_;
}
</code>```

Which means $_ will be undefined in the print, but it still adds $\ in which I accumulated the sum. It is also a standard golf trick to get post-loop processing

Title: The Base in the mix

Body:
Perl, <s>35</s> <s>34</s> 33 bytes

Includes +2 for -ap

Run with the list of numbers on STDIN:

basemix.pl <<< "4 12 34 20 14 6 25 13 33";echo

basemix.pl:

#!/usr/bin/perl -ap
$\+=$&+"$`$& 10"*/.$/*$`for@F}{

I've been waiting for ages for a chance to use this abuse...

Explanation

The input numbers can have at most 2 digits. A number xy in base b is simply b*x+y. I'm going to use the regex /.$/ so the first digit ends up in $`</code> and the last digit in <code>$&</code>, so the contribution to the sum is <code>$&+$b*$`.

I abuse the fact that for does not properly localize the regex variables (like for example map and while do) so the results of a match in the previous loop is still available in the current loop. So if I'm careful about the order in which I do the operations the base is available as "$`$&"</code>, except for the very first loop where I need the base to be 10. So I use <code>"$`$& 10" instead

The way the first $& works is an abuse too since it is actually changed by the /.$/ while it is already on the stack waiting to be added.

The final abuse is the }{ at the end which changes the loop implied by -p from

LINE: while (defined($_ = <ARGV>)) {
    ...code..
}
continue {
    die "-p destination: $!\n" unless print $_;
}

to

LINE: while (defined($_ = <ARGV>)) {
    ...code..
}
{
}
continue {
    die "-p destination: $!\n" unless print $_;
}

Which means $_ will be undefined in the print, but it still adds $\ in which I accumulated the sum. It is also a standard golf trick to get post-loop processing


答:
R, 41 bytes

The recursive solution, based on xnor's python solution:

```<code>f=function(a,b){cat(a,b,"\n");f(a+b,a-b)}
</code>```

For the first-k method, the code size doubles to 82 bytes:

```<code>function(a,b,k=Inf,i=1){cat(a,b,"\n");while(i<k){cat(a<-a+b,b<-a-b*2,"\n");i=i+1}}
</code>```

This function takes a and b as input, plus optionally k. If k is unspecified, it continues forever. (Well, until i overflows, which is a very big number, much larger than the recursion limit.)

ContentLicense: CC BY-SA 4.0

Title: The plus-minus sequence

Body:
The plus-minus sequence

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

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

Test cases

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

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

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

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

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

Catalog

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

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

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

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

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

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

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

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

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

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

Body:
R, 41 bytes

The recursive solution, based on xnor's python solution:

f=function(a,b){cat(a,b,"\n");f(a+b,a-b)}

For the first-k method, the code size doubles to 82 bytes:

function(a,b,k=Inf,i=1){cat(a,b,"\n");while(i<k){cat(a<-a+b,b<-a-b*2,"\n");i=i+1}}

This function takes a and b as input, plus optionally k. If k is unspecified, it continues forever. (Well, until i overflows, which is a very big number, much larger than the recursion limit.)


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

答:
Ruby, 65 bytes

```<code>->a,b{a,b=b,a if a.size>b.size;a.chars.map{|e|b.sub!e,""};a+?_+b}
</code>```

ungolfed

```<code>->a, b{
  a, b = b, a if a.size > b.size
  a.chars.map { |e|
    b.sub! e, ""
  }
  a + ?_ + b
}
</code>```

61 bytes(in case the argument is an array of strings)

```<code>->a{a.sort_by!(&:size);a[0].chars.map{|c|a[1].sub!c,""};a*?_}
</code>```

Thank you, m-chrzan!

Title: String Concatenation

Body:
Ruby, 65 bytes

->a,b{a,b=b,a if a.size>b.size;a.chars.map{|e|b.sub!e,""};a+?_+b}

ungolfed

->a, b{
  a, b = b, a if a.size > b.size
  a.chars.map { |e|
    b.sub! e, ""
  }
  a + ?_ + b
}

61 bytes(in case the argument is an array of strings)

->a{a.sort_by!(&:size);a[0].chars.map{|c|a[1].sub!c,""};a*?_}

Thank you, m-chrzan!


答:
Julia, 63 Bytes

```<code>f(l)=sum([parse(Int,string(l[i]),l[i-1])for i=2:length(l)])+l[]
</code>```

Parses each number (except the first) taking the previous element as base and sums. Adds the first element at the end

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:
Julia, 63 Bytes

f(l)=sum([parse(Int,string(l[i]),l[i-1])for i=2:length(l)])+l[]

Parses each number (except the first) taking the previous element as base and sums. Adds the first element at the end


答:
R, 161 bytes

This turned out to be much longer than I expected, albeit, string manipulation is usually tedious in R. I feel that this should easily be golfable by just using another approach.

```<code>function(x,y){s=strsplit;if(nchar(x)>nchar(y)){v=y;w=x}else{v=x;w=y};v=s(v,"")[[1]];w=s(w,"")[[1]];j=0;for(i in v){j=j+1;if(i==w[j])w[j]=""};cat(v,"_",w,sep="")}
</code>```

Ungofled

```<code>function(x,y){
    s=strsplit                      # alias for stringsplit
    if(nchar(x)>nchar(y)){v=y;w=x}  # assign v/w for the short/long strings
    else{v=x;w=y}
    v=s(v,"")[[1]]                  # split short string into vector
    w=s(w,"")[[1]]                  # split long string into vector
    j=0
    for(i in v){                    # for each char in short string, check
        j=j+1                       # if is equal to corresponding char in
        if(i==w[j])w[j]=""          # long, replace long with "" if true
    }
    cat(v,"_",w,sep="")             # insert _ and print
}
</code>```

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:
R, 161 bytes

This turned out to be much longer than I expected, albeit, string manipulation is usually tedious in R. I feel that this should easily be golfable by just using another approach.

function(x,y){s=strsplit;if(nchar(x)>nchar(y)){v=y;w=x}else{v=x;w=y};v=s(v,"")[[1]];w=s(w,"")[[1]];j=0;for(i in v){j=j+1;if(i==w[j])w[j]=""};cat(v,"_",w,sep="")}

Ungofled

function(x,y){
    s=strsplit                      # alias for stringsplit
    if(nchar(x)>nchar(y)){v=y;w=x}  # assign v/w for the short/long strings
    else{v=x;w=y}
    v=s(v,"")[[1]]                  # split short string into vector
    w=s(w,"")[[1]]                  # split long string into vector
    j=0
    for(i in v){                    # for each char in short string, check
        j=j+1                       # if is equal to corresponding char in
        if(i==w[j])w[j]=""          # long, replace long with "" if true
    }
    cat(v,"_",w,sep="")             # insert _ and print
}


问:
Outputting ordinal numbers (1st, 2nd, 3rd)
I would like to generate (as a return result of a function, or simply as the output of a program) the ordinal suffix of a positive integer concatenated to the number.

Samples:

```<code>1st
2nd
3rd
4th
...
11th
12th
13th
...
20th
21st
22nd
23rd
24th
</code>```

And so on, with the suffix repeating the initial 1-10 subpattern every 10 until 100, where the pattern ultimately starts over.

The input would be the number and the output the ordinal string as shown above.

What is the smallest algorithm for this?

Body:
Scala 2.11.7, 151 Chars

def o(x:Int*)=x map{
case a if(a%10)==1&&a%100!=11=>a+"st"
case b if(b%10)==2&&b%100!=12=>b+"nd"
case c if(c%10)==3&&c%100!=13=>c+"rd"
case e=>e+"th"
}

Usage

   o(1,2,3,4) -> ArrayBuffer("1st", "2nd", "3rd", "4th")


问:
Non-transitive dice game
Those of you who like Numberphile would be familiar with Dr. James Grime, who described a non-transitive dice game on his channel.

The game consists of three 6-faced dice:

Die 1: 3,3,3,3,3,6

Die 2: 2,2,2,5,5,5

Die 3: 1,4,4,4,4,4

Two players each select a die to use. They roll them and the higher die wins, best-of-whatever.

Probabilistically, die 1 beats dies 2 with >50% chance. Similarly, die 2 beats die 3, and, interestingly, die 3 beats die 1.

Write a program taking 1, 2 or 3 as input. This indicates the die the user chooses. The program then choose the die that would beat the user and output the results of 21 rolls, and "Computer/User wins with x points"

Rules

Code-golf, votes as tiebreaker

You must use RNG (or the likes) to actually simulate the dice rolls.

I am not too strict on output format. It's okay as long as you show the dices, somehow separate between the 21 rolls (in a way different from how you separate the dice in the same roll), and output that sentence above.

Input can be stdin, command line argument, from screen, etc.

Example

Input

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

Output

```<code>4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 6
1 3
4 3
4 3
1 3
4 3
1 3
4 3
4 3
4 3
4 3
4 6
 Computer wins with 16 points
</code>```

Here, the user chooses die 1 and his rolls are shown on the right column. The program chooses die 3 and beats him.

答:
Python 182

```<code>from random import*
u=2+input()
r=[eval("int(choice(`0x1d67e987c0e17c9`[i%3::3])),"*21)for i in(u,u-1)]
U,C=map(sum,r)
print r,['Us','Comput'][U<C]+'er wins with %d points'%abs(U-C)
</code>```

Title: Non-transitive dice game

Body:
Python 182

from random import*
u=2+input()
r=[eval("int(choice(`0x1d67e987c0e17c9`[i%3::3])),"*21)for i in(u,u-1)]
U,C=map(sum,r)
print r,['Us','Comput'][U<C]+'er wins with %d points'%abs(U-C)


问:
Checkmate (aka the urinal problem)
My Precalc teacher has one of his favorite problems that he made up (or more likely <s>stole</s> inspired by xkcd) that involves a row of n urinals. "Checkmate" is a situation in which every urinal is already occupied OR has an occupied urinal next to them. For instance, if a person is an X, then

X-X--X

is considered checkmate. Note that a person cannot occupy a urinal next to an already occupied urinal.

Task

Your program will take a number through stdin, command line args, or a function argument. Your program will then print out or return the number of ways that checkmate can occur in with the inputted number of urinals.

Examples

0 -> 1 (the null case counts as checkmate)

1 -> 1 (X)

2 -> 2 (X- or -X)

3 -> 2 (X-X or -X-)

4 -> 3 (X-X-, -X-X, or X--X)

5 -> 4 (X-X-X, X--X-, -X-X-, or -X--X)

6 -> 5 (X-X-X-, X--X-X, X-X--X, -X--X- or -X-X-X)

7 -> 7 (X-X-X-X, X--X-X-, -X-X--X, -X--X-X, X-X--X-, X--X--X or -X-X-X-)

8 -> 9 (-X--X--X, -X--X-X-, -X-X--X-, -X-X-X-X, X--X--X-, X--X-X-X, X-X--X-X, X-X-X--X, X-X-X-X-)

...

Scoring

The smallest program in bytes wins.

答:
05AB1E, 12 bytes

```<code>XXXIGX@DŠ0@+
</code>```

Explanation

```<code>XXX            # initialize stack as 1, 1, 1
   IG          # input-1 times do:
     X@        # get the item 2nd from bottom of the stack
       DŠ      # duplicate and push one copy down as 2nd item from bottom of the stack
         0@    # get the bottom item from the stack
           +   # add the top 2 items of the stack (previously bottom and 2nd from bottom)
               # implicitly print the top element of the stack after the loop
</code>```

Try it online!

Title: Checkmate (aka the urinal problem)

Body:
05AB1E, 12 bytes

XXXIGX@DŠ0@+

Explanation

XXX            # initialize stack as 1, 1, 1
   IG          # input-1 times do:
     X@        # get the item 2nd from bottom of the stack
       DŠ      # duplicate and push one copy down as 2nd item from bottom of the stack
         0@    # get the bottom item from the stack
           +   # add the top 2 items of the stack (previously bottom and 2nd from bottom)
               # implicitly print the top element of the stack after the loop

Try it online!


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

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

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

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

答:
SX, 38 bytes

```<code>的 webbrowser im**;o&('http:ppcg.ga')
</code>```

Save this shell script as SXexec.sh to your SX directory:

#!/bin/sh
N=$1.py;python Main.py $1;wine SXCompiler.exe $N;rm $N;python $N.py;rm $N.py
```
<p>The script features tidying up after execution. To execute the above script, you need to have Wine and Python. Usage is like this:</p>
```SXexec.sh file
```

Body:
SX, 38 bytes

的 webbrowser im**;o&('http:ppcg.ga')

Save this shell script as SXexec.sh to your SX directory:

#!/bin/sh
N=$1.py;python Main.py $1;wine SXCompiler.exe $N;rm $N;python $N.py;rm $N.py

The script features tidying up after execution. To execute the above script, you need to have Wine and Python. Usage is like this:

SXexec.sh file


问:
Is it a balanced number?
A number is balanced if the sum of the digits on each half of the number is equal, so: 1423 is balanced because 1+4 = 2+3, so is: 42615 because 4+2=1+5. Note that the middle digit is not included on either side (or it's included on both sides) if there's an odd number of digits.

Challenge:

Take a positive integer as input, and output a truthy value if it's balanced and a falsy value if it's unbalanced.

Test cases (true)

```<code>1
6
11
141
1221
23281453796004414
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
</code>```

Test cases (false)

```<code>10
12
110
15421
5234095123508321
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
</code>```

There will not be numbers starting with zero, for instance 00032 instead of 32. You must support numbers up to at least 100 digits (so larger than 2^64-1). As always, optional input format, so you may surround the number with apostrophes if desired.

答:
05AB1E, <s>14</s> 7 bytes

```<code>€D2äO`Q
</code>```

Explanation

Using 141 as example:

```<code>€D       # duplicate each (turns the number into a list of digits)
         # STACK: ['1','1','4','4','1','1']
  2ä     # split list in 2 (as we duplicated each element,
         # the middle element will exist on both sides for an odd length input
         # STACK: [['1','1','4'],['4','1','1']]
    O    # sum each sublist
         # STACK: [6,6]
     `   # flatten
         # STACK: 6, 6
      Q  # compare for equality
         # STACK: 1 (true)
</code>```

Try it online!

Title: Is it a balanced number?

Body:
05AB1E, <s>14</s> 7 bytes

€D2äO`Q

Explanation

Using 141 as example:

€D       # duplicate each (turns the number into a list of digits)
         # STACK: ['1','1','4','4','1','1']
  2ä     # split list in 2 (as we duplicated each element,
         # the middle element will exist on both sides for an odd length input
         # STACK: [['1','1','4'],['4','1','1']]
    O    # sum each sublist
         # STACK: [6,6]
     `   # flatten
         # STACK: 6, 6
      Q  # compare for equality
         # STACK: 1 (true)

Try it online!


答:
Pyke, 20 bytes

```<code>[QleQ`)>[R<]mmbms$X!
</code>```

Try it here!

Title: Is it a balanced number?

Body:
A number is balanced if the sum of the digits on each half of the number is equal, so: 1423 is balanced because 1+4 = 2+3, so is: 42615 because 4+2=1+5. Note that the middle digit is not included on either side (or it's included on both sides) if there's an odd number of digits.

Challenge:

Take a positive integer as input, and output a truthy value if it's balanced and a falsy value if it's unbalanced.

Test cases (true)

```<code>1
6
11
141
1221
23281453796004414
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
</code>```

Test cases (false)

```<code>10
12
110
15421
5234095123508321
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
</code>```

There will not be numbers starting with zero, for instance 00032 instead of 32. You must support numbers up to at least 100 digits (so larger than 2^64-1). As always, optional input format, so you may surround the number with apostrophes if desired.

Body:
Pyke, 20 bytes

[QleQ`)>[R<]mmbms$X!

Try it here!


Title: The Base in the mix

Body:
Ruby, 52 bytes

->a{eval a.zip([10]+a).map{|e|'"%s".to_i(%s)'%e}*?+}

ungolfed

->a{
  eval(
    a.zip([10]+a).map { |e|
      '"%s".to_i(%s)' % e
    }.join("+")
  )
}

usage

f=->a{eval a.zip([10]+a).map{|e|'"%s".to_i(%s)'%e}*?+}
p f[[4, 12, 34, 20, 14, 6, 25, 13, 33]] # => 235


Title: The Base in the mix

Body:
Matlab, 68 bytes

Not a very creative solution, but here it is:

function[s]=r(x);j=10;s=0;for(i=x)s=s+base2dec(num2str(i),j);j=i;end

Tests:

>> r([4,12,34,20,14,6,25,13,33])
ans =
   235
>> r([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 12, 2, 11, 3, 10, 2, 10])
ans =
   98
>> r([5, 14, 2, 11, 30, 18])
ans =
   90
>> r([36,36])
ans =
   150


答:
Haskell, <s>64</s> 63  bytes

```<code>b(a:t@(r:s))=a-last t+b(init t);b _=0
(==0).b.map fromEnum.show
</code>```

One Byte Saved thanks to nimi

Title: Is it a balanced number?

Body:
Haskell, <s>64</s> 63  bytes

b(a:t@(r:s))=a-last t+b(init t);b _=0
(==0).b.map fromEnum.show

One Byte Saved thanks to nimi


答:
Mathematica, 69

```<code>Tr@#[[;;⌊l=Length@#/2⌋]]==Tr@#[[⌈l⌉+1;;]]&@*IntegerDigits
</code>```

Title: Is it a balanced number?

Body:
Mathematica, 69

Tr@#[[;;⌊l=Length@#/2⌋]]==Tr@#[[⌈l⌉+1;;]]&@*IntegerDigits


问:
Count even steps of 196 algorithm
In the 196-algorithm one starts from an integer and then adds its reverse to it until a palindrome is reached, like this:

```<code>start -> 5280
5280 + 0825 = 6105
6105 + 5016 = 11121
11121 + 12111 = 23232
-end-
</code>```

Write a function that counts how many even numbers are visited before the algorithm ends. Starting and ending numbers are also counted, so, in the example above, visited are consider the numbers: 5280, 6105, 11121, 23232 but not 825, 5016 and 12111.

Examples:

```<code>f(5280) = 2
f(56) = 1
f(59) = 1
f(89) = 13
</code>```

Extended code golf rules apply: shortest number of instructions and operations (like +,-,mod,print,while,if,...) wins.

答:
Haskell 12 Operations

```<code>f n=1-n`rem`2+if q/=p then f(n+read p) else 0 where q=show n;p=reverse q
</code>```

New to Haskell. Need help to reduce it further.

Title: Count even steps of 196 algorithm

Body:
Haskell 12 Operations

f n=1-n`rem`2+if q/=p then f(n+read p) else 0 where q=show n;p=reverse q

New to Haskell. Need help to reduce it further.

ContentLicense: CC BY-SA 2.5


Title: Non-transitive dice game

Body:
Those of you who like Numberphile would be familiar with Dr. James Grime, who described a non-transitive dice game on his channel.

The game consists of three 6-faced dice:

Die 1: 3,3,3,3,3,6

Die 2: 2,2,2,5,5,5

Die 3: 1,4,4,4,4,4

Two players each select a die to use. They roll them and the higher die wins, best-of-whatever.

Probabilistically, die 1 beats dies 2 with >50% chance. Similarly, die 2 beats die 3, and, interestingly, die 3 beats die 1.

Write a program taking 1, 2 or 3 as input. This indicates the die the user chooses. The program then choose the die that would beat the user and output the results of 21 rolls, and "Computer/User wins with x points"

Rules

Code-golf, votes as tiebreaker

You must use RNG (or the likes) to actually simulate the dice rolls.

I am not too strict on output format. It's okay as long as you show the dices, somehow separate between the 21 rolls (in a way different from how you separate the dice in the same roll), and output that sentence above.

Input can be stdin, command line argument, from screen, etc.

Example

Input

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

Output

```<code>4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 3
4 6
1 3
4 3
4 3
1 3
4 3
1 3
4 3
4 3
4 3
4 3
4 6
 Computer wins with 16 points
</code>```

Here, the user chooses die 1 and his rolls are shown on the right column. The program chooses die 3 and beats him.

Body:
Mathematica <s>208</s> <s>172</s> <s>166</s> 159

Spaces added for clarity

b=Boole;{#, Row@{
         If[# > 10, "Play", "Comput"], "er wins with ",
         Max[#, 21 - #], " points"} &@ Total[b[#1 > #2] & @@@ #]} &@
   Table[1 + i + 3 b[6 Random[] > 2 i + 1],{21}, {i, {#, Mod[# + 1, 3]}}] &


答:
><>, <s>31</s> 29 bytes

```<code>i:0(?v
~00}v>
v+r+>l4(?
>{=n;
</code>```

Try it online!

Line 1: Standard input loop

Line 2: Discard the -1 on top of the stack, push two 0's and rotate one to the bottom of the stack (this ensures that inputs of length <3 don't exhaust the stack later in the program)

Line 3: If the length of the stack is >3, add the top two and bottom two elements of the stack together.

Line 4: If top and bottom of the stack are equal, output 1, 0 otherwise.

Edit: realised that there's no need to take the characters mod 12, 2 bytes saved

Title: Is it a balanced number?

Body:
><>, <s>31</s> 29 bytes

i:0(?v
~00}v>
v+r+>l4(?
>{=n;

Try it online!

Line 1: Standard input loop

Line 2: Discard the -1 on top of the stack, push two 0's and rotate one to the bottom of the stack (this ensures that inputs of length <3 don't exhaust the stack later in the program)

Line 3: If the length of the stack is >3, add the top two and bottom two elements of the stack together.

Line 4: If top and bottom of the stack are equal, output 1, 0 otherwise.

Edit: realised that there's no need to take the characters mod 12, 2 bytes saved


答:
Brachylog, 20 bytes

```<code>@eL@2tM,Lr@2t:M:+a#=
</code>```

Try it online!

Explanation

```<code>@eL                    Get the list of digits L of the input
  L@2tM,               Get the second half M of L
        Lr@2t          Get the second half of the reverse of L
             :M        The list [L, M]
               :+a#=   The sum of elements of L and the sum of elements of M must be equal
</code>```

Title: Is it a balanced number?

Body:
Brachylog, 20 bytes

@eL@2tM,Lr@2t:M:+a#=

Try it online!

Explanation

@eL                    Get the list of digits L of the input
  L@2tM,               Get the second half M of L
        Lr@2t          Get the second half of the reverse of L
             :M        The list [L, M]
               :+a#=   The sum of elements of L and the sum of elements of M must be equal


Title: Is it a balanced number?

Body:
Racket 204 bytes

(define(f n)(let*((s(number->string n))(g(λ(x y)(apply +(map(λ(x)(string->number(string x)))
(string->list(substring s x y))))))(l(string-length s))(h(/ l 2)))(if(=(g 0(floor h))(g(ceiling h)l))#t #f)))

Detailed version:

(define (f1 n)
(let* (  (s (number->string n))
         (g(λ(x y)
              (apply + (map
                        (λ(x)
                          (string->number
                           (string x)))
                        (string->list
                         (substring s x y))))))
         (l (string-length s))
         (h (/ l 2)))
    (if(= (g 0 (floor h)) (g (ceiling h) l))
       #t #f  ) ) )

Testing:

(f 23281453796004414)
(f 523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088)
(f 15421)
(f 5234095123508321)

Output:

#t
#t
#f
#f


答:
Python 3, <s>107</s> <s>102</s> 76 bytes

```<code>n=input()
l=len(n)
print(sum(map(int,n[:l//2]))==sum(map(int,n[l//2+l%2:])))
</code>```

-26 bytes by @Rod!

Title: Is it a balanced number?

Body:
Python 3, <s>107</s> <s>102</s> 76 bytes

n=input()
l=len(n)
print(sum(map(int,n[:l//2]))==sum(map(int,n[l//2+l%2:])))

-26 bytes by @Rod!


答:
PowerShell v2+, 85 bytes

```<code>param($a)!((,'('+$a[0..(($b=$a.length)/2-1)]+'0)-('+$a[($b/2)..$b]+'0)')-join'+'|iex)
</code>```

Takes input $a as a string (necessary to support numbers >2^64-1 without getting into extremely clunky [biginteger] casting on the command line).

For the explanation, let's assume input of '1423'. We're then constructing a new string. The two array slices are obvious ($a[...]), and that's surrounded by three additional strings (, 0)-(, and 0), formulating an array of chars and strings. Note the , at the front to enforce array concatenation, not string concatenation.

That whole array is -joined together with +, resulting in a string like (+1+4+0)-(+2+3+0), and you can see that the 0s are needed to prevent syntax errors. That's fed into |iex (short for Invoke-Expression and similar to eval), which will compute the mathematical result. So long as the string is balanced, you'll get 0 as an output, which we encapsulate in parens and take the Boolean-not thereof !(...), to output True. If it's any non-zero integer, it'll output False.

Test Cases

```<code>PS C:\Tools\Scripts\golfing> '1','6','11','141','23281453796004414','523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088'|%{$_;.\is-it-a-balanced-number.ps1 $_;'---'}
1
True
---
6
True
---
11
True
---
141
True
---
23281453796004414
True
---
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
True
---

PS C:\Tools\Scripts\golfing> '10','110','15421','5234095123508321','6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454'|%{$_;.\is-it-a-balanced-number.ps1 $_;'---'}
10
False
---
110
False
---
15421
False
---
5234095123508321
False
---
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
False
---
</code>```

Title: Is it a balanced number?

Body:
PowerShell v2+, 85 bytes

param($a)!((,'('+$a[0..(($b=$a.length)/2-1)]+'0)-('+$a[($b/2)..$b]+'0)')-join'+'|iex)

Takes input $a as a string (necessary to support numbers >2^64-1 without getting into extremely clunky [biginteger] casting on the command line).

For the explanation, let's assume input of '1423'. We're then constructing a new string. The two array slices are obvious ($a[...]), and that's surrounded by three additional strings (, 0)-(, and 0), formulating an array of chars and strings. Note the , at the front to enforce array concatenation, not string concatenation.

That whole array is -joined together with +, resulting in a string like (+1+4+0)-(+2+3+0), and you can see that the 0s are needed to prevent syntax errors. That's fed into |iex (short for Invoke-Expression and similar to eval), which will compute the mathematical result. So long as the string is balanced, you'll get 0 as an output, which we encapsulate in parens and take the Boolean-not thereof !(...), to output True. If it's any non-zero integer, it'll output False.

Test Cases

PS C:\Tools\Scripts\golfing> '1','6','11','141','23281453796004414','523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088'|%{$_;.\is-it-a-balanced-number.ps1 $_;'---'}
1
True
---
6
True
---
11
True
---
141
True
---
23281453796004414
True
---
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
True
---

PS C:\Tools\Scripts\golfing> '10','110','15421','5234095123508321','6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454'|%{$_;.\is-it-a-balanced-number.ps1 $_;'---'}
10
False
---
110
False
---
15421
False
---
5234095123508321
False
---
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
False
---


答:
C#, 83 bytes

```<code>n=>{var t=n+"";int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};
</code>```

Try it online!

Full source, including test case:

```<code>using System;
using System.Numerics;

namespace BalancedNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<BigInteger,bool>s= n=>{var t=n+"";int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};

            Console.WriteLine(s(1));    //true
            Console.WriteLine(s(6));    //true
            Console.WriteLine(s(11));   //true
            Console.WriteLine(s(141));  //true
            Console.WriteLine(s(23281453796004414));    //true
            BigInteger bi = BigInteger.Parse("523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088");
            Console.WriteLine(s(bi));   //true
            Console.WriteLine(s(10));   //false
            Console.WriteLine(s(12));   //false
            Console.WriteLine(s(110));  //false
            Console.WriteLine(s(15421));    //false
            Console.WriteLine(s(5234095123508321)); //false
            bi = BigInteger.Parse("6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454");
            Console.WriteLine(s(bi));   //false
        }
    }
}
</code>```

The BigInteger data type allows any number length. If the number is too large, the compiler complains (error CS1021: Integral constant is too large), so the BigInteger.Parse(String) method is used instead.

The solution can actually be reduced to 72 bytes considering the input is a string (and updating the program accordingly):

```<code>t=>{int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};
</code>```

Title: Is it a balanced number?

Body:
C#, 83 bytes

n=>{var t=n+"";int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};

Try it online!

Full source, including test case:

using System;
using System.Numerics;

namespace BalancedNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<BigInteger,bool>s= n=>{var t=n+"";int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};

            Console.WriteLine(s(1));    //true
            Console.WriteLine(s(6));    //true
            Console.WriteLine(s(11));   //true
            Console.WriteLine(s(141));  //true
            Console.WriteLine(s(23281453796004414));    //true
            BigInteger bi = BigInteger.Parse("523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088");
            Console.WriteLine(s(bi));   //true
            Console.WriteLine(s(10));   //false
            Console.WriteLine(s(12));   //false
            Console.WriteLine(s(110));  //false
            Console.WriteLine(s(15421));    //false
            Console.WriteLine(s(5234095123508321)); //false
            bi = BigInteger.Parse("6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454");
            Console.WriteLine(s(bi));   //false
        }
    }
}

The BigInteger data type allows any number length. If the number is too large, the compiler complains (error CS1021: Integral constant is too large), so the BigInteger.Parse(String) method is used instead.

The solution can actually be reduced to 72 bytes considering the input is a string (and updating the program accordingly):

t=>{int l=t.Length,i=0,r=0;for(;i<l/2;)r+=t[i]-t[l-1-i++];return r==0;};


问:
Find the minimum and maximum integers in an array, without using builtins

Challenge

Given an array of integers, received from stdin, function arguments, program arguments, or some other method:

Output only the minimum and maximum numbers in the array, through a return value, stdout, or other fitting methods.

Example session

```<code>> minmax( {0, 15, 2, 3, 7, 18, -2, 9, 6, -5, 3, 8, 9, -14} )
-14 18
</code>```

Reference implementation

```<code>// C++14

void minmax(std::vector<int> v) {
    int min = v[0]; int max = v[0];
    for(auto it : v) {
        if (*it < min)
            min = *it;
        if (*it > max)
            max = *it;
    }
    std::cout << min << ' ' << max << std::endl;
}
</code>```

Rules

You may not use a built-in function to calculate the values.

Standard loopholes disallowed.

Creative implementations encouraged.

This is code-golf, shortest answer wins but will not be selected.

Clarifications

If the array contains 1 element you need to output it twice.

If the minimum and maximum values are the same, you need to output them both.

答:
PHP, <s>66</s> 65 bytes

Note: this doesn't use any sort builtin. Also, PHP 7 required for the null coalesce operator.

```<code>for(;n|$x=$argv[++$i];$x>$h&&$h=$x)$l=min($l??$x,$x);echo"$l,$h";
</code>```

The max part is straightforward. The min part is a bit more elaborate. since in PHP null is less than 123, null needs to be handled. For this I'm using the null coalesce operator. If $l is null, use the current number ($x) instead, then take the smaller of the 2 numbers.

Run like this:

```<code>php -d error_reporting=30709 -r 'for(;n|$x=$argv[++$i];$x>$h&&$h=$x)$l=min($l??$x,$x);echo"$l,$h";' -- 0 15 2 3 7 18 -2 9 6 -5 3 8 9 -14;echo
</code>```

37 bytes (with sort)

Being allowed to sort makes it trivial (windows-1252 encoding):

```<code>php -d error_reporting=30709 -r '$a=$argv;echo$a[sort($a)],~ß,end($a);' -- 0 15 2 3 7 18 -2 9 6 -5 3 8 9 -14;echo
</code>```

Sort returns 1 when successful, and the list of arguments will start with - which will be sorted as the first item, so we need item 1 to yield min. Therefore we happen to be able to use the return value of sort as the index, saving 2 bytes.

Tweaks

Use n|"0" to make "0" truthy to continue the loop, instead of 0 ."0". Saved a byte

Body:
PHP, <s>66</s> 65 bytes

Note: this doesn't use any sort builtin. Also, PHP 7 required for the null coalesce operator.

for(;n|$x=$argv[++$i];$x>$h&&$h=$x)$l=min($l??$x,$x);echo"$l,$h";

The max part is straightforward. The min part is a bit more elaborate. since in PHP null is less than 123, null needs to be handled. For this I'm using the null coalesce operator. If $l is null, use the current number ($x) instead, then take the smaller of the 2 numbers.

Run like this:

php -d error_reporting=30709 -r 'for(;n|$x=$argv[++$i];$x>$h&&$h=$x)$l=min($l??$x,$x);echo"$l,$h";' -- 0 15 2 3 7 18 -2 9 6 -5 3 8 9 -14;echo

37 bytes (with sort)

Being allowed to sort makes it trivial (windows-1252 encoding):

php -d error_reporting=30709 -r '$a=$argv;echo$a[sort($a)],~ß,end($a);' -- 0 15 2 3 7 18 -2 9 6 -5 3 8 9 -14;echo

Sort returns 1 when successful, and the list of arguments will start with - which will be sorted as the first item, so we need item 1 to yield min. Therefore we happen to be able to use the return value of sort as the index, saving 2 bytes.

Tweaks

Use n|"0" to make "0" truthy to continue the loop, instead of 0 ."0". Saved a byte


Title: Is it a balanced number?

Body:
Ruby, 63 bytes

->s{e=s.chars*?+
l=s.size
e[l-1-r=l%2,2*r+1]="=="
l<2||eval(e)}

Note: arg s must be string.

Testing(minitest 5+ required):

require 'minitest/autorun'

class TestRunner < Minitest::Test
  def setup
    @truthy_nums = %w(1 6 11 141 23281453796004414 523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088)
    @falsy_nums = %w(10 110 15421 5234095123508321 6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454)

@f=->s{e=s.chars*?+
l=s.size
e[l-1-r=l%2,2*r+1]="=="
l<2||eval(e)}

  end
  def test_true
    @truthy_nums.each do |e|
      assert @f[e], e
    end
  end
  def test_false
    @falsy_nums.each do |e|
      assert !@f[e], e
    end
  end
end


答:
Java, 85 bytes

```<code>n->{int s=0,i=0,l=n.length();for(;i<l/2;)s+=n.charAt(i)-n.charAt(l-++i);return s==0;}
</code>```

Note: the input is given as String as Java can't handle without BigInteger (and BigIntegers are constructed using a... String.)

Testing and ungolfed:

```<code>import java.util.function.Predicate;

public class Main {

  public static void main(String[] args) {
    Predicate<String> f = n -> {
      int s = 0, i = 0, l = n.length();
      for (; i < l / 2;) {
        s += n.charAt(i) - n.charAt(l - ++i);
      }
      return s == 0;
    };

    String[] truthies = {"1",
      "6",
      "11",
      "141",
      "23281453796004414",
      "523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088"};
    for (String s : truthies) {
      boolean result = f.test(s);
      System.out.println(result);
    }
    String[] falsies = {"10",
      "12",
      "110",
      "15421",
      "5234095123508321",
      "6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454"};
    for (String s : falsies) {
      boolean result = f.test(s);
      System.out.println(result);
    }
  }
}
</code>```

Title: Is it a balanced number?

Body:
A number is balanced if the sum of the digits on each half of the number is equal, so: 1423 is balanced because 1+4 = 2+3, so is: 42615 because 4+2=1+5. Note that the middle digit is not included on either side (or it's included on both sides) if there's an odd number of digits.

Challenge:

Take a positive integer as input, and output a truthy value if it's balanced and a falsy value if it's unbalanced.

Test cases (true)

```<code>1
6
11
141
1221
23281453796004414
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
</code>```

Test cases (false)

```<code>10
12
110
15421
5234095123508321
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
</code>```

There will not be numbers starting with zero, for instance 00032 instead of 32. You must support numbers up to at least 100 digits (so larger than 2^64-1). As always, optional input format, so you may surround the number with apostrophes if desired.

Body:
Java, 85 bytes

n->{int s=0,i=0,l=n.length();for(;i<l/2;)s+=n.charAt(i)-n.charAt(l-++i);return s==0;}

Note: the input is given as String as Java can't handle without BigInteger (and BigIntegers are constructed using a... String.)

Testing and ungolfed:

import java.util.function.Predicate;

public class Main {

  public static void main(String[] args) {
    Predicate<String> f = n -> {
      int s = 0, i = 0, l = n.length();
      for (; i < l / 2;) {
        s += n.charAt(i) - n.charAt(l - ++i);
      }
      return s == 0;
    };

    String[] truthies = {"1",
      "6",
      "11",
      "141",
      "23281453796004414",
      "523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088"};
    for (String s : truthies) {
      boolean result = f.test(s);
      System.out.println(result);
    }
    String[] falsies = {"10",
      "12",
      "110",
      "15421",
      "5234095123508321",
      "6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454"};
    for (String s : falsies) {
      boolean result = f.test(s);
      System.out.println(result);
    }
  }
}


Title: Is it a balanced number?

Body:
Brain-Flak, <s>410</s> <s>206</s> <s>204</s> 178 + 3 = 181 bytes

Here is a 178 byte version that uses the -a flag.

26 bytes golfed off by DJMcMayhem

Try it Online

([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>){({}[()]<({}<>)<>>)}{}([]<>[[]]<>){(<{}{}>)}{}({{}<>[{}]<>}<(())>){{}{}((<>))}{}

Here is a longer 410 byte version that does not use the -a flag.

<a href="http://brain-flak.tryitonline.net/#code=eygoe30pKSg8KCgoKSgpKCkoKSgpKXt9PD4pPik8Pnsoe31bKCldKTw-KCh7fSgpWyh7fSldKSl7e30oPCh7fSh7fSkpPil9e308Pn17fTw-KHt9PHt9Pik8Pig8KCgoKSgpKCkoKSgpKXt9KDw-KSk-KTw-eyh7fVsoKV0pPD4oKHt9KClbKHt9PCh7fSgpKT4pXSkpe3t9KDwoe30oe308KHt9WygpXSk-KSk-KX17fTw-fXt9PD57fXt9KHt9PD4pfXt9PD4oW10pKDwoKCkoKSg8PikpPik8Pnsoe31bKCldKTw-KCh7fSgpWyh7fTwoe30oKSk-KV0pKXt7fSg8KHt9KHt9PCh7fVsoKV0pPikpPil9e308Pn17fTw-e317fSh7fTw-KXsoe31bKCldPCh7fTw-KTw-Pil9e30oW108PltbXV08Pil7e317fSg8Pil9e30oKFtdKTw-KSh7PHt9Pnt9PChbXSk-fXt9PD5bezx7fT57fTwoW10pPn17fV08KCgpKT4pe3t9e30oKDw-KSl9e30&input=MTI0MDM" rel="nofollow">Try it Online

{(({}))(<((()()()()()){}<>)>)<>{({}[()])<>(({}()[({})])){{}(<({}({}))>)}{}<>}{}<>({}<{}>)<>(<((()()()()()){}(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)}{}<>([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>){({}[()]<({}<>)<>>)}{}([]<>[[]]<>){{}{}(<>)}{}(([])<>)({<{}>{}<([])>}{}<>[{<{}>{}<([])>}{}]<(())>){{}{}((<>))}{}

Explanation

Here is an explanation of the shorter solution

To begin the number is converted to all of its ASCII values by the -a flag.

We push the stack height (i.e. number of digits) and divide by two.

([])(<(()()(<>))>)<>{({}[()])<>(({}()[({}<({}())>)])){{}(<({}({}<({}[()])>))>)}{}<>}{}<>{}{}({}<>)

For each number less than the number we just pushed we move a digit to the other stack

{({}[()]<({}<>)<>>)}{}

If the stacks have different heights we remove the top item from the current stack

([]<>[[]]<>){(<{}{}>)}{}

We want the difference between the sums of each stack.  So we use the following algorithm to sum each stack.

{{}}

This assumes no digit has an ASCII value of zero, which is a valid assumption.

We run this for both stacks and take the difference (The <(())> is necessary for the next part.

({{}}<>[{{}}]<(())>)

We now want to negate the sum.  If the sum is zero it will pop the top off revealing the one we pushed earlier otherwise it will remove both the number and the one and place a zero on top.

{{}{}((<>))}{}


答:
Perl, 29 bytes

Includes +5 for -lpF

Give number on STDIN

```<code>balanced.pl <<< 1423
</code>```

balanced.pl:

```<code>#!/usr/bin/perl -lpF
$;+=$_-pop@F for@F;$_=!$
</code>```

Title: Is it a balanced number?

Body:
Perl, 29 bytes

Includes +5 for -lpF

Give number on STDIN

balanced.pl <<< 1423

balanced.pl:

#!/usr/bin/perl -lpF
$;+=$_-pop@F for@F;$_=!$


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

答:
PHP, 91 bytes

```<code>foreach(str_split($argv[1])as$c)$n+=substr_count("AEIOU",strtoupper($c));if($n%2==0)echo 1;
</code>```

Outputs 1 for even word, empty for odd word.

Test online

Testing code:

```<code>$wa = array('trees','brush','CAts','Savoie','rhythm');
foreach ($wa as $w) {
    $n = 0;
    foreach(str_split($w) as $c)
        $n+=substr_count("AEIOU",strtoupper($c));
    if ($n%2==0) echo 1;
}
</code>```

Test online

Title: Is it an Odd Word?

Body:
PHP, 91 bytes

foreach(str_split($argv[1])as$c)$n+=substr_count("AEIOU",strtoupper($c));if($n%2==0)echo 1;

Outputs 1 for even word, empty for odd word.

Test online

Testing code:

$wa = array('trees','brush','CAts','Savoie','rhythm');
foreach ($wa as $w) {
    $n = 0;
    foreach(str_split($w) as $c)
        $n+=substr_count("AEIOU",strtoupper($c));
    if ($n%2==0) echo 1;
}

Test online


答:
PHP, <s>73</s> <s>67</s> <s>60</s> 57 bytes

Requires PHP 7.1 for negative string offsets:

```<code>for(;2*$x<strlen($a=$argn);)$s+=$a[$x++]-$a[-$x];echo!$s;
</code>```

Run:

```<code>echo 15324 | php -nR 'for(;2*$x<strlen($a=$argn);)$s+=$a[$x++]-$a[-$x];echo!$s;';echo
</code>```

Previous version

Note: requires PHP 7 for the spaceship operator.

```<code>for(;$x<$l=strlen($a=$argv[1]);)$s+=(2*$x<=>$l-1)*$a[$x++];echo!$s;
</code>```

Run like this:

```<code>php -d error_reporting=30709 -r 'for(;$x<$l=strlen($a=$argv[1]);)$s+=(2*$x<=>$l-1)*$a[$x++];echo!$s;' -- 15324;echo
</code>```

Explanation

Iterates over the digits in the number. Checks if the digit belongs to the first half or the second half (or is the middle digit) by comparing the digit's index to the length of the input with combined comparison (2 * $x <=> $l - 1). Then multiply that with the digit, take the sum of all digits. If it's a balanced number, the sum will be 0.

Example with input 15324:

```<code>  index     0  1  2  3  4
  digit     1  5  3  2  4

  2*index   0  2  4  6  8
  length-1  4  4  4  4  4
  factor    1  1  0 -1 -1  # Result of the spaceship operator

  result    1  5  0 -2 -4
           --------------
  sum                   0
</code>```

Tweaks

Don't set the digit to $d, just iterate the length of the input. Saved 5 bytes.

String offset null doesn't have to be cast to int for PHP to interpret it as 0. Saved 1 byte.

Using negative string offsets to get the digits from the second half and iterating to half of the string. Saved 7 bytes, but requires PHP 7.1

Saved 3 bytes by using $argn

Title: Is it a balanced number?

Body:
PHP, <s>73</s> <s>67</s> <s>60</s> 57 bytes

Requires PHP 7.1 for negative string offsets:

for(;2*$x<strlen($a=$argn);)$s+=$a[$x++]-$a[-$x];echo!$s;

Run:

echo 15324 | php -nR 'for(;2*$x<strlen($a=$argn);)$s+=$a[$x++]-$a[-$x];echo!$s;';echo

Previous version

Note: requires PHP 7 for the spaceship operator.

for(;$x<$l=strlen($a=$argv[1]);)$s+=(2*$x<=>$l-1)*$a[$x++];echo!$s;

Run like this:

php -d error_reporting=30709 -r 'for(;$x<$l=strlen($a=$argv[1]);)$s+=(2*$x<=>$l-1)*$a[$x++];echo!$s;' -- 15324;echo

Explanation

Iterates over the digits in the number. Checks if the digit belongs to the first half or the second half (or is the middle digit) by comparing the digit's index to the length of the input with combined comparison (2 * $x <=> $l - 1). Then multiply that with the digit, take the sum of all digits. If it's a balanced number, the sum will be 0.

Example with input 15324:

  index     0  1  2  3  4
  digit     1  5  3  2  4

  2*index   0  2  4  6  8
  length-1  4  4  4  4  4
  factor    1  1  0 -1 -1  # Result of the spaceship operator

  result    1  5  0 -2 -4
           --------------
  sum                   0

Tweaks

Don't set the digit to $d, just iterate the length of the input. Saved 5 bytes.

String offset null doesn't have to be cast to int for PHP to interpret it as 0. Saved 1 byte.

Using negative string offsets to get the digits from the second half and iterating to half of the string. Saved 7 bytes, but requires PHP 7.1

Saved 3 bytes by using $argn


Title: Is it a balanced number?

Body:
Python 2, <s>83</s> 77 bytes

g=[int(h)for h in raw_input()];b=int(len(g)/2);print sum(g[:b])==sum(g[-b:])or b==0

EDIT

reduced to 77 with help from @Rod

g=[int(h)for h in raw_input()];b=len(g)/2;print sum(g[:b])==sum(g[-b:])or b<1

Examples:

D:\>bal.py
1
True

D:\>bal.py
6
True

D:\>bal.py
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
True

D:\>bal.py
10
False

D:\>bal.py
110
False

D:\>bal.py
 6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
False


答:
Retina, <s>64</s> 44 bytes

```<code>^((.)*?).?(?=(?<-2>.)*$)
$1
\d
$*
^(1+) \1$
</code>```

Try it online

The first stage splits the string in the middle, omitting the middle character if there is one (<s>taken and modified from here.</s> Courtesy of Martin.) Then, replace digits with their unary representation, and match if the two halves are of equal length.

Title: Is it a balanced number?

Body:
Retina, <s>64</s> 44 bytes

^((.)*?).?(?=(?<-2>.)*$)
$1
\d
$*
^(1+) \1$

Try it online

The first stage splits the string in the middle, omitting the middle character if there is one (<s>taken and modified from here.</s> Courtesy of Martin.) Then, replace digits with their unary representation, and match if the two halves are of equal length.


Title: Is it a balanced number?

Body:
JavaScript (ES6), <s>74</s> <s>67</s> ... <s>59</s> 50 bytes

Recursively sums the difference of the first and last digits until there's less than two digits left:

let f =

n=>!(F=n=>n[1]?(n.pop()-n.shift()+F(n)):0)([...n])

// some truthy examples
console.log(f("11"));
console.log(f("141"));
console.log(f("523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088"));

// some falsy examples
console.log(f("12"));
console.log(f("110"));
console.log(f("6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454"));


答:
Javascript, 73 bytes

Good ol' ES5 loops

for(a=c=0,b=(l=(s=prompt()).length)-1;a<~-l/2;c-=s[a++]-s[b--]);alert(!c)```
</div>
</div>
</p>
<p>What's happening here?</p>
```for(
    a=c=0,               // a = left digits of the number
                         // c = the result
    b=                   // b = right digits of number
        (l=              // l = length of number - 1
            (s=prompt()) // s = the number as input from user
        .length)-1;

    a<~-l/2;             // while a < length of number / 2, rounded down (~-)

    c-=
        s[a++]           // c -= left digit
        -
        s[b--]           // c += right digit (because - and - == +)
 );
                         // for balanced numbers c should be 0
 alert(!c)               // 0 equals false in javascript, so output the opposite of c
```

Title: Is it a balanced number?

Body:
Javascript, 73 bytes

Good ol' ES5 loops

for(a=c=0,b=(l=(s=prompt()).length)-1;a<~-l/2;c-=s[a++]-s[b--]);alert(!c)

What's happening here?

for(
    a=c=0,               // a = left digits of the number
                         // c = the result
    b=                   // b = right digits of number
        (l=              // l = length of number - 1
            (s=prompt()) // s = the number as input from user
        .length)-1;

    a<~-l/2;             // while a < length of number / 2, rounded down (~-)

    c-=
        s[a++]           // c -= left digit
        -
        s[b--]           // c += right digit (because - and - == +)
 );
                         // for balanced numbers c should be 0
 alert(!c)               // 0 equals false in javascript, so output the opposite of c


答:
JavaScript (ES6), <s>59</s> <s>55</s> <s>51</s> <s>44</s> 42 bytes

```<code>f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n
</code>```

Turns out I was using the wrong strategy entirely. This version recursively finds the sum of the first half minus the sum of the second half, then returns the logical NOT of the result.

If we could return falsy in place of truthy and vice-versa, this would be 35 bytes:

```<code>f=([x,...a])=>a[0]?x-a.pop()+f(a):0
</code>```

Test snippet

f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id=I value="23281453796004414"><br>
<button onclick="console.log(`Result of f(${I.value}): `+f(I.value))">Run</button></code>```

Title: Is it a balanced number?

Body:
JavaScript (ES6), <s>59</s> <s>55</s> <s>51</s> <s>44</s> 42 bytes

f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n

Turns out I was using the wrong strategy entirely. This version recursively finds the sum of the first half minus the sum of the second half, then returns the logical NOT of the result.

If we could return falsy in place of truthy and vice-versa, this would be 35 bytes:

f=([x,...a])=>a[0]?x-a.pop()+f(a):0

Test snippet

f=([x,...a],n=0)=>a[0]?f(a,x-a.pop()+n):!n

<input id=I value="23281453796004414"><br>
<button onclick="console.log(`Result of f(${I.value}): `+f(I.value))">Run</button>


答:
Scala, 67 bytes

```<code>def f(a:Int*)=a zip(10+:a)map{t=>Integer.parseInt(""+t._1,t._2)}sum
</code>```

Explanation:

```<code>def f(a: Int*) =     //declare a method f with varargs of type Int as parameter
a zip (10 +: a)      //zip a with 10 prepended to a, resulting in...
                     //...Array((4,10), (12,4), (34,12), (20,34), (14,20), (6,14), (25,6), (13,25), (33,13))
map { t =>           //map each tuple t to...
  Integer.parseInt(  //...an integer by parsing...
    ""+t._1, t._2    //...a string of the first item in base-second-item.
  )
}
sum                  //and sum
</code>```

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:
Scala, 67 bytes

def f(a:Int*)=a zip(10+:a)map{t=>Integer.parseInt(""+t._1,t._2)}sum

Explanation:

def f(a: Int*) =     //declare a method f with varargs of type Int as parameter
a zip (10 +: a)      //zip a with 10 prepended to a, resulting in...
                     //...Array((4,10), (12,4), (34,12), (20,34), (14,20), (6,14), (25,6), (13,25), (33,13))
map { t =>           //map each tuple t to...
  Integer.parseInt(  //...an integer by parsing...
    ""+t._1, t._2    //...a string of the first item in base-second-item.
  )
}
sum                  //and sum


问:
Shortest way to reverse a number
Write a function (or equivalent subprogram) to accept a single integer valued argument and return a (similarly typed) value found by reversing the order of the base-10 digits of the argument.

For example given 76543 return 34567

答:
BaCon

```<code>PRINT REVERSE$(STR$(76543))
</code>```

Replace 76543 with any number.

OwnerDisplayName: eltond

Title: Shortest way to reverse a number

Body:
BaCon

PRINT REVERSE$(STR$(76543))

Replace 76543 with any number.


Title: Is it a balanced number?

Body:
sed (165 + 1 for -r) 166

/^.$/c1
:l;s,^([^!])([^!]*)([^!])!?([^=]*)=?(.*),\2!\4\1=\5\3,;tl;:
s,.?!|0,,;s,2,11,;s,3,21,;s,4,31,;s,5,41,;s,6,51,;s,7,61,
s,8,71,;s,9,81,;t;s,1=1,=,;t;/^=$/c1
c0

Output:

1 for true

0 for false

<a href="http://sed.tryitonline.net/#code=L14uJC9jMQo6bDtzLF4oW14hXSkoW14hXSopKFteIV0pIT8oW149XSopPT8oLiopLFwyIVw0XDE9XDVcMyw7dGw7OgpzLC4_IXwwLCw7cywyLDExLDtzLDMsMjEsO3MsNCwzMSw7cyw1LDQxLDtzLDYsNTEsO3MsNyw2MSwKcyw4LDcxLDtzLDksODEsO3Q7cywxPTEsPSw7dDsvXj0kL2MxCmMw&input=MQo2CjExCjE0MQoxMjIxCjIzMjgxNDUzNzk2MDA0NDE0CjUyMzQyODEyMTY1NjY2NjY1NTY1NTU1NjY1NTY1NjUwMjgwOTc0NTI0OTU1MjQ2NjMzOTA4OTcwMjM2MTcxNjQ3Nzk4MzYxMDc1NDk2Njg4NTEyODA0MTk3NTQwNjAwNTA4OAoxMAoxMgoxMTAKMTU0MjEKNTIzNDA5NTEyMzUwODMyMQo2MjQwOTExMzE0Mzk5MDcyNDU5NDkzNzY1NjYxMTkxMDU4NjEzNDkxODYzMTQ0MTUyMzUyMjYyODk3MzUxOTg4MjUwNDMxMTQwNTQ2NjYwMDM1NjQ4Nzk1MzE2NzQwMjEyNDU0&args=LXI" rel="nofollow">Try it online!


答:
PHP, 156 Bytes

with much Help from Titus Thank You

```<code><?foreach($_GET[t]as$v)if(strstr($v,$s=$_GET[s])==$v)$r[]=$z=$v;for(;$i++<strlen($z);){$s=substr($z,0,$i);foreach($r as$x)if($x[$i]!=$z[$i])break 2;}echo$s;
</code>```

PHP, 199 Bytes

32 Bytes saves by Titus with array_unique

```<code><?foreach($_GET[t]as$v)if(strstr($v,$s=$_GET[s])==$v)$r[]=$v;for(;$i++<strlen($r[0]);$a=[]){foreach($r as$x)$a[]=substr($x,0,$i);if(count($r)==count($a)&count(array_unique($a))<2)$s=$a[0];}echo$s;
</code>```

I know that the Regex Solution by Titus was shorter till Titus help me to improve my way. Maybe the way I found is interesting for you

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:
PHP, 156 Bytes

with much Help from Titus Thank You

<?foreach($_GET[t]as$v)if(strstr($v,$s=$_GET[s])==$v)$r[]=$z=$v;for(;$i++<strlen($z);){$s=substr($z,0,$i);foreach($r as$x)if($x[$i]!=$z[$i])break 2;}echo$s;

PHP, 199 Bytes

32 Bytes saves by Titus with array_unique

<?foreach($_GET[t]as$v)if(strstr($v,$s=$_GET[s])==$v)$r[]=$v;for(;$i++<strlen($r[0]);$a=[]){foreach($r as$x)$a[]=substr($x,0,$i);if(count($r)==count($a)&count(array_unique($a))<2)$s=$a[0];}echo$s;

I know that the Regex Solution by Titus was shorter till Titus help me to improve my way. Maybe the way I found is interesting for you


问:
Prime factors buddies
Given an integer N > 1, output all other numbers which prime decompositions have the same digits as the prime decomposition of N.

For example, if N = 117, then the output must be [279, 939, 993, 3313, 3331], because

```<code>117 = 3 × 3 × 13
</code>```

therefore, the available digits are 1, 3, 3 and 3 and we have

```<code>279  = 3 × 3 × 31
939  = 3 × 313
993  = 3 × 331
3313 = 3313
3331 = 3331
</code>```

Those are the only other possible numbers, because other combination of these digits yield non-prime integers, which can't be the result of prime factorization.

If N is any of 117, 279, 939, 993, 3313 or 3331, then the output will contain the five other numbers: they are prime factors buddies.

You cannot use leading zeroes to get primes, e.g. for N = 107, its only buddy is 701 (017 is not considered).

Input and Outputs

The input and output buddies must be taken and returned in the decimal base.

N will always be strictly greater than 1.

The output can be formatted rather freely, as long as it only contains the buddies and separators/list syntactic elements.

The ordering of the output is unimportant.

You may take the input through STDIN, as a function argument or anything similar.

You may print the output to STDOUT, return it from a function, or anything similar.

Test cases

Your program should solve any of the test cases below in less than a minute.

```<code>N        Buddies
2        []
4        []
8        []
15       [53]
16       []
23       [6]
42       [74, 146, 161]
126      [222, 438, 483, 674, 746, 851, 1466, 1631, 1679]
204      [364,548,692,762,782,852,868,1268,1626,2474,2654,2921,2951,3266,3446,3791,4274,4742,5426,5462,6233,6434,6542,7037,8561,14426,14642,15491,15833,22547]
</code>```

Scoring

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

答:
PowerShell v3+, 450 bytes

```<code>param($n)function f{param($a)for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}}}
$y=($x=@((f $n)-split'(.)'-ne''|sort))|?{$_-eq(f $_)}
$a,$b=$x
$a=,$a
while($b){$z,$b=$b;$a=$a+($a+$y|%{$c="$_";0..$c.Length|%{-join($c[0..$_]+$z+$c[++$_..$c.Length])};"$z$c";"$c$z"})|select -u}
$x=-join($x|sort -des)
$l=@();$a|?{$_-eq(f $_)}|%{$j=$_;for($i=0;$i-le$x;$i+=$j){if(0-notin($l|%{$i%$_})){if(-join((f $i)-split'(.)'|sort -des)-eq$x){$i}}}$l+=$j}|?{$_-ne$n}
</code>```

Finally!

PowerShell doesn't have any built-ins for primality checking, factorization, or permutations, so this is completely rolled by hand. I worked through a bunch of optimization tricks to try and reduce the time complexity down to something that will fit in the challenge restrictions, and I'm happy to say that I finally succeeded --

```<code>PS C:\Tools\Scripts\golfing> Measure-Command {.\prime-factors-buddies.ps1 204}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 27
Milliseconds      : 114
Ticks             : 271149810
TotalDays         : 0.000313830798611111
TotalHours        : 0.00753193916666667
TotalMinutes      : 0.45191635
TotalSeconds      : 27.114981
TotalMilliseconds : 27114.981
</code>```

Explanation

There's a lot going on here, so I'll try to break it down.

The first line takes input $n and defines a function, f. This function uses accumulative trial division to come up with a list of the prime factors. It's pretty speedy for small inputs, but obviously bogs down if the input is large. Thankfully all the test cases are small, so this is sufficient.

The next line gets the factors of $n, -splits them on every digit ignoring any empty results (this is needed due to how PowerShell does regex matching and how it moves the pointer through the input and is kinda annoying for golfing purposes), then sorts the results in ascending order. We store that array of digits into $x, and use that as the input to a |?{...} filter to pull out only those that are themselves prime. Those prime digits are stored into $y for use later.

We then split $x into two components. The first (i.e., smallest) digit is stored into $a, while the rest are passed into $b. If $x only has one digit, then $b will be empty/null. We then need to re-cast $a as an array, so we use the comma operator quick-like to do so.

Next, we need to construct all possible permutations of the digits. This is necessary so our division tests later skip a bunch of numbers and make things faster overall.

So long as there's element left in $b, we peel off the first digit into $z and leave the remaining in $b. Then, we need to accumulate into $a the result of some string slicing and dicing. We take $a+$y as array concatenation, and for each element we construct a new string $c, then loop through $c's .length and insert $z into every position, including prepending $z$c and appending $c$z, then selecting only the -unique elements. That's again array-concatenated with $a and re-stored back into $a. Yes, this does wind up having goofy things happen, like you can get 3333 for input 117, which isn't actually a permutation, but this is much shorter than attempting to explicitly filter them out, ensures that we get every permutation, and is only very marginally slower.

So, now $a has an array of all possible (and then some) permutations of the factor's digits. We need to re-set $x to be our upper-bound of possible results by |sorting the digits in -descending order and -joining them back together. Obviously, no output value can be larger than this number.

We set our helper array $l to be an array of values that we've previously seen. Next, we're pulling out every value from $a (i.e., those permutations) that are prime, and enter a loop that is the biggest time sink of the whole program...

Every iteration, we're looping from 0 to our upper bound $x, incrementing by the current element $j. So long as the $i value we're considering is not a multiple of a previous value (that's the 0-notin($l|%{$i%$_}) section), it's a potential candidate for output. If we take the factors of $i, sort them, and they -equal $x, then add the value to the pipeline. At the end of the loop, we add our current element $j into our $l array for use next time, as we've already considered all those values.

Finally, we tack on |?{$_-ne$n} to pull out those that are not the input element. They're all left on the pipeline and output is implicit.

Examples

```<code>PS C:\Tools\Scripts\golfing> 2,4,8,15,16,23,42,117,126,204|%{"$_ --> "+(.\prime-factors-buddies $_)}
2 -->
4 -->
8 -->
15 --> 53
16 -->
23 --> 6
42 --> 74 146 161
117 --> 279 939 993 3313 3331
126 --> 222 438 674 746 1466 483 851 1679 1631
204 --> 782 2921 3266 6233 3791 15833 2951 7037 364 868 8561 15491 22547 852 762 1626 692 548 1268 2654 3446 2474 5462 4742 5426 4274 14426 6542 6434 14642
</code>```

Title: Prime factors buddies

Body:
PowerShell v3+, 450 bytes

param($n)function f{param($a)for($i=2;$a-gt1){if(!($a%$i)){$i;$a/=$i}else{$i++}}}
$y=($x=@((f $n)-split'(.)'-ne''|sort))|?{$_-eq(f $_)}
$a,$b=$x
$a=,$a
while($b){$z,$b=$b;$a=$a+($a+$y|%{$c="$_";0..$c.Length|%{-join($c[0..$_]+$z+$c[++$_..$c.Length])};"$z$c";"$c$z"})|select -u}
$x=-join($x|sort -des)
$l=@();$a|?{$_-eq(f $_)}|%{$j=$_;for($i=0;$i-le$x;$i+=$j){if(0-notin($l|%{$i%$_})){if(-join((f $i)-split'(.)'|sort -des)-eq$x){$i}}}$l+=$j}|?{$_-ne$n}

Finally!

PowerShell doesn't have any built-ins for primality checking, factorization, or permutations, so this is completely rolled by hand. I worked through a bunch of optimization tricks to try and reduce the time complexity down to something that will fit in the challenge restrictions, and I'm happy to say that I finally succeeded --

PS C:\Tools\Scripts\golfing> Measure-Command {.\prime-factors-buddies.ps1 204}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 27
Milliseconds      : 114
Ticks             : 271149810
TotalDays         : 0.000313830798611111
TotalHours        : 0.00753193916666667
TotalMinutes      : 0.45191635
TotalSeconds      : 27.114981
TotalMilliseconds : 27114.981

Explanation

There's a lot going on here, so I'll try to break it down.

The first line takes input $n and defines a function, f. This function uses accumulative trial division to come up with a list of the prime factors. It's pretty speedy for small inputs, but obviously bogs down if the input is large. Thankfully all the test cases are small, so this is sufficient.

The next line gets the factors of $n, -splits them on every digit ignoring any empty results (this is needed due to how PowerShell does regex matching and how it moves the pointer through the input and is kinda annoying for golfing purposes), then sorts the results in ascending order. We store that array of digits into $x, and use that as the input to a |?{...} filter to pull out only those that are themselves prime. Those prime digits are stored into $y for use later.

We then split $x into two components. The first (i.e., smallest) digit is stored into $a, while the rest are passed into $b. If $x only has one digit, then $b will be empty/null. We then need to re-cast $a as an array, so we use the comma operator quick-like to do so.

Next, we need to construct all possible permutations of the digits. This is necessary so our division tests later skip a bunch of numbers and make things faster overall.

So long as there's element left in $b, we peel off the first digit into $z and leave the remaining in $b. Then, we need to accumulate into $a the result of some string slicing and dicing. We take $a+$y as array concatenation, and for each element we construct a new string $c, then loop through $c's .length and insert $z into every position, including prepending $z$c and appending $c$z, then selecting only the -unique elements. That's again array-concatenated with $a and re-stored back into $a. Yes, this does wind up having goofy things happen, like you can get 3333 for input 117, which isn't actually a permutation, but this is much shorter than attempting to explicitly filter them out, ensures that we get every permutation, and is only very marginally slower.

So, now $a has an array of all possible (and then some) permutations of the factor's digits. We need to re-set $x to be our upper-bound of possible results by |sorting the digits in -descending order and -joining them back together. Obviously, no output value can be larger than this number.

We set our helper array $l to be an array of values that we've previously seen. Next, we're pulling out every value from $a (i.e., those permutations) that are prime, and enter a loop that is the biggest time sink of the whole program...

Every iteration, we're looping from 0 to our upper bound $x, incrementing by the current element $j. So long as the $i value we're considering is not a multiple of a previous value (that's the 0-notin($l|%{$i%$_}) section), it's a potential candidate for output. If we take the factors of $i, sort them, and they -equal $x, then add the value to the pipeline. At the end of the loop, we add our current element $j into our $l array for use next time, as we've already considered all those values.

Finally, we tack on |?{$_-ne$n} to pull out those that are not the input element. They're all left on the pipeline and output is implicit.

Examples

PS C:\Tools\Scripts\golfing> 2,4,8,15,16,23,42,117,126,204|%{"$_ --> "+(.\prime-factors-buddies $_)}
2 -->
4 -->
8 -->
15 --> 53
16 -->
23 --> 6
42 --> 74 146 161
117 --> 279 939 993 3313 3331
126 --> 222 438 674 746 1466 483 851 1679 1631
204 --> 782 2921 3266 6233 3791 15833 2951 7037 364 868 8561 15491 22547 852 762 1626 692 548 1268 2654 3446 2474 5462 4742 5426 4274 14426 6542 6434 14642


答:
Scala, 78 bytes

```<code>def f(a:String,b:String):String={if(a.size>b.size)f(b,a)else
a+"_"+(b diff a)}
</code>```

Explanation:

```<code>def f(a:String,b:String):String={ //define a method f which has two String parameters and returns a String
                                  //(because it's recursive, scala can't figure out the return type)
  if (a.size > b.size)            //make sure that a is the shorter string
    f(b, a)
  else
    a+"_"+(b diff a)              //`b diff a` removes all elements/chars of a from b
}
</code>```

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:
Scala, 78 bytes

def f(a:String,b:String):String={if(a.size>b.size)f(b,a)else
a+"_"+(b diff a)}

Explanation:

def f(a:String,b:String):String={ //define a method f which has two String parameters and returns a String
                                  //(because it's recursive, scala can't figure out the return type)
  if (a.size > b.size)            //make sure that a is the shorter string
    f(b, a)
  else
    a+"_"+(b diff a)              //`b diff a` removes all elements/chars of a from b
}


答:
Python 2.7, 102 92 bytes

For loop works better :/

```<code>s=`input()`
a,b,l=0,0,len(s)
for i in range(l/2):a=a+int(s[i]);b=b+int(s[l-i-1])
print a==b
</code>```

Same idea, just use length - i to get other side.  It will never reach the center of an odd number.

Old code

```<code>s=input()
l=len(s)
def n(i):return 0if not i else int(i[0])+n(i[1:])
print n(s[:l/2])==n(s[l/2+l%2:])
</code>```

Gets input

Saves length of input

Recursive func to get sum of string

Compare the first half sum to the second half sum

Trying to get it below 100, but its hard :/

Title: Is it a balanced number?

Body:
A number is balanced if the sum of the digits on each half of the number is equal, so: 1423 is balanced because 1+4 = 2+3, so is: 42615 because 4+2=1+5. Note that the middle digit is not included on either side (or it's included on both sides) if there's an odd number of digits.

Challenge:

Take a positive integer as input, and output a truthy value if it's balanced and a falsy value if it's unbalanced.

Test cases (true)

```<code>1
6
11
141
1221
23281453796004414
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088
</code>```

Test cases (false)

```<code>10
12
110
15421
5234095123508321
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454
</code>```

There will not be numbers starting with zero, for instance 00032 instead of 32. You must support numbers up to at least 100 digits (so larger than 2^64-1). As always, optional input format, so you may surround the number with apostrophes if desired.

Body:
Python 2.7, 102 92 bytes

For loop works better :/

s=`input()`
a,b,l=0,0,len(s)
for i in range(l/2):a=a+int(s[i]);b=b+int(s[l-i-1])
print a==b

Same idea, just use length - i to get other side.  It will never reach the center of an odd number.

Old code

s=input()
l=len(s)
def n(i):return 0if not i else int(i[0])+n(i[1:])
print n(s[:l/2])==n(s[l/2+l%2:])

Gets input

Saves length of input

Recursive func to get sum of string

Compare the first half sum to the second half sum

Trying to get it below 100, but its hard :/


答:
Mathematica, 57 bytes

```<code>Tr@(#-Reverse@#)[[;;⌊Length@#/2⌋]]==0&@*IntegerDigits
</code>```

Explanation

I was really hoping I could use this approach in some language, and it seems to be doing fairly well in Mathematica. The idea is to avoid having to obtain both the front and the back half by combining the list with its reverse and looking only at the front half.

```<code>...&@*IntegerDigits
</code>```

First, we turn the input into a list of decimal digits and pass the result to the unnamed function on the left.

```<code>...(#-Reverse@#)...
</code>```

Now we subtract the reverse of the list from the list itself. If the digits are {a1,a2,...,an} then the result will be {a1-an,a2-an-1,...,an-a1}.

```<code>...[[;;⌊Length@#/2⌋]]
</code>```

We extract the first half of this list (excluding the middle digit although that doesn't actually matter, because the corresponding difference will be 0 anyway).

```<code>Tr@...
</code>```

And then we sum this list. So that's:

```<code>a<sub>1</sub> - a<sub>n</sub> + a<sub>2</sub> - a<sub>n-1</sub> + ... + a<sub>⌊n/2⌋</sub> - a<sub>⌈n/2⌉+1</sub></code>```

Rearranging:

```<code>a<sub>1</sub> + a<sub>2</sub> + ... + a<sub>⌊n/2⌋</sub> - (a<sub>⌈n/2⌉+1</sub> + ... + a<sub>n-1</sub> + a<sub>n</sub>)</code>```

The input is balanced if the two halves have the same sum. Hence, this expression is zero if the input is balanced. So that's what we check:

```<code>...==0
</code>```

Title: Is it a balanced number?

Body:
Mathematica, 57 bytes

Tr@(#-Reverse@#)[[;;⌊Length@#/2⌋]]==0&@*IntegerDigits

Explanation

I was really hoping I could use this approach in some language, and it seems to be doing fairly well in Mathematica. The idea is to avoid having to obtain both the front and the back half by combining the list with its reverse and looking only at the front half.

...&@*IntegerDigits

First, we turn the input into a list of decimal digits and pass the result to the unnamed function on the left.

...(#-Reverse@#)...

Now we subtract the reverse of the list from the list itself. If the digits are {a1,a2,...,an} then the result will be {a1-an,a2-an-1,...,an-a1}.

...[[;;⌊Length@#/2⌋]]

We extract the first half of this list (excluding the middle digit although that doesn't actually matter, because the corresponding difference will be 0 anyway).

Tr@...

And then we sum this list. So that's:

a1 - an + a2 - an-1 + ... + a⌊n/2⌋ - a⌈n/2⌉+1

Rearranging:

a1 + a2 + ... + a⌊n/2⌋ - (a⌈n/2⌉+1 + ... + an-1 + an)

The input is balanced if the two halves have the same sum. Hence, this expression is zero if the input is balanced. So that's what we check:

...==0


答:
PHP, 66 Bytes

```<code>for(;2*$i<$l=strlen($t=$argv[1]);)$s+=$t[$i++]-$t[$l-$i];echo+!$s;
</code>```

-4 Bytes by @Titus Thank You

Title: Is it a balanced number?

Body:
PHP, 66 Bytes

for(;2*$i<$l=strlen($t=$argv[1]);)$s+=$t[$i++]-$t[$l-$i];echo+!$s;

-4 Bytes by @Titus Thank You