Does the sum of 2 numbers in the list equal the desired sum?

27

1

The Task

This is my first challenge so apologies if it is very simple! In this challenge, your task is to write a program or function which takes in a list of integers and a desired sum and outputs a truthy or falsey value based on whether the list contains two numbers that can be summed together to achieve the desired sum.

Input

The input must be acquired in a standard way for your language. The list of integers can be any standard collection type for your language but cannot be a hashed set, sorted set, or any highly functional collection type. Don't assume the input is sorted, any valid integer type is acceptable.

The desired sum is also an integer and must be provided to your program as input.

Output

The output may be a function return, console log, writing to a file, etc... Any valid Truthy or Falsey value is acceptable.

Additional Rules

  • The input list may or may not be sorted.
  • Duplicate values may occur in the list
  • The same item in the list may not be summed to itself to achieve the desired sum (Eg. [3,4,5] with desired sum 6 will expect False because 3 cannot be used twice)
  • Standard loopholes are not allowed.

Test Cases

INPUT                 OUTPUT
[3,4,5], 6            Falsey
[1,2,3,4,5,6],11      Truthy
[4,23,8174,42,-1],41  Truthy
[1,1,1,1,1,3],3       Falsey
[2,1,1,1,53,2],4      Truthy
[2,2,2,2],4           Truthy
[3],3                 Falsey
[],-43                Falsey

This is , so the shortest code in bytes wins!

maple_shaft

Posted 2017-05-16T11:58:47.293

Reputation: 421

Question was closed 2017-05-16T16:10:18.103

at least two numbers or just two numbers? – marmeladze – 2017-05-16T12:13:04.877

1@marmeladze Just 2 numbers. – maple_shaft – 2017-05-16T12:16:55.690

8Nice first challenge! – HyperNeutrino – 2017-05-16T12:34:43.850

Can the sum integer be zero or negative? – Kevin Cruijssen – 2017-05-16T13:54:51.500

1Can we assume that the input least contains at least 2 elements? – Arnauld – 2017-05-16T14:09:07.057

@Arnauld No. I should add those test cases. – maple_shaft – 2017-05-16T14:14:32.060

Could we take in a length of the list and.or assume a certain sentinel value will not be in the input? – Rohan Jhunjhunwala – 2017-05-16T14:21:24.483

@RohanJhunjhunwala Any possible integer for desired sum and any possible integer within the list so no sentinel values. Only two inputs, length is not provided. – maple_shaft – 2017-05-16T14:50:20.967

@maple_shaft my language doesn't support a native list type, it can really only take in a null terminated string or a list of numbers with a sentinel,shouldn't this be the "native" list type? – Rohan Jhunjhunwala – 2017-05-16T15:06:06.670

1Can we choose an empty output for falsey and 1 for truthy? – Mr. Xcoder – 2017-05-16T15:43:43.693

[3],6 should also be Falsey, which one solution might currently accept as truthy. – Joey – 2017-05-16T15:56:16.117

4I think the other challenge should be closed as a duplicate of this one instead. I like this one better. – mbomb007 – 2017-05-16T19:12:41.513

Answers

9

Brachylog, 3 bytes

⊇Ċ+

Try it online!

⊇Ċ+   input as STDIN, output as ARG1
      (prove that:)
⊇     the input is a superset of
 Ċ       a list of two elements
  +         which sums up to the output

Leaky Nun

Posted 2017-05-16T11:58:47.293

Reputation: 45 011

1@Fatalize For the love of God, I was having a dinner. – Leaky Nun – 2017-05-16T12:27:56.527

5

Jelly, 7 6 5 bytes

ŒcS€ċ

Try it online!

-1 byte by using the Unordered Pairs atom

ŒcS€ċ  Main Link; left argument is the array, right argument is the required sum
  S€   Take the sum of each...
Œc     ...unordered pair...
    ċ  Check if the sum array contains the right argument

-1 byte thanks to Erik!

HyperNeutrino

Posted 2017-05-16T11:58:47.293

Reputation: 26 575

You can use ċ instead of ⁹e to outgolf MATL. The rules don't specify that the values must be consistent, only truthy/falsey. – Erik the Outgolfer – 2017-05-16T13:25:22.830

@EriktheOutgolfer Oh thanks :D Outgolfed MATL and 05AB1E :) – HyperNeutrino – 2017-05-16T13:45:23.120

Umm, your TIO doesn't contain any code? ;) And you forgot to change the 6 to <s>6</s> 5 based on your edit? – Kevin Cruijssen – 2017-05-16T13:56:33.633

@KevinCruijssen Ehhh lol thanks, I failed at copy-pasting. And yes I forgot that, thanks! :D – HyperNeutrino – 2017-05-16T14:01:42.690

4

05AB1E, 6 bytes

æ2ùOIå

Try it online!

Explanation

æ        # get powerset of first input
 2ù      # keep only those of size 2
   O     # sum each
    Iå   # check if 2nd input is in the list of sums

Emigna

Posted 2017-05-16T11:58:47.293

Reputation: 50 798

4

Python 2, 43 42 bytes

-1 byte thanks to mbomb007

lambda a,b:any(b-a.pop()in a for x in a*1)

Try it online!

Rod

Posted 2017-05-16T11:58:47.293

Reputation: 17 588

Why do you need [:]? – Erik the Outgolfer – 2017-05-16T13:51:02.760

@EriktheOutgolfer because I'm using a.pop() and iterating over a, without it it will iterate over the popped list, resulting in only half runs. a[:] is there just to make the code run len(a) times. – Rod – 2017-05-16T13:55:05.900

Oh so that's how you make a copy of a list. What code-golf teaches you... – Erik the Outgolfer – 2017-05-16T13:57:12.163

1Better TIO test suite. Also, can you use 1*a instead of a[:]? – mbomb007 – 2017-05-16T14:26:08.587

1@mbomb007 yep, now it has a perfect score :3 – Rod – 2017-05-16T14:31:40.740

Is there a test case you could use that would give a different answer if you had a instead of a*1? Because right now, the results are the same. – mbomb007 – 2017-05-16T14:33:13.033

@mbomb007 [0, 1, 2, 3, 4],1 or any case where the right numbers are in the first half if the list – Rod – 2017-05-16T14:37:57.073

4

Mathematica, 29 bytes

!FreeQ[Tr/@#~Subsets~{2},#2]&

JungHwan Min

Posted 2017-05-16T11:58:47.293

Reputation: 13 290

3

MATL, 6 bytes

2XN!sm

Try it online!

Explanation

2XN   % Implicitly input an array. Combinations of elements taken 2 at a time
      % The result is a matrix where each row is a combination
!s    % Sum of each row
m     % Implicitly input a number. Ismember function. Implicitly display

Luis Mendo

Posted 2017-05-16T11:58:47.293

Reputation: 87 464

3

JavaScript (ES6), 38 43 bytes

a=>n=>[...a].some(_=>a.includes(n-a.pop()))

Try It

f=
a=>n=>[...a].some(_=>a.includes(n-a.pop()))
o.innerText=`           f([3,4,5])(6) = ${f([3,4,5])(6)}
    f([1,2,3,4,5,6])(11) = ${f([1,2,3,4,5,6])(11)}
f([4,23,8174,42,-1])(41) = ${f([4,23,8174,42,-1])(41)}
     f([1,1,1,1,1,3])(3) = ${f([1,1,1,1,1,3])(3)}
    f([2,1,1,1,53,2])(4) = ${f([2,1,1,1,53,2])(4)}
         f([2,2,2,2])(4) = ${f([2,2,2,2])(4)}
               f([3])(3) = ${f([3])(3)}
              f([])(-43) = ${f([])(-43)}
     f([1,2,3,4,5,6])(3) = ${f([1,2,3,4,5,6])(3)}`
pre{font-size:14px;line-height:1.75}
<pre id=o>

Shaggy

Posted 2017-05-16T11:58:47.293

Reputation: 24 623

1Doesn't work for f([1,2,3,4,5,6])(3). Try using [...a].some instead? – Neil – 2017-05-16T14:53:22.603

Out of interest I tried porting Rod's Python answer, it also came out at 43 bytes. – Neil – 2017-05-16T14:58:28.463

@Neil, I was trying to figure out a shorter way, without using includes() but I couldn't see it. – Shaggy – 2017-05-16T15:20:13.957

3

Haskell, 39 37 36 bytes

(a:t)#n=n`elem`map(a+)t||t#n
_#n=1<0

Try it online! Example usage: [1,3,2,5] # 3. Returns True or False.


Alternative (also 36 bytes)

f(a:t)=map(a+)t++f t
f e=e
(.f).elem

Laikoni

Posted 2017-05-16T11:58:47.293

Reputation: 23 676

I felt like using applicatives that you can get this in only 31 bytes but it fails a couple test cases for some reason: g x d=any(\x->x==d)$(+)<$>x<*>x – maple_shaft – 2017-05-16T14:20:53.853

@maple_shaft Interesting idea, but it computes for each list element also the sum with itself, that's way some test cases fail. By the way it can be shortened to 22 bytes: x#d=elem d$(+)<$>x<*>x – Laikoni – 2017-05-16T16:20:58.720

3

C, 114 113 bytes

i,j,k="F";main(c,v)char**v;{for(--c;++i<c;)for(j=0;++j<c;)k=j^i&atoi(v[i])+atoi(v[j])==atoi(v[c])?"T":k;puts(k);}

Here's the output

C:\eng\golf>a.exe 3 4 5 6
F
C:\eng\golf>a.exe 1 2 3 4 5 6 11
T
C:\eng\golf>a.exe 4 23 8174 42 -1 41
T
C:\eng\golf>a.exe 1 1 1 1 1 3
F
C:\eng\golf>a.exe 2 1 1 1 53 2 4
T
C:\eng\golf>a.exe 2 2 2 2 4
T

cleblanc

Posted 2017-05-16T11:58:47.293

Reputation: 3 360

2

Ruby, 59 53 37 bytes

inspiration comes from this answer

->a,b{a.map{|e|a.include?(b-e)}.any?}

will now look where can I chop a few bytes -))

HISTORY

#53 bytes
->a,b{a.combination(2).map{|e|e.reduce(&:+)==b}.any?}

#59 bytes 
->a,b{a.combination(2).map{|e|e.reduce(&:+)}.any?{|x|x==b}}

marmeladze

Posted 2017-05-16T11:58:47.293

Reputation: 227

2

PHP (>= 7.1), 53 51 50 46 Bytes

<?foreach($_GET[0]as$c)+$$c||${$_GET[1]-$c}=a;

sadly it's quite big but at least better than 2 loops. +a fails with a warning if the sum can be made => non empty output => truthy. Outputs nothing if the sum can not be made => falsey.

Thanks @user63956 !

Christoph

Posted 2017-05-16T11:58:47.293

Reputation: 1 489

You forget the <? and if the terminate in true cases should be printable the shortest status i Know is !0 – Jörg Hülsermann – 2017-05-16T13:36:22.863

@JörgHülsermann <? for $_GET? Fair enough. Why should I print something if I can use exit code golfing? If I wanted to print something die(a) would also work just fine. – Christoph – 2017-05-16T13:45:26.203

Can you explain me how you will get the exit code when it not is printed with using the $_GET array as input? http://sandbox.onlinephpfunctions.com/code/537bbdd8b7f8a06f573b88d37b7b81327f673b0b

– Jörg Hülsermann – 2017-05-16T13:59:42.537

@JörgHülsermann Using CGI – Christoph – 2017-05-16T14:07:01.933

Thank You I have never tried CGI and $_GET together before. I am sad that I could only one upvote – Jörg Hülsermann – 2017-05-16T14:17:37.580

1You can save a few bytes with variable variables instead of $q: $$c and ${$_GET[1]-$c}. – user63956 – 2017-05-17T06:06:21.243

2

TAESGL, 8 bytes

Ş⇒AĨB-AĖ

Interpreter

Explanation

Ş⇒        Array.some with anonymous function on implicit input
  AĨ      first input includes
    B-    second input minus
      AĖ  first input popped

Tom

Posted 2017-05-16T11:58:47.293

Reputation: 3 078

2

Clojure, 53 bytes

#(loop[[v & r]%](if v(or((set r)(- %2 v))(recur r))))

Uses destructuring to take the first and rest of the input list (and subsequent recur of rest), and returns the number "target - value1" if found in the set of remaining numbers (a "truthy"), nil otherwise.

NikoNyrh

Posted 2017-05-16T11:58:47.293

Reputation: 2 361

2

Java 7, 138 bytes

boolean c(int[]a,int s){String r="";for(int l=a.length,i=0,j;i<l;i++)for(j=-1;++j<l;)if(i!=j)r+=(a[i]+a[j])+",";return r.contains(s+",");}

Explanation:

boolean c(int[]a,int s){             // Method with integer-array and integer parameters and boolean return-type
  String r="";                       // Temp String
  for(int l=a.length,i=0,j;i<l;i++)  //  Loop (1) over the input array
    for(j=-1;++j<l;)                 //   Inner loop (2) over the input array again
      if(i!=j)                       //    If the index of both loops aren't equal (so not the same item in the list)
        r+=(a[i]+a[j])+",";          //     Append the sum with a comma to the temp-String
                                     //   End of loop (2) (implicit / single-line body)
                                     //  End of loop (1) (implicit / single-line body)
  return r.contains(s+",");          //  Return whether the temp-String contains the given sum (+ comma)
}                                    // End of method

Test code:

Try it here.

class M{
  static boolean c(int[]a,int s){String r="";for(int l=a.length,i=0,j;i<l;i++)for(j=-1;++j<l;)if(i!=j)r+=(a[i]+a[j])+",";return r.contains(s+",");}

  public static void main(String[] a){
    System.out.println(c(new int[]{1,2,3,4,5,6},11));
    System.out.println(c(new int[]{4,23,8174,42,-1},41));
    System.out.println(c(new int[]{2,1,1,1,53,2},4));
    System.out.println(c(new int[]{2,2,2,2},4));
    System.out.println();
    System.out.println(c(new int[]{1,1,1,1,1,3},3));
    System.out.println(c(new int[]{3,4,5},6));
  }
}

Output:

true
true
true
true

false
false

Kevin Cruijssen

Posted 2017-05-16T11:58:47.293

Reputation: 67 575

1

Mathematica, 38 bytes

MemberQ[Total/@#~Permutations~{2},#2]&

input style [{1,2,3,4,5,6},11]

J42161217

Posted 2017-05-16T11:58:47.293

Reputation: 15 931

# is short for #1, and infix notations can shave a byte: MemberQ[Total/@#~Permutations~{2},#2]& – JungHwan Min – 2017-05-16T13:29:32.913

@JungHwan thanks. I'm new to this. Where is your answer? – J42161217 – 2017-05-16T13:34:27.433

1

R, 32 bytes

function(x,l)x%in%combn(l,2,sum)

Returns an anonymous function. combn returns all combinations of l taken m at a time, in this case 2, and then optionally applies a function, in this case sum. Returns an empty logical vector logical(0) for an empty first input, which I define for this problem as falsey, and TRUE or FALSE corresponding to the other elements otherwise.

Try it online!

Giuseppe

Posted 2017-05-16T11:58:47.293

Reputation: 21 077

1

Python 3, 41 bytes

f=lambda a,b,*c:a-b in c or c and f(a,*c)

Try it online!
Recursive aproach with flexible input and output. Returns an empty set as falsy.

Rod

Posted 2017-05-16T11:58:47.293

Reputation: 17 588

This doesn't work for test case [], -43. Try it online

– mbomb007 – 2017-05-16T19:48:23.343

1

MATLAB, 28 bytes

@(a,b)any(pdist(a,@plus)==b)

This defines an anonymous function with inputs a: column vector (possibly empty); b: number.

The code also works in Octave except if the first input is empty, which causes an error. Try it online!

Explanation

pdist(a,@fun) applies function fun (in our case, addition) to each combination of two rows of the input matrix a (in our case, a column vector). The output is a column vector. any(...==b) gives true if any of the results equals the input number b.

Luis Mendo

Posted 2017-05-16T11:58:47.293

Reputation: 87 464

1

Pyth - 9 bytes

/msd.cE2E

Try it

/msd.cE2E
    .cE2     # All subsets of length 2
 msd         # The sum of each subset
/       E    # Number of occurrences of the input number

Maria

Posted 2017-05-16T11:58:47.293

Reputation: 644

0

Axiom, 90 92 bytes

f(a,k)==(for i in 1..#a-1 repeat for j in i+1..#a repeat(q:=a.i+a.j;q=k=>return true);false)

test

(42) -> f([3,4,5],6)
   (42)  false
                                                            Type: Boolean
(43) -> f([1,2,3,4,5,6],11)
   (43)  true
                                                            Type: Boolean
(44) -> f([4,23,8174,42,-1],11)
   (44)  false
                                                            Type: Boolean
(45) -> f([4,23,8174,42,-1],41)
   (45)  true
                                                            Type: Boolean
(46) -> f([2,23,8174,42,2],2)
   (46)  false

RosLuP

Posted 2017-05-16T11:58:47.293

Reputation: 3 036

0

Python 2, 71 bytes

from itertools import*
lambda L,n:n in map(sum,list(combinations(L,2)))

Try it online

Yes, I know there is already a better solution posted.

mbomb007

Posted 2017-05-16T11:58:47.293

Reputation: 21 944

0

C#, 96 90 bytes

using System.Linq;a=>n=>Enumerable.Range(0,a.Count).Any(i=>a.Skip(i+1).Any(j=>a[i]+j==n));

Compiles to a Func<List<int>, Func<int, bool>>. Formatted version:

Func<List<int>, Func<int, bool>> f = a => n =>
    Enumerable.Range(0, a.Count).Any(i => a.Skip(i + 1).Any(j => a[i] + j == n));

Old for loop version for 96 bytes:

a=>n=>{for(int i=0,j,l=a.Count;i<l;++i)for(j=i+1;j<l;)if(a[i]+a[j++]==n)return 1>0;return 1<0;};

TheLethalCoder

Posted 2017-05-16T11:58:47.293

Reputation: 6 930

0

C#, 103 102 bytes


Data

  • Input Int32[] l A list of Int32 to sum
  • Input Int32 r The result to check against
  • Output Boolean A result indicating if the sum can be performed

Golfed

(int[] l,int r)=>{for(int x=l.Length,y;--x>=0;)for(y=0;y<x;)if(l[x]+l[y++]==r)return 1>0;return 0>1;};

Ungolfed

( int[] l, int r ) => {
   for( int x = l.Length, y; --x >= 0; )
      for( y = 0; y < x; )
         if( l[ x ] + l[ y++ ] == r )
            return 1 > 0;

   return 0 > 1;
};

Ungolfed readable

Working on it...


Full code

using System;
using System.Collections.Generic;

namespace Namespace {
   class Program {
      static void Main( String[] args ) {
        Func<Int32[], Int32, Boolean> f = ( int[] l, int r ) => {
            for( int x = l.Length, y; --x >= 0; )
                for( y = 0; y < x; )
                    if( l[ x ] + l[ y++ ] == r )
                        return 1 > 0;

            return 0 > 1;
        };

        List<KeyValuePair<Int32[], Int32>>
            testCases = new List<KeyValuePair<Int32[], Int32>>() {
                new KeyValuePair<Int32[], Int32>( new Int32[] { 3, 4, 5 }, 6 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 1, 2, 3, 4, 5, 6 }, 11 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 4, 23, 8174, 42, -1 }, 41 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 1, 1, 1, 1, 1, 3 }, 3 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 2, 1, 1, 1, 53, 2 }, 4 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 2, 2, 2, 2 }, 4 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] { 3 }, 3 ),
                new KeyValuePair<Int32[], Int32>( new Int32[] {  }, -43 ),
            };

        foreach( var testCase in testCases ) {
            Console.WriteLine( $" Input: {testCase.Value}; {{ {String.Join(", ", testCase.Key)} }}\nOutput: {f( testCase.Key, testCase.Value )}\n" );
        }

         Console.ReadLine();
      }
   }
}

Releases

  • v1.1 -  -1 byte  - Thanks to TheLethalCoder suggestion.
  • v1.0 - 103 bytes - Initial solution.

Notes

  • None

auhmaan

Posted 2017-05-16T11:58:47.293

Reputation: 906

(int[] l,int r)=> can just be (l,r)=>, however, you can also use currying to shave another byte off of that l=>r=>. Pass in a list instead of an array to save another byte by using Count instead of Length. You can set y = to zero and do a post increment in the array indexer instead. – TheLethalCoder – 2017-05-16T15:06:25.820

Put that together for 90 bytes: l=>r=>{for(int x=l.Count,y;--x>=0;)for(y=0;y<x;)if(l[x]+l[y++]==r)return 1>0;return 0>1;};. Note that I haven't tested this put it looks correct. Now comes in at the same count as my Linq answer :) – TheLethalCoder – 2017-05-16T15:15:30.140

Hey @TheLethalCoder, thanks for your suggestions, but some days ago I've got in a discussion with another member of CodeGolf and I have submitted myself to explicitly type the input types since then, hence the (int[] l,int r). Also, I refrain from using Lists and other classes that require usings -- although when I use them, I type the full name, i.e. System.Collections.Generic.List. – auhmaan – 2017-05-16T15:40:25.090

You don't need to explicitly type them but your choice. You can still save one byte by changing y=-1 to y=0 and post incrementing in the indexer instead of the loop condition. – TheLethalCoder – 2017-05-16T15:41:47.070

If I'm thinking correctly, your suggestion is to change for( y =- 1; ++y < x; ) to for( y = 0; y++ < x; ), but that would cause IndexOutOfRangeException to be thrown, which, to be fixed, I had to change the for to for( y = 0; y < x; y++ ), which would result in the same byte count. – auhmaan – 2017-05-16T16:07:13.740

1No change for(y=-1;++y<x;)if(l[x]+l[y]==r) to for(y=0;y<x;)if(l[x]+l[y++]==r). – TheLethalCoder – 2017-05-16T16:12:28.490

0

AWK, 77 bytes

{for(s=i=0;++i<NF;)for(j=0;++j<NF;){if(i==j)continue
if($i+$j==$NF)s=1}$0=s}1

Try it online!

I could save 2 bytes by removing the i= in the for(s=i=0...), but then it would only work for one line of data. Since this isn't the shortest answer, I thought I'd make a general solution :)

Input is whitespace separated numbers with the last value being the desired sum.

Robert Benson

Posted 2017-05-16T11:58:47.293

Reputation: 1 339

0

Jellyfish, 13 bytes

p
cd!i
i 2
 1

Try it online!

How it works

print(exists(i,from_base(1,permutations(i,2)))

where i are the inputs.

Leaky Nun

Posted 2017-05-16T11:58:47.293

Reputation: 45 011