15
\$\begingroup\$

This question already has an answer here:

Your task is to write a function that takes an even-digit integer and compares the 2 halves of the integer. If the sum of the digits in the first half is greater than the sum of the digits in the second half, output a truthy value, otherwise, output falsey.

For example:

12345678
1234 5678
(1+2+3+4)>(5+6+7+8)
10>26

Output falsey

Input

A single integer.

  • This must be passed as a single whole integer in base 10, a single string, an array of integers, or an array of characters. Please specify which format your answer accepts
  • The input can be passed via Command Line Arguments, STDIN, or any other standard method of input supported by your language
  • Assume the input will always have an even digit count
  • Assume the input will always be positive and greater than 0
  • Assume the input will be within feasible number handling capacities for your language
  • The input will not contain leading zeroes

Output

A truthy value if the sum of the digits in the first half is greater than the sum of the digits in the second half.

A falsey value if the sum of the digits in the first half is less than or equal to the sum of the digits in the second half.

Test cases

Input > Output

12345678 > False
87654321 > True
12344321 > False
12 > False
214758392639543385 > False
1001 > False
100000 > True

Scoring

This is so fewest bytes wins.

\$\endgroup\$

marked as duplicate by Stewie Griffin, Sriotchilism O'Zaic, Toto, Blue code-golf May 6 '17 at 17:01

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 2
    \$\begingroup\$ The "duplicate" is an = check, this is a > check. I don't think they're duplicates. \$\endgroup\$ – CalculatorFeline May 6 '17 at 18:01

28 Answers 28

6
\$\begingroup\$

Brachylog, 5 bytes

ḍ+ᵐ>₁

Try it online!

How it works

ḍ+ᵐ>₁                     example input: 12345678
ḍ        split in half                   [[1,2,3,4],[5,6,7,8]]
 +ᵐ      sum each half                   [10,26]
   >₁    results in a decreasing list    false
\$\endgroup\$
5
\$\begingroup\$

Octave, 39 35 28 bytes

@(x)sum(x)/2<sum(x(1:end/2))

Input integers as a string '12345678'.

Takes the sum of all the digits (as ASCII-values), and divides it by two, to get the mean of the two sides. Compares this to the sum of the first half of the integer, to check if it's smaller or not.

\$\endgroup\$
  • 1
    \$\begingroup\$ I like the use of ASCII values and calculating the mean, always cool to see different approaches to the task. \$\endgroup\$ – Skidsdev May 5 '17 at 9:11
5
\$\begingroup\$

Retina, 34 bytes

\d
$*1;
+`;(.*);(.)
$1$2
1(1*);\1;

Try it online! Works by inserting ;s after each digit as they are converted to unary. The ;s are then deleted in pairs until only the middle and final ;s remain and the numbers can then be compared.

\$\endgroup\$
  • \$\begingroup\$ How does it only remove the first and last semicolons each iteration? \$\endgroup\$ – Cows quack May 5 '17 at 9:11
  • \$\begingroup\$ The * in .* is maximal matching (greedy), so it would match as much as possible. \$\endgroup\$ – Leaky Nun May 5 '17 at 9:11
  • \$\begingroup\$ @KritixiLithos * is greedy, so it skips as many ;s as possible. \$\endgroup\$ – Neil May 5 '17 at 9:12
4
\$\begingroup\$

Regex, 226 bytes

^(9(){9}|8(?<2>){8}|7(?<2>){7}|6(?<2>){6}|5(?<2>){5}|4(?<2>){4}|3(?<2>){3}|2(?<2>){2}|1(?<2>)|0)+(?<-1>9(?<-2>){9}|8(?<-2>){8}|7(?<-2>){7}|6(?<-2>){6}|5(?<-2>){5}|4(?<-2>){4}|3(?<-2>){3}|2(?<-2>){2}|1(?<-2>)|0)+(?<-2>)(?(1)^)$

Try it online! (uses Retina to check)

\$\endgroup\$
  • \$\begingroup\$ I assume the 0 or 1 output is the number of matches? Meaning this will only match "significant" numbers? That's pretty cool. \$\endgroup\$ – Skidsdev May 5 '17 at 9:07
  • \$\begingroup\$ What does the (?<number>) do? \$\endgroup\$ – Cows quack May 5 '17 at 10:43
  • \$\begingroup\$ They are called balancing groups. Please refer to an answer written by Martin Ender on SO. \$\endgroup\$ – Leaky Nun May 5 '17 at 10:44
4
\$\begingroup\$

Haskell, 34 bytes

g(h:t)=h-g(reverse t)
g _=0
(>0).g

Try it online! Take list as input.

Computes the sum of the first half minus that of the second half by recursively taking the first element and subtracting the recursive result on the reverse. For example:

g [1,2,3,4]    =
1-g[4,3,2]     =
1-(4-g[2,3])   =
1-(4-(2-g[3])) =
1-(4-(2-3))    =
1-4+2-3        =
(1+2)-(3+4)
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 5 bytes

2äO`›

Try it online!

Explanation

Takes input as list of digits.

2ä     # split in half
  O    # sum each part
   `›  # is the first half greater than the second

To take input as an integer you could just add S for

S2äO`›
\$\endgroup\$
  • \$\begingroup\$ Oh, we're even now... \$\endgroup\$ – Leaky Nun May 5 '17 at 8:28
  • \$\begingroup\$ @LeakyNun: I like yours better though, due to the input format. \$\endgroup\$ – Emigna May 5 '17 at 8:29
3
\$\begingroup\$

Retina, 60 40 bytes

Saved some bytes thanks to @MartinEnder

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

Try it online!

\$\endgroup\$
3
\$\begingroup\$

PHP, 54 bytes

for($n=$argn;~$n[2*$i];)$s+=$n[$i]-$n[-++$i];echo$s>0;

takes input from STDIN; empty output for falsy. Requires PHP 7.1. Run with -nR.

breakdown

for($n=$argn;       # import input
    ~$n[2*$i];      # loop while there is a 2*$i-th digit (0-indexed)
)
    $s+=$n[$i]          # 1. add $i-th digit
        -$n[-++$i];     # 2. subtract -1-$i-th digit
echo$s>0;           # if $s>0, print "1" , else print nothing
\$\endgroup\$
3
\$\begingroup\$

Python 2, 78 62 44 35 bytes

Crossed out 44 is still regular 44. :c

-16 bytes thanks to LeakyNun. -18 bytes on allowance of integer array input. -9 bytes thanks to Dennis.

Takes input as an array of integers and returns True/False. Note that it relies on Python 2's integer division.

lambda s:sum(s[:len(s)/2])*2>sum(s)

Try it online!

Explanation:

I know this (or anything in Python) doesn't need an explanation but I'm doing it anyways for good practise. :P

    s[:len(s)/2]             # Gets first half of array
sum(s[:len(s)/2])            # Calculates the sum of the values
sum(s[:len(s)/2])*2          # Multiplies it by 2 (explanations...)
                    sum(s)   # Total sum of the digits
sum(s[:len(s)/2])*2>sum(s)   # Compares the two sums
\$\endgroup\$
  • 1
    \$\begingroup\$ Golfed \$\endgroup\$ – Leaky Nun May 5 '17 at 10:17
  • \$\begingroup\$ @LeakyNun I should really learn how map() works. o0 Thanks! \$\endgroup\$ – totallyhuman May 5 '17 at 10:39
  • 1
    \$\begingroup\$ Hint: the sum of both halves is the total. \$\endgroup\$ – Dennis May 5 '17 at 15:47
  • \$\begingroup\$ @Dennis I hope this is what you meant. \$\endgroup\$ – totallyhuman May 5 '17 at 17:10
3
\$\begingroup\$

Python 3, 68 62 bytes

i=input()
print(sum(map(int,i))>2*sum(map(int,i[len(i)//2:])))

Short explanation:

  • input() reads a string from stdin.
  • i[len(i)//2:] takes the second half of the string.
  • The map functions turn the string to an integer list.
  • sum, >, *2 and print do what they say.
\$\endgroup\$
3
\$\begingroup\$

Python 2, 52 Bytes thanks to help in comments

lambda x:sum(x[i]-x[~i] for i in range(len(x)//2))>0

The idea was to substract the first digit from the last, second from second last... and check if the sum of all substractions is greater then 0.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Can you use string indexes? \$\endgroup\$ – Titus May 5 '17 at 11:40
  • \$\begingroup\$ @erbsenhirn use x[i]-x[~i] for the same output. you can index python lists with negative indices, -1 being the last, so x[-i-1] would do the trick, but -i-1 == ~i :D \$\endgroup\$ – Felipe Nardi Batista May 5 '17 at 12:34
  • \$\begingroup\$ @erbsenhirn you can remove [ ] from the sum, as: sum(x[i]....range(len(x)/2))>0 \$\endgroup\$ – Felipe Nardi Batista May 5 '17 at 13:28
  • \$\begingroup\$ Nice approach, but it doesn't beat doing it the regular way. \$\endgroup\$ – totallyhuman May 5 '17 at 13:51
2
\$\begingroup\$

Actually, 7 bytes

2,╡♂Σi>

Input is taken as a list of digits. Try it online!

Explanation:

2,╡♂Σi>
2,╡      split input into two equal sublists
   ♂Σ    sum each sublist
     i>  is first sum greater than second sum?
\$\endgroup\$
2
\$\begingroup\$

Jelly, 10 7 bytes

œs2S€>/

Saved a byte by changing the input to a list of digits.

Saved several more thanks to Leaky Nun!

Try it online!

Explanation:

œs2    Split that list into 2 chunks
   S€  Sum each chunk individually
>/     Reduce the resulting list by relative compare.

Prepend this to work with integer input instead of a list:

D       Turn the integer into a list of digits
\$\endgroup\$
2
\$\begingroup\$

JavaScript (ES6), 44 bytes

f=([n,...a],d=0)=>1/n?f(a,d-=n-=a.pop()):d<0
<input oninput=o.textContent=this.value.length%2?``:f(this.value)><pre id=o>

Takes input as a string or array of digits as characters or integers.

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

C (gcc), 79 or 75

better version (80 char -> 79 thanks to titus )

f(char*s){int i=0,n=strlen(s--)/2;for(;*(++s+n);)i-=*s-s[n];putchar(48+(i<0));}

Try it online!

next, 75 bytes if we rely on constant undefined behaviour,

f(char*s){int i=0,n=strlen(s)/2;for(;s[n];)i-=*s-s++[n];putchar(48+(i<0);}

Try it online!

input valid string in C (a zero terminated array of char) output 1 for true, 0 for false

ungolfed version

f(char*s)
{
    int i=0;
    int n=strlen(s)/2; /* n is the length of each strings  so we have 
                          the start of the first string at *s or s[0],
                          and the start of the second sequence at s[n] 
                        */
    for(;s[n];) /* until we get 0, all string in C are terminated by 0 */
        i-=*s-s++[n]; /* i is the difference between the two characters *s and s[n], 
        then we move the cursor to the next character (s++) :) 
        on the string 12345678, after the first iteration we have 
        i == -4 and 234,678 the proceed
        */
    putchar(48+(i<0)); /* put char '0' if i<0, char '0'+1 otherwise (the char '1')
 } 
\$\endgroup\$
  • 1
    \$\begingroup\$ i-=*s-s++[n]; invokes undefined behaviour. \$\endgroup\$ – mch May 5 '17 at 11:06
  • 1
    \$\begingroup\$ Would 48+(i<0) work? \$\endgroup\$ – Titus May 5 '17 at 12:15
2
\$\begingroup\$

C#, 148 bytes

void q(){var a=Console.ReadLine();int b=0,c=0,i=0,d=a.Length/2;for(;i<d;i++){b+=int.Parse(a[i]+"");c+=int.Parse(a[i+d]+"");}Console.WriteLine(b>c);}
\$\endgroup\$
1
\$\begingroup\$

Braingolf, 20 bytes

dl2/2->[+]>l3->[+],-

Try it online!

Figured nobody else is likely to post a braingolf answer, so here's mine. Takes input as an integer, Prints a positive number for truthy, and a negative number or zero for falsey

Explanation:

dl2/2->[+]>l3->[+],-
d                     Split last item on stack into digits, push each digit to stack
 l                    Push length of stack to stack
  2/                  Halve last item on stack
    2-                Subtract 2 from last item on stack
      >               Move last item on stack to start of stack
       [+]            Sum last 2 items of stack 3 times (last 4 items)
          >           Move last item on stack to start of stack
           l          Push length of stack to stack
            3-        Subtract 3 from last item on stack
              [+]     Sum last 2 items of stack 3 times (last 4 items)
                 ,-   Subtract last item (sum of first half) from 2nd to last (sum of 2nd half)
                      Implicit: Print last item on stack
\$\endgroup\$
1
\$\begingroup\$

Batch, 122 bytes

@set/al=r=0
@set/ps=
:l
@set/al+=%s:~,1%,r+=%s:~-1%
@set s=%s:~1,-1%
@if not "%s%"=="" goto l
@if %l% gtr %r% echo 1

Takes input on STDIN and outputs 1 if the value is significant.

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

Java, 95 94 bytes

boolean f(long n){int x=10,a=x,s=0;for(;a<n;n/=x,a*=x)s+=n%x;for(;n>0;n/=x)s-=n%x;return s<0;}

Try it online!

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

Haskell, 40 38 bytes

f s=sum s<2*sum(take(div(length s)2)s)

Try it online! Takes the integer as list of digits and returns either True or False. Example usage: f [1,2,3,4].

f s=                                   -- function f takes a list s
    sum s                              -- return whether the sum of s
         <2*sum(                     ) -- is smaller than two times the sum of
                take(div(length s)2)s  -- the first (length s/2) elements of s

Edit: Thanks to @nimi for -2 bytes.

\$\endgroup\$
  • \$\begingroup\$ @nimi Thanks, I was thinking to complicated ... \$\endgroup\$ – Laikoni May 5 '17 at 13:57
1
\$\begingroup\$

Japt, 29 17 bytes

Saved 12 bytes thanks to ETHproductions and obarakon

¯½*Ul)x >Us½*Ul)x

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Nice answer! The input can be an array, so you can do something like A=Ul /2U¯A x >UtA x \$\endgroup\$ – Oliver May 5 '17 at 13:59
  • \$\begingroup\$ ¯½*Ul)x >UsUl /2 x for 18 bytes! \$\endgroup\$ – Oliver May 5 '17 at 14:46
  • \$\begingroup\$ @obarakon And another byte off that: ¯½*Ul)x >Us½*Ul)x (It brings a tear of joy to my eye to see someone other than myself helping someone else golf in Japt, haha) \$\endgroup\$ – ETHproductions May 5 '17 at 15:45
  • \$\begingroup\$ @ETHproductions Oh, I didn't think would work. Sweet! \$\endgroup\$ – Oliver May 5 '17 at 15:47
  • \$\begingroup\$ @obarakon It's a bug in the current version of the online interpreter, but not in TIO. I'll push a fix in a couple minutes... \$\endgroup\$ – ETHproductions May 5 '17 at 16:04
1
\$\begingroup\$

Mathematica 36 Bytes

#>#2&@@BlockMap[Total,#,Length@#/2]&
\$\endgroup\$
1
\$\begingroup\$

Lua, 65 bytes

s=...load("x="..s:gsub(".","+%0"):gsub("+","-",#s/2))()print(x<0)

Steps of conversion:

1234
+1+2+3+4
-1-2+3+4
x=-1-2+3+4
eval the last string
print(x<0)

Usage:

$ lua program.lua 1234
false
\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 67 65 bytes

I think it might be too early in the morning for golf; this seems much longer than it needs to be!

Takes input as an array of individual digits.

n=>(g=(a,b)=>eval(n.slice(a,b).join`+`))(0,l=n.length/2)>g(l,l+l)

Try it

f=
n=>(g=(a,b)=>eval(n.slice(a,b).join`+`))(0,l=n.length/2)>g(l,l+l)
console.log(f([1,2,3,4,5,6,7,8])) // false
console.log(f([8,7,6,5,4,3,2,1])) // true
console.log(f([1,2,3,4,4,3,2,1])) // false
console.log(f([1,2])) // false
console.log(f([2,1,4,7,5,8,3,9,2,6,3,9,5,4,3,3,8,5])) // false
console.log(f([1,0,0,1])) // false
console.log(f([1,0,0,0,0,0])) // true

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

Pyth, 9 bytes

>.*msdc2Q

Takes an array of integers.

Try it!

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

Brain-Flak, 98 bytes

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

Try it online!

#Push half of the input onto the alternate stack in reverse
(()){{}({}<>)([][<>[]])}{}

#Sum the main stack
({{}})<>

#Sum the alternate stack and subtract the sum of the main stack +1 from it
({{}}<>[{}()])

#Greater than or equal to 0?
([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}

Credit to Wheat Wizard, Riley, and MegaTom for collaboratively coming up with that greater than 0 snippet in chat

\$\endgroup\$
  • \$\begingroup\$ It's a bit sad how half of the code is >=0. \$\endgroup\$ – Erik the Outgolfer May 6 '17 at 10:26
0
\$\begingroup\$

CJam, 12 bytes

l~_,2//::+~>

Explanation:

l~  e# Read line and evaluate:   | [1 2 3 4 5 6 7 8]
_,  e# Duplicate and get length: | [1 2 3 4 5 6 7 8] 8
2/  e# Divide by 2:              | [1 2 3 4 5 6 7 8] 4
/   e# Break into groups:        | [[1 2 3 4] [5 6 7 8]]
::+ e# Sum each:                 | [10 26]
~   e# Unpack:                   | 10 26
>   e# More than:                | 0 (false)
\$\endgroup\$
0
\$\begingroup\$

Clojure, 44 bytes

#(neg?(apply +(map -(drop(/(count %)2)%)%)))

Input is a sequence of ASCII integers. This ended up being a bit shorted than using split-at, and also avoids for as map stops when one of the input lists runs out. So this substracts element-wise the two halves of the input and checks if the sum of differences is negative or not (as we are substracting the second half from the first).

(def f #(neg?(apply +(map -(drop(/(count %)2)%)%))))
(f (map int "214758392639543385"))
\$\endgroup\$

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