# Does the sum of 2 numbers in the list equal the desired sum? [duplicate]

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.

• 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                 Falsey
[],-43                Falsey


This is , so the shortest code in bytes wins!

• @marmeladze Just 2 numbers. – maple_shaft May 16 '17 at 12:16
• Nice first challenge! – HyperNeutrino May 16 '17 at 12:34
• Can we assume that the input least contains at least 2 elements? – Arnauld May 16 '17 at 14:09
• Can we choose an empty output for falsey and 1 for truthy? – Mr. Xcoder May 16 '17 at 15:43
• I think the other challenge should be closed as a duplicate of this one instead. I like this one better. – mbomb007 May 16 '17 at 19:12

# 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

• @Fatalize For the love of God, I was having a dinner. – Leaky Nun May 16 '17 at 12:27

# Jelly, 76 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!

• 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 May 16 '17 at 13:25
• @EriktheOutgolfer Oh thanks :D Outgolfed MATL and 05AB1E :) – HyperNeutrino May 16 '17 at 13:45
• 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 May 16 '17 at 13:56
• @KevinCruijssen Ehhh lol thanks, I failed at copy-pasting. And yes I forgot that, thanks! :D – HyperNeutrino May 16 '17 at 14:01

# 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


# Mathematica, 29 bytes

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


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

• Why do you need [:]? – Erik the Outgolfer May 16 '17 at 13:51
• @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 May 16 '17 at 13:55
• Oh so that's how you make a copy of a list. What code-golf teaches you... – Erik the Outgolfer May 16 '17 at 13:57
• Better TIO test suite. Also, can you use 1*a instead of a[:]? – mbomb007 May 16 '17 at 14:26
• @mbomb007 yep, now it has a perfect score :3 – Rod May 16 '17 at 14:31

# Haskell, 39 37 36 bytes

(a:t)#n=nelemmap(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

• 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 May 16 '17 at 14:20
• @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 May 16 '17 at 16:20

# 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


# 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


# 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) = ${f()(3)} f([])(-43) =${f([])(-43)}

## Mathematica, 38 bytes

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


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

• # is short for #1, and infix notations can shave a byte: MemberQ[Total/@#~Permutations~{2},#2]& – JungHwan Min May 16 '17 at 13:29
• @JungHwan thanks. I'm new to this. Where is your answer? – J42161217 May 16 '17 at 13:34

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

• This doesn't work for test case [], -43. Try it online – mbomb007 May 16 '17 at 19:48

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

# 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


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

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

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


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

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

# 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


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


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

}
}
}


### Releases

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

### Notes

• None
• (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 May 16 '17 at 15:06
• 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 May 16 '17 at 15:15
• 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 May 16 '17 at 15:40
• 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 May 16 '17 at 15:41
• No 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 May 16 '17 at 16:12