22
\$\begingroup\$

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\$
3
  • 2
    \$\begingroup\$ The "duplicate" is an = check, this is a > check. I don't think they're duplicates. \$\endgroup\$ Commented May 6, 2017 at 18:01
  • 1
    \$\begingroup\$ Voting to reopen, because even though the differences are small, they obviously make a large difference given that answers to this are often 15-20 bytes smaller than the :duplicate". \$\endgroup\$ Commented Oct 22, 2020 at 12:43
  • \$\begingroup\$ I am reopening this challenge because the difference between > and = is not too major, but the guarantee of an even length integer changes the entire approach that a lot of answers use (not just removing one or two bytes). \$\endgroup\$
    – hyper-neutrino
    Commented Oct 22, 2020 at 15:53

41 Answers 41

7
\$\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
  • 1
    \$\begingroup\$ I like the use of ASCII values and calculating the mean, always cool to see different approaches to the task. \$\endgroup\$
    – Mayube
    Commented May 5, 2017 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\$
3
  • \$\begingroup\$ How does it only remove the first and last semicolons each iteration? \$\endgroup\$
    – user41805
    Commented May 5, 2017 at 9:11
  • \$\begingroup\$ The * in .* is maximal matching (greedy), so it would match as much as possible. \$\endgroup\$
    – Leaky Nun
    Commented May 5, 2017 at 9:11
  • \$\begingroup\$ @KritixiLithos * is greedy, so it skips as many ;s as possible. \$\endgroup\$
    – Neil
    Commented May 5, 2017 at 9:12
5
\$\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\$
3
  • \$\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\$
    – Mayube
    Commented May 5, 2017 at 9:07
  • \$\begingroup\$ What does the (?<number>) do? \$\endgroup\$
    – user41805
    Commented May 5, 2017 at 10:43
  • \$\begingroup\$ They are called balancing groups. Please refer to an answer written by Martin Ender on SO. \$\endgroup\$
    – Leaky Nun
    Commented May 5, 2017 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\$
2
  • \$\begingroup\$ Oh, we're even now... \$\endgroup\$
    – Leaky Nun
    Commented May 5, 2017 at 8:28
  • \$\begingroup\$ @LeakyNun: I like yours better though, due to the input format. \$\endgroup\$
    – Emigna
    Commented May 5, 2017 at 8:29
3
\$\begingroup\$

Retina, 60 40 bytes

Saved some bytes thanks to @MartinEnder

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

Try it online!

\$\endgroup\$
0
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\$
4
  • 1
    \$\begingroup\$ Golfed \$\endgroup\$
    – Leaky Nun
    Commented May 5, 2017 at 10:17
  • \$\begingroup\$ @LeakyNun I should really learn how map() works. o0 Thanks! \$\endgroup\$ Commented May 5, 2017 at 10:39
  • 1
    \$\begingroup\$ Hint: the sum of both halves is the total. \$\endgroup\$
    – Dennis
    Commented May 5, 2017 at 15:47
  • \$\begingroup\$ @Dennis I hope this is what you meant. \$\endgroup\$ Commented May 5, 2017 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\$
4
  • \$\begingroup\$ Can you use string indexes? \$\endgroup\$
    – Titus
    Commented May 5, 2017 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\$ Commented May 5, 2017 at 12:34
  • \$\begingroup\$ @erbsenhirn you can remove [ ] from the sum, as: sum(x[i]....range(len(x)/2))>0 \$\endgroup\$ Commented May 5, 2017 at 13:28
  • \$\begingroup\$ Nice approach, but it doesn't beat doing it the regular way. \$\endgroup\$ Commented May 5, 2017 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\$
1
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#, 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\$
2
\$\begingroup\$

Husk, 5 bytes

F<mΣ½

Try it online!

Input as an array of integers.

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

GolfScript, 13 bytes

.,2//{{+}*}/>

Try it online!

.,              # Get the length of the input                        "12345678" 8
  2/            # Half it                                            "12345678" 4
    /           # Divide the string in groups of that many digits    ["1234" "5678"]
     {    }/    # For each string
      {+}*      # Add the ascii values                               202 218
            >   # Is the first bigger than the second?               0

It actually adds the ascii values of the numbers, but both groups of digits have d digits, so both results are 48*d more than the actual value. This would only be a problem if the groups had different lengths.

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

C (gcc), 79 or 75, 74

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

and now 74 thanks to "a stone arachnid"

C (gcc), 74 bytes

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

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ i-=*s-s++[n]; invokes undefined behaviour. \$\endgroup\$
    – mch
    Commented May 5, 2017 at 11:06
  • 1
    \$\begingroup\$ Would 48+(i<0) work? \$\endgroup\$
    – Titus
    Commented May 5, 2017 at 12:15
  • \$\begingroup\$ printf("%d",i<0) is shorter than putchar(48+(i<0)): Try it online! \$\endgroup\$ Commented Apr 26, 2021 at 16:12
2
\$\begingroup\$

Vyxal, 8 7 6 bytes

Thanks to @Razetime for saving 1 byte due to the command auto-vectorising.

½⌊v∑>t

Try it Online!

Takes input in the form of "12345678". Alternatively, the quotes can be left out if the flag is used.

I’m gonna be honest, I’m not really sure what the > is doing since (a:string, b:list) isn’t documented for that command, but I was messing with it and found that in this case it returns <1|0> or <1|1>, so I take the last value of the list and that’s the answer.

Explanation:

        # Implicit input
½       # Split the input into two chunks
 ⌊      # Convert both chunks to integers
  v∑    # Sum the digits of each chunk
    >   # Some sort of a>b thing?
     t  # Tail; last item
        # Implicit output
\$\endgroup\$
3
  • \$\begingroup\$ v⌊ -> since it auto vectorizes \$\endgroup\$
    – Razetime
    Commented Apr 27, 2021 at 13:49
  • \$\begingroup\$ @Razetime Added. Thanks for pointing that out. \$\endgroup\$ Commented Apr 27, 2021 at 13:58
  • \$\begingroup\$ Very clever usage of . +1 \$\endgroup\$
    – lyxal
    Commented Apr 28, 2021 at 2:10
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\$
0
1
\$\begingroup\$

Japt, 29 17 bytes

Saved 12 bytes thanks to ETHproductions and obarakon

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

Try it online!

\$\endgroup\$
6
  • \$\begingroup\$ Nice answer! The input can be an array, so you can do something like A=Ul /2U¯A x >UtA x \$\endgroup\$
    – Oliver
    Commented May 5, 2017 at 13:59
  • \$\begingroup\$ ¯½*Ul)x >UsUl /2 x for 18 bytes! \$\endgroup\$
    – Oliver
    Commented May 5, 2017 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\$ Commented May 5, 2017 at 15:45
  • \$\begingroup\$ @ETHproductions Oh, I didn't think would work. Sweet! \$\endgroup\$
    – Oliver
    Commented May 5, 2017 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\$ Commented May 5, 2017 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\$
1
\$\begingroup\$

K (oK), 13 10 9 bytes

-4 bytes by making tacit

>/+/0N 2#

Try it online!

Takes a list of integers as the input.

  • 0N 2# split input into pairs
  • +/ sum the pairs column-wise
  • >/ is the sum of the first chunk larger than the sum of the second?
\$\endgroup\$
1
\$\begingroup\$

Factor + math.unicode, 20 bytes

[ halves v- Σ 0 > ]

Try it online!

Explanation:

It's a quotation (anonymous function) that takes a sequence of integers from the data stack as input and leaves a boolean value on the data stack as output. Assuming { 1 2 3 4 5 6 7 8 } is on top of the data stack when this quotation is called...

  • halves Split a sequence in half.

    Stack: { 1 2 3 4 } { 5 6 7 8 }

  • v- Element-wise subtraction of two vectors. (This is shorter than summing each sequence individually.)

    Stack: { -4 -4 -4 -4 }

  • Σ Sum.

    Stack: -16

  • 0 > Is it greater than zero?

    Stack: f

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

Thunno 2, 5 bytes

2ẆʂØv

Try it online!

Explanation

2ẆʂØv  # Implicit input
2Ẇ     # Split into 2 pieces
  ʂ    # Sum each inner list
   Øv  # Strictly decreasing?
       # Implicit output
\$\endgroup\$

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.