Is it a balanced number?

38

1

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.

Stewie Griffin

Posted 2016-09-23T12:26:02.967

Reputation: 43 471

Answers

12

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!

Emigna

Posted 2016-09-23T12:26:02.967

Reputation: 50 798

Can't you use Ë instead of \Q`? – Erik the Outgolfer – 2017-07-11T19:33:48.437

@EriktheOutgolfer: Ë was a different command back when this challenge was made, so unfortunately not. – Emigna – 2017-07-11T19:57:45.100

10

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

Sok

Posted 2016-09-23T12:26:02.967

Reputation: 5 592

7

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

Damien

Posted 2016-09-23T12:26:02.967

Reputation: 2 407

Don't snippets need parentheses? – Michael Klein – 2016-09-23T16:45:59.873

@michael-klein No, unnamed function are allowed. http://meta.codegolf.stackexchange.com/a/7615/20260

– Damien – 2016-09-23T16:59:16.697

1One byte to save: b(a:t@(r:s))=a-last t+b(init t);b _=0 – nimi – 2016-09-23T17:23:46.633

@nimi Thanks... – Damien – 2016-09-24T08:32:58.803

5

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

Fatalize

Posted 2016-09-23T12:26:02.967

Reputation: 32 976

5

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);
    }
  }
}

Olivier Grégoire

Posted 2016-09-23T12:26:02.967

Reputation: 10 647

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));. – todeale – 2016-09-24T07:31:51.057

@todeale Look at the golfed code, not the ungolfed one. I think your suggestion and my golfed answer use the same amount of bytes – Olivier Grégoire – 2016-09-24T07:48:51.010

Ooops! Now I see. – todeale – 2016-09-24T09:26:11.990

5

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>

ETHproductions

Posted 2016-09-23T12:26:02.967

Reputation: 47 880

I really like this n[i*2]! Nice one. – Arnauld – 2016-09-23T16:39:34.023

@Arnauld Thanks :-) I've found a completely different approach now that doesn't need that at all... – ETHproductions – 2016-09-23T16:40:52.820

Now, that's brilliant! – Arnauld – 2016-09-23T17:06:19.230

Can't you use f=([x,...a])=>!(a[0]?x-a.pop()+f(a):0)? – mbomb007 – 2016-09-23T18:46:04.577

@mbomb007 Nope; that would return a boolean (coerced to 0 or 1) after every recursion, rather than a sum. – ETHproductions – 2016-09-23T21:55:57.680

5

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

Martin Ender

Posted 2016-09-23T12:26:02.967

Reputation: 184 808

4

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!

Yytsi

Posted 2016-09-23T12:26:02.967

Reputation: 3 582

2you 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 – Rod – 2016-09-23T13:58:06.793

1also 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:] – Rod – 2016-09-23T14:26:01.237

5It also looks really weird when your import isn't at the top. – mbomb007 – 2016-09-23T14:33:06.783

@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! :) – Yytsi – 2016-09-23T20:48:10.283

@Rod By using your last tip on your second comment, the single digit testcases return falsey values :( – Yytsi – 2016-09-23T20:59:43.630

4

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

AdmBorkBork

Posted 2016-09-23T12:26:02.967

Reputation: 41 581

4

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;};

adrianmp

Posted 2016-09-23T12:26:02.967

Reputation: 1 592

1

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?

– Digital Trauma – 2016-09-23T17:04:06.727

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. – adrianmp – 2016-09-23T18:08:26.410

4

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

cia_rana

Posted 2016-09-23T12:26:02.967

Reputation: 441

4

Perl, 29 bytes

Includes +5 for -lpF

Give number on STDIN

balanced.pl <<< 1423

balanced.pl:

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

Ton Hospel

Posted 2016-09-23T12:26:02.967

Reputation: 14 114

4

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.

xnor

Posted 2016-09-23T12:26:02.967

Reputation: 115 687

3

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.

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

Post Rock Garf Hunter

Posted 2016-09-23T12:26:02.967

Reputation: 55 382

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. – James – 2016-09-23T18:19:09.777

@DJMcMayhem Good point. I forgot there couldn't be a zero on the stack – Post Rock Garf Hunter – 2016-09-23T18:49:37.373

3

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.

mbomb007

Posted 2016-09-23T12:26:02.967

Reputation: 21 944

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: http://retina.tryitonline.net/#code=XigoLikqPykuPyg_PSg_PC0yPi4pKiQpCiQxLA&input=MjMyODE0NTM3OTYwMDQ0MTQ (I also tried multiple stages but that ends up slightly longer http://retina.tryitonline.net/#code=XGIKLAorYCwoLikoLiopKC4pLAokMSwkMiwkMw&input=MjMyODE0NTM3OTYwMDQ0MTQ).

– Martin Ender – 2016-09-23T14:58:08.587

@MartinEnder Yeah, I knew it would be, but I never really grasped the concept. And I suppose I overlooked the non-capturing group. – mbomb007 – 2016-09-23T15:11:47.737

1It'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. – Martin Ender – 2016-09-23T15:15:14.137

3

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"));

Arnauld

Posted 2016-09-23T12:26:02.967

Reputation: 111 334

1Nice technique. I think you can do (s-=i<0?v:-v). – ETHproductions – 2016-09-23T15:18:04.413

@ETHproductions - Interesting to see how close the methods with and without Math.sign() turn out to be. – Arnauld – 2016-09-23T16:13:42.000

Darn, you may have beaten me for good... nice one :) – ETHproductions – 2016-09-23T16:55:28.130

I was wrong ;-) – ETHproductions – 2016-09-23T17:00:58.800

3

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.

Azor Ahai

Posted 2016-09-23T12:26:02.967

Reputation: 141

Can you bind length(y)%/%2 somehow to a variable and use that within the calls of tail and head? – nimi – 2016-09-23T17:51:52.350

@nimi Oh yeah, good point. – Azor Ahai – 2016-09-23T17:53:11.483

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 – Sumner18 – 2018-12-14T17:56:08.850

3

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.

Sherlock9

Posted 2016-09-23T12:26:02.967

Reputation: 11 664

3

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
}

Brad Gilbert b2gills

Posted 2016-09-23T12:26:02.967

Reputation: 12 713

This doesn't seem to work anymore (I suspect a change in how .. handles non-integers). How about 33 bytes instead

– Jo King – 2018-08-01T04:06:21.427

2

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.

NikoNyrh

Posted 2016-09-23T12:26:02.967

Reputation: 2 361

2

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

aross

Posted 2016-09-23T12:26:02.967

Reputation: 1 583

2

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

ElPedro

Posted 2016-09-23T12:26:02.967

Reputation: 5 301

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 – Rod – 2016-09-23T14:34:46.660

in fact the b==0 is needed for len=1, but you can shorten it to b<1 – Rod – 2016-09-23T14:45:13.593

2

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

Bassdrop Cumberwubwubwub

Posted 2016-09-23T12:26:02.967

Reputation: 5 707

2

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.

Jonathan Allan

Posted 2016-09-23T12:26:02.967

Reputation: 67 804

Ah, that's why I was getting the L at the end. +1 – ElPedro – 2016-09-24T06:16:05.723

1

Python 3, 69 67 bytes

I'm quite proud of this one, since it's smaller than any other python answers in this thread :). I owe the idea of printing the equivalence of the two sums to tuukkaX's answer though, I don't think I would have thought of that myself.

*a,=map(int,input())
h=(len(a)+1)//2
print(sum(a[:h])==sum(a[-h:]))

Try it online!

The +1 on the second line is necessary to make my slices work properly for single digit inputs. I realised that even though it overslices, it does so on both sides so it still works.

On a list of len 1, slicing a[:0] gives an empty list but a[-0;] gives the whole list. Every 1 digit input became itself==0 so it was always false.

thanks to david for shaving off 2 bytes

Terjerber

Posted 2016-09-23T12:26:02.967

Reputation: 51

1h=(len(a)+1)//2 saves a couple of bytes – david – 2018-12-14T09:45:16.947

1

Pyke, 20 bytes

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

Try it here!

Blue

Posted 2016-09-23T12:26:02.967

Reputation: 26 661

@WeeingIfFirst you were right - I forgot not [0] was 0 not 1 – Blue – 2016-09-23T19:48:22.500

1

Mathematica, 69

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

shrx

Posted 2016-09-23T12:26:02.967

Reputation: 462

2You can save a couple of bytes by changing the end to ...;;]]&@*IntegerDigits – Martin Ender – 2016-09-23T15:01:12.847

@MartinEnder thanks, but how does this work? – shrx – 2016-09-24T07:32:01.237

@* is short for Composition. f@*g is f[g[##]]&. – Martin Ender – 2016-09-24T07:44:19.063

1

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

rnso

Posted 2016-09-23T12:26:02.967

Reputation: 1 635

1

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!

Riley

Posted 2016-09-23T12:26:02.967

Reputation: 11 345

1

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

greyShift

Posted 2016-09-23T12:26:02.967

Reputation: 221

1

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

Jörg Hülsermann

Posted 2016-09-23T12:26:02.967

Reputation: 13 026

1That $t[$i++]-$t[$l-$i] trick is great! It saves 4 bytes in my JS answer :-) – ETHproductions – 2016-09-23T16:26:44.937

unnecessary parentheses around the $l assignment; always returns 1 for odd lengths with PHP < 7. – Titus – 2016-09-24T08:35:21.660

@Titus the result for php -r "for(;$i<($l=strlen($t=$argv[1]))/2;)$s+=$t[$i++]-$t[$l-$i];echo$s?0:1;" 110 is 0 under PHP 7. You are sure that your input is a string? – Jörg Hülsermann – 2016-09-24T10:15:00.447

No it wasn´t. but you still don´t need the parentheses. – Titus – 2016-09-24T10:20:59.687

@Titus If a remove the parentheses $l=strlen($t=$argv[1])/2 the variable is the half value and I get a wrong result – Jörg Hülsermann – 2016-09-24T10:35:39.340

1Oops. You´re right. Use 2*$i<$l=strlen($t=$argv[1]) instead. – Titus – 2016-09-24T10:59:01.983

1And echo+!$s; for the output. (-2) – Titus – 2016-09-24T11:01:58.220

1

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.

Digital Trauma

Posted 2016-09-23T12:26:02.967

Reputation: 64 644

You can't use strlen without including #include"string.h"\n, which adds 19 to your score. – NoSeatbelts – 2016-09-30T16:31:40.537

1

@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.

– Digital Trauma – 2016-09-30T17:14:33.493

1No need for the space in char *n – Cyoce – 2017-05-06T20:51:44.980

remove spaces l;i;t;f(char*n){..return!t;} -2 bytes – Khaled.K – 2017-05-07T17:32:53.410

1

Groovy - 74 69 bytes

Represented as a Groovy closure. Please note that the parameter passed in (i) is a String, as with the Java version.

{i->e=i.size();k=0;s=0;for(;s<e;){k+=i.charAt(s++)-i.charAt(--e)};!k}

GolfIsAGoodWalkSpoilt

Posted 2016-09-23T12:26:02.967

Reputation: 101

Hi, and welcome to the site! This is a nice first post, but assuming the input is stored in a predefined variable is not an allowed input method. I don't know much Groovy, but could you add something like i=input() or turn it into a function?

– James – 2016-09-26T17:04:49.743

Rats, sorry - should be a bit better now; please do let me know. – GolfIsAGoodWalkSpoilt – 2016-09-27T07:21:23.200

1

JavaScript (ES5), 70 66 bytes

function g(n){for(a=b=0;(l=n.length)>b*2;)a+=n[b]-n[l-++b];return!a}


// tests:
var falses = ['10', '12', '110', '15421', '5234095123508321', '6240911314399072459493765661191058613491863144152352262897351988250431140546660035648795316740212454']
var i=falses.length;
while(i--) console.info(!g(falses[i]) ? 'ok' : 'not false: ' + falses[i])

var trues = ['1', '6', '11', '141', '1221', '23281453796004414', '523428121656666655655556655656502809745249552466339089702361716477983610754966885128041975406005088'];
i = trues.length;
while(i--) console.info(g(trues[i]) ? 'ok' : 'not true: ' + trues[i])

user470370

Posted 2016-09-23T12:26:02.967

Reputation: 201

1

Nice answer! I count 67 bytes, not including the g (it doesn't count toward your byte count). You can also save a byte or two by switching to a for loop.

– ETHproductions – 2016-09-28T21:05:46.790

thx - very useful!! – user470370 – 2016-09-29T16:00:37.237

1

Groovy (85 73 Bytes)

f={n->x=n.collect{[it,it]}.flatten().collate(n.size())*.sum();x[0]==x[1]}
  • .collect{[it,it]} - Dupe all elements into a 2D array.
  • .flatten() - Turn 2D array into 1D array.
  • .collate(n.size()) - Split new array in half.
  • *.sum() - Sum both sub-arrays.
  • x[0]==x[1] - Check for equality / return.

Magic Octopus Urn

Posted 2016-09-23T12:26:02.967

Reputation: 19 422

0

Jelly, 7 bytes

Dx2ŒH§E

Try it online!

Same algorithm as 05AB1E answer.

user202729

Posted 2016-09-23T12:26:02.967

Reputation: 14 620

0

Tcl, 156 bytes

proc R n {set l [string le $n];puts [expr [join [split [string ra $n 0 [expr $l/2-($l%2==0)]] {}] +]==[join [split [string ra $n [expr $l/2] $l+$l] {}] +]]}

Try it online!

david

Posted 2016-09-23T12:26:02.967

Reputation: 479

0

C# (Visual C# Interactive Compiler), 58 bytes

s=>s.Zip(s.Reverse(),(a,b)=>a-b).Take(s.Length/2).Sum()==0

Try it online!

dana

Posted 2016-09-23T12:26:02.967

Reputation: 2 541

0

JavaScript 95 88 bytes

i=>(s=(i,a,b)=>[...i.slice(a,b)].reduce((p,e)=>p-e,0))(i=i+"",0,m=i.length/2)==s(i,m+.5)

Explanation:

Convert input to a string, create a function that takes string segments and sums up all of the digits, and call that function for the left and right halves of the input.

Grax32

Posted 2016-09-23T12:26:02.967

Reputation: 1 282

0

Scala, 77 bytes

Like Java, must take Strings.
I'm sure someone could find an improvement.

def f(s:String)=(for(i<-0 until s.length/2)yield s(i)-s(s.length-i-1)).sum==0

Can test online

Himself12794

Posted 2016-09-23T12:26:02.967

Reputation: 61