44
\$\begingroup\$

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)

1
6
11
141
1221
23281453796004414
523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088

Test cases (false)

10
12
110
15421
5234095123508321
6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454

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.

\$\endgroup\$
0

47 Answers 47

12
\$\begingroup\$

05AB1E, 14 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!

\$\endgroup\$
2
  • \$\begingroup\$ Can't you use Ë instead of `Q? \$\endgroup\$ Jul 11, 2017 at 19:33
  • \$\begingroup\$ @EriktheOutgolfer: Ë was a different command back when this challenge was made, so unfortunately not. \$\endgroup\$
    – Emigna
    Jul 11, 2017 at 19:57
10
\$\begingroup\$

><>, 31 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

\$\endgroup\$
7
\$\begingroup\$

Haskell, 64 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

\$\endgroup\$
3
  • \$\begingroup\$ Don't snippets need parentheses? \$\endgroup\$ Sep 23, 2016 at 16:45
  • \$\begingroup\$ @michael-klein No, unnamed function are allowed. meta.codegolf.stackexchange.com/a/7615/20260 \$\endgroup\$
    – Damien
    Sep 23, 2016 at 16:59
  • 1
    \$\begingroup\$ One byte to save: b(a:t@(r:s))=a-last t+b(init t);b _=0 \$\endgroup\$
    – nimi
    Sep 23, 2016 at 17:23
6
\$\begingroup\$

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
\$\endgroup\$
6
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

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);
    }
  }
}
\$\endgroup\$
3
  • \$\begingroup\$ Nice answer. You could save 2 bytes by making the for-loop empty: for (; i < l / 2;s += n.charAt(i) - n.charAt(l - ++i));. \$\endgroup\$
    – todeale
    Sep 24, 2016 at 7:31
  • \$\begingroup\$ @todeale Look at the golfed code, not the ungolfed one. I think your suggestion and my golfed answer use the same amount of bytes \$\endgroup\$ Sep 24, 2016 at 7:48
  • \$\begingroup\$ Ooops! Now I see. \$\endgroup\$
    – todeale
    Sep 24, 2016 at 9:26
5
\$\begingroup\$

JavaScript (ES6), 59 55 51 44 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>

\$\endgroup\$
5
  • \$\begingroup\$ I really like this n[i*2]! Nice one. \$\endgroup\$
    – Arnauld
    Sep 23, 2016 at 16:39
  • \$\begingroup\$ @Arnauld Thanks :-) I've found a completely different approach now that doesn't need that at all... \$\endgroup\$ Sep 23, 2016 at 16:40
  • \$\begingroup\$ Now, that's brilliant! \$\endgroup\$
    – Arnauld
    Sep 23, 2016 at 17:06
  • \$\begingroup\$ Can't you use f=([x,...a])=>!(a[0]?x-a.pop()+f(a):0)? \$\endgroup\$
    – mbomb007
    Sep 23, 2016 at 18:46
  • \$\begingroup\$ @mbomb007 Nope; that would return a boolean (coerced to 0 or 1) after every recursion, rather than a sum. \$\endgroup\$ Sep 23, 2016 at 21:55
5
\$\begingroup\$

Haskell, 55 bytes

g(h:t)=read[h]-g(reverse t)
g _=0
(==0).g.(<*"xx").show

The recursive function g unwraps a number string from both ends by repeatedly taking the head, then reversing. It subtracts the recursive result from the head, which causes it alternate coefficients of +1 and -1, with +1 applied to the first half and -1 to the second half.

   g "12345" 
== 1 - g "5432"
== 1 - (5 - g "432")
== 1 - (5 - (4 - g "32"))
== 1 - (5 - (4 - (3 - g "2"))
== 1 - (5 - (4 - (3 - 2))
== 1 + 2 + 3 - 4 - 5

So, it takes the sum of the first half minus the sum of the second half. This has the issue that with an odd number of digits, the center tiebreaks to the left, but the main function fixes that by (<*"xx"), which doubles every character, i.e. "12345" becomes "1122334455". That way the middle digit splits evenly on both sides and cancels out.

\$\endgroup\$
4
\$\begingroup\$

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
---
\$\endgroup\$
4
\$\begingroup\$

Perl, 29 bytes

Includes +5 for -lpF

Give number on STDIN

balanced.pl <<< 1423

balanced.pl:

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

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;};
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Not surprisingly, my c answer ended up looking fairly similar to this one. Can you do t[l-++i] instead of t[l-1-i++], and return !r instead of return r==0? \$\endgroup\$ Sep 23, 2016 at 17:04
  • \$\begingroup\$ Prefixing the increment operator should do the trick and save 2 bytes, but in C# the return value must be a boolean, so !r won't cut it. Thanks, I'll update my answer as soon as possible. \$\endgroup\$
    – adrianmp
    Sep 23, 2016 at 18:08
4
\$\begingroup\$

Python 3, 107 102 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!

\$\endgroup\$
5
  • 2
    \$\begingroup\$ you can replace floor(l/2) with l//2 and ceil(l/2) with l//2+l%2 to save 7 bytes, and then remove the math import, saving more 18 \$\endgroup\$
    – Rod
    Sep 23, 2016 at 13:58
  • 1
    \$\begingroup\$ also you don't need the 0 on n[0:l//2] and n[l//2+l%2:] could just be n[-(l//2):]. Or you could move the //2 to l=len(n)//2 and use n[:l] and n[-l:] \$\endgroup\$
    – Rod
    Sep 23, 2016 at 14:26
  • 5
    \$\begingroup\$ It also looks really weird when your import isn't at the top. \$\endgroup\$
    – mbomb007
    Sep 23, 2016 at 14:33
  • \$\begingroup\$ @Rod I came here to change all the things you mentioned on the first comment, but was amazed by the second one, thanks a lot! :) \$\endgroup\$
    – Yytsi
    Sep 23, 2016 at 20:48
  • \$\begingroup\$ @Rod By using your last tip on your second comment, the single digit testcases return falsey values :( \$\endgroup\$
    – Yytsi
    Sep 23, 2016 at 20:59
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

Vyxal, 4 bytes

YIṠ≈

Try it Online!

Beats all other answers.

How?

YIṠ≈
Y     # Interleave the input with itself, giving a list with each digit duplicated
 I    # Split into two halves
  Ṡ   # Sum each
   ≈  # Is this list all equal?

05AB1E, 6 bytes

.ι2äOË

Try it online!

Same concept.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Funnily enough, this is also exactly what this Jelly answer does, despite it being a port of the 05AB1E answer yours beats! \$\endgroup\$ Feb 28, 2023 at 4:50
3
\$\begingroup\$

Retina, 64 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 (taken and modified from here. Courtesy of Martin.) Then, replace digits with their unary representation, and match if the two halves are of equal length.

\$\endgroup\$
3
  • \$\begingroup\$ Why would you use a non-capturing group in a code golf? ;) Regardless, in .NET it's much shorter to split the string with balancing groups: retina.tryitonline.net/… (I also tried multiple stages but that ends up slightly longer retina.tryitonline.net/…). \$\endgroup\$ Sep 23, 2016 at 14:58
  • \$\begingroup\$ @MartinEnder Yeah, I knew it would be, but I never really grasped the concept. And I suppose I overlooked the non-capturing group. \$\endgroup\$
    – mbomb007
    Sep 23, 2016 at 15:11
  • 1
    \$\begingroup\$ It's really simple in this case: we count characters with (.)*? (each iteration pushes a capture onto stack 2). Then we try to reach the end by popping from the stack again with (?<-2>.)*$ (after an optional middle digit). The first time this is possible is when we've captured exactly half the digits (rounded down) into group 2. \$\endgroup\$ Sep 23, 2016 at 15:15
3
\$\begingroup\$

JavaScript (ES6), 74 67 ... 59 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"));

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Nice technique. I think you can do (s-=i<0?v:-v). \$\endgroup\$ Sep 23, 2016 at 15:18
  • \$\begingroup\$ @ETHproductions - Interesting to see how close the methods with and without Math.sign() turn out to be. \$\endgroup\$
    – Arnauld
    Sep 23, 2016 at 16:13
  • \$\begingroup\$ Darn, you may have beaten me for good... nice one :) \$\endgroup\$ Sep 23, 2016 at 16:55
  • \$\begingroup\$ I was wrong ;-) \$\endgroup\$ Sep 23, 2016 at 17:00
3
\$\begingroup\$

R, 105 96 bytes

Turns out R is very verbose. Takes input as a character.

function(x){y<-as.numeric(unlist(strsplit(x,"")));l<-length(y)%/%2;sum(tail(y,l))==sum(head(y,l))}

Formatted nicely:

function(x){
    y=as.numeric(unlist(strsplit(x,"")))
    l=length(y)%/%2
    sum(tail(y,l))==sum(head(y,l))
}

Explanation

  • y<-as.numeric(unlist(strsplit(x,""))) Split the input (a string_, and coerce it to a vector instead of a list, and then turn it back into integers.
  • sum(tail(y,: tail takes the last n elements, found by:
    • length(y)%/%2)), where %/% is integer division, to get the ceiling of the quotient, where the length is odd.
  • sum(head(y,length(y)%/%2)): like tail, head takes the first n elements of the vector, found in the same way.

Edits

  • Saved seven bytes thanks to niam
  • Switched to = instead of <- , saved another two bytes.
\$\endgroup\$
4
  • \$\begingroup\$ Can you bind length(y)%/%2 somehow to a variable and use that within the calls of tail and head? \$\endgroup\$
    – nimi
    Sep 23, 2016 at 17:51
  • \$\begingroup\$ @nimi Oh yeah, good point. \$\endgroup\$ Sep 23, 2016 at 17:53
  • \$\begingroup\$ 85 bytes tio.run/… \$\endgroup\$
    – Sumner18
    Dec 14, 2018 at 17:50
  • \$\begingroup\$ by consolidating y and l into the first sum, changing as.numeric to as.double(), unlist() to el(). This allowed me to do it all in one line, removing brackets, and pryr::f guesses the formals/variables from the code \$\endgroup\$
    – Sumner18
    Dec 14, 2018 at 17:56
3
\$\begingroup\$

Brain-Flak, 410 206 204 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.

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.

{{}{}((<>))}{}
\$\endgroup\$
2
  • \$\begingroup\$ Why use ([]){[{}]{}([])}{} to sum each stack? ({{}}) should work just fine, and since you're taking ASCII input, you don't have to worry about 0's ruining the loop. \$\endgroup\$
    – DJMcMayhem
    Sep 23, 2016 at 18:19
  • \$\begingroup\$ @DJMcMayhem Good point. I forgot there couldn't be a zero on the stack \$\endgroup\$
    – Wheat Wizard
    Sep 23, 2016 at 18:49
3
\$\begingroup\$

Actually, 17 16 bytes

This answer is inspired by ElPedro's Python 2 answer and their idea to use [-b:]. Golfing suggestions welcome. Try it online!

$♂≈;l½L│±aHΣ)tΣ=

Ungolfing

      Implicit input n.
$♂≈   list(str(n)). This converts n to a list of n's digits.
;l    Duplicate the list of digits and get its length. Call it len.
½L    Push len//2.
│     This duplicates the stack.
        Stack: len//2, digit_list, len//2, digit_list
±     Negate the len//2 at TOS for later.
a     Invert the stack.
        Stack: digit_list, len//2, digit_list, -(len//2)
HΣ    Push digit_list[:len//2], then push its sum.
)     Rotate this first sum to BOS.
tΣ    Push digit_list[-(len//2):], then push its sum.
=     Check if those sums are equal.
      Implicit return.
\$\endgroup\$
3
\$\begingroup\$

Perl 6,  42 39  33 bytes

{[==] .comb[{^($_/2),Int($_/2)..*}]>>.sum}

Test it

{[==] .comb[^(*/2),(*/2).Int..*]>>.sum}

Test it

{[==] .comb[^*/2,^*/2+*/2]>>.sum}

Test it (from Jo King)

Explanation:

{ # lambda with implicit parameter 「$_」

  [==]                   # reduce the following using &infix:«==»

    .comb\               # split input into individual characters
    [                    # index into that using:

      # first half of the values (includes middle value)
      # 「(0/2) ..^ (*/2)」
      ^ * / 2,     

      # last half of the values (includes middle value)
      ^ * / 2            # same number of values as first half
        + * / 2          # shifted up by half

    ]\
    >>.sum               # sum each of the two halves separately
}
\$\endgroup\$
1
  • \$\begingroup\$ This doesn't seem to work anymore (I suspect a change in how .. handles non-integers). How about 33 bytes instead \$\endgroup\$
    – Jo King
    Aug 1, 2018 at 4:06
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

Python 2, 73 bytes

def f(n):x=map(int,str(n));d=len(x)/2;print sum(x[:d])==sum(x[-d:])or d<1

Tests are at ideone

We have to use str() rather than `` since n may be outside the range of signed int.

\$\endgroup\$
1
  • \$\begingroup\$ Ah, that's why I was getting the L at the end. +1 \$\endgroup\$
    – ElPedro
    Sep 24, 2016 at 6:16
2
\$\begingroup\$

Python 2, 83 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
\$\endgroup\$
2
  • \$\begingroup\$ you can use map(int,input()) instead [int(h)for h in raw_input()], len(g)/2 will always be int, no need to convert, and or b==0 ins't really necessary \$\endgroup\$
    – Rod
    Sep 23, 2016 at 14:34
  • \$\begingroup\$ in fact the b==0 is needed for len=1, but you can shorten it to b<1 \$\endgroup\$
    – Rod
    Sep 23, 2016 at 14:45
2
\$\begingroup\$

PHP, 73 67 60 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
\$\endgroup\$
2
\$\begingroup\$

Clojure, 66 64 bytes

Update: Took str out from the map int function.

(comp #(=(apply +(map -(drop(/(count %)2)%)%))0)#(map int %)str)

This would have been shorted if the input format was more flexible, now I had to first map the integer into a sequence of ASCII values. The inner map calculates pair-wise differences of values from the two halves, and this checks if the sum of deltas is zero.

((comp f g h) x y z) = (f (g (h x y z)).

Actually this ended up being the same length as just doing the mapping within a let and just define a single function.

\$\endgroup\$
2
\$\begingroup\$

Factor + math.unicode sequences.repeating, 32 bytes

[ 2 repeat halves [ Σ ] same? ]

Try it online!

            ! "141"
2 repeat    ! "114411"
halves      ! "114" "411"
[ Σ ] same? ! t
\$\endgroup\$
2
\$\begingroup\$

C (GCC), 66 bytes

char*c,*d;i;f(s){for(d=index(c=s,i=0);c<--d;)i+=*c++-*d;return!i;}

Try It Online!

Explanation:

char*c,*d;i;
f(s)
{
    // d = the first null-terminator in s, c = s, i = 0
    // Before the first and after each iteration, decrement d and break out of
    // the loop if c has surpassed d.
    for(d=index(c=s,i=0);c<--d;)
        // Add the ascii values of c and d to i, increment c.
        // The ascii values of a number equals the ascii value of 0 plus the
        // number, so if numbers j and k are respectively stored in c and d,
        // *c - *d = (i + '0') - ('j + '0') = i - j = the signed difference
        i+=*c++-*d;
    // If the sum of the signed differences are 0, return 1; otherwise 0
    return!i;
}
\$\endgroup\$
1
\$\begingroup\$

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

Try it online!

\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
\$\begingroup\$

C function, 74

l;i;t;f(char *n){l=strlen(n);for(t=i=0;i<l/2;)t+=n[i]-n[l-++i];return !t;}

Ideone.

\$\endgroup\$
4
  • \$\begingroup\$ You can't use strlen without including #include"string.h"\n, which adds 19 to your score. \$\endgroup\$ Sep 30, 2016 at 16:31
  • 1
    \$\begingroup\$ @NoSeatbelts Yes you can - try out the Ideone link. The compiler will most likely give you a bunch of warnings, but compile a working executable anyway (at least GCC and Clang do). Which compiler are you using? There's even a code-golf tip about this. \$\endgroup\$ Sep 30, 2016 at 17:14
  • 1
    \$\begingroup\$ No need for the space in char *n \$\endgroup\$
    – Cyoce
    May 6, 2017 at 20:51
  • \$\begingroup\$ remove spaces l;i;t;f(char*n){..return!t;} -2 bytes \$\endgroup\$
    – Khaled.K
    May 7, 2017 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.