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

1
2
1
\$\begingroup\$

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

Pyke, 20 bytes

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

Try it here!

\$\endgroup\$
1
  • \$\begingroup\$ @WeeingIfFirst you were right - I forgot not [0] was 0 not 1 \$\endgroup\$
    – Blue
    Sep 23, 2016 at 19:48
1
\$\begingroup\$

Mathematica, 69

Tr@#[[;;⌊l=Length@#/2⌋]]==Tr@#[[⌈l⌉+1;;]]&@*IntegerDigits
\$\endgroup\$
3
  • 2
    \$\begingroup\$ You can save a couple of bytes by changing the end to ...;;]]&@*IntegerDigits \$\endgroup\$ Sep 23, 2016 at 15:01
  • \$\begingroup\$ @MartinEnder thanks, but how does this work? \$\endgroup\$
    – shrx
    Sep 24, 2016 at 7:32
  • \$\begingroup\$ @* is short for Composition. f@*g is f[g[##]]&. \$\endgroup\$ Sep 24, 2016 at 7:44
1
\$\begingroup\$

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

\$\endgroup\$
7
  • 1
    \$\begingroup\$ That $t[$i++]-$t[$l-$i] trick is great! It saves 4 bytes in my JS answer :-) \$\endgroup\$ Sep 23, 2016 at 16:26
  • \$\begingroup\$ unnecessary parentheses around the $l assignment; always returns 1 for odd lengths with PHP < 7. \$\endgroup\$
    – Titus
    Sep 24, 2016 at 8:35
  • \$\begingroup\$ @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? \$\endgroup\$ Sep 24, 2016 at 10:15
  • 1
    \$\begingroup\$ Oops. You´re right. Use 2*$i<$l=strlen($t=$argv[1]) instead. \$\endgroup\$
    – Titus
    Sep 24, 2016 at 10:59
  • 1
    \$\begingroup\$ And echo+!$s; for the output. (-2) \$\endgroup\$
    – Titus
    Sep 24, 2016 at 11:01
1
\$\begingroup\$

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}
\$\endgroup\$
2
  • \$\begingroup\$ 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? \$\endgroup\$
    – DJMcMayhem
    Sep 26, 2016 at 17:04
  • \$\begingroup\$ Rats, sorry - should be a bit better now; please do let me know. \$\endgroup\$ Sep 27, 2016 at 7:21
1
\$\begingroup\$

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

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Sep 28, 2016 at 21:05
  • \$\begingroup\$ thx - very useful!! \$\endgroup\$
    – user470370
    Sep 29, 2016 at 16:00
1
\$\begingroup\$

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

Jelly, 7 bytes

Dx2ŒH§E

Try it online!

Same algorithm as 05AB1E answer.

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

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ h=(len(a)+1)//2 saves a couple of bytes \$\endgroup\$
    – david
    Dec 14, 2018 at 9:45
1
\$\begingroup\$

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!

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

C (gcc), 98 bytes

V=2;main(A,v)char**v;{char*a=*++v;while(a[1])a++;while(*v<a)V+=*(*v)++,A+=*a--;puts(A^V?"0":"1");}

There's a shorter submission for a C function, but mine compiles on its own and handles command line arguments.

Try it online!

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

flax, 7 bytes

EṠXFz˘D

Port of the 05AB1E answer. Ties with jelly. No online link as the latest commit is not on ATO.

flax repl

Explanation

EṠXFz˘D

      D  ⊳ Digits
    z˘   ⊳ Zip with itself
   F     ⊳ Flatten
  X      ⊳ Split into two
EṠ       ⊳ Are the sum of the two halves equal?
\$\endgroup\$
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

Burlesque, 39 bytes

{iTg1!!}s9XXsa2./s1{q%9!{<-%9!}}M-)++sm

Try it online!

{
 iT   # Generate tails
 g1   # Get var 1
 !!   # Select from array
}s9   # Save as var 9
XX    # Split int to digits
sa    # Number of digits
2./   # /2
s1    # Save as 1
{
 q%9! # Eval 9 as function 
 {
  <-  # Reverse
  %9! # Eval 9 as function
 }
}M-   # Eval each contained function on the digits
)++   # Map sum
sm    # Same
\$\endgroup\$
0
\$\begingroup\$

Thunno E, \$14\log_{256}(96)\approx\$ 11.52 bytes

eDZPiES2AP.Sze

Attempt This Online!

Port of Emigna's 05AB1E answer.

    # E flag converts to string 
e   # Map:
DZP #  Pair with itself
i   #  Convert to integer
E   # End map
S   # Flatten
2AP # Split in half
.S  # Sum each
ze  # All equal?
\$\endgroup\$
1
2

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.