27
\$\begingroup\$

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!

\$\endgroup\$
12
  • 1
    \$\begingroup\$ @marmeladze Just 2 numbers. \$\endgroup\$ Commented May 16, 2017 at 12:16
  • 8
    \$\begingroup\$ Nice first challenge! \$\endgroup\$ Commented May 16, 2017 at 12:34
  • 1
    \$\begingroup\$ Can we assume that the input least contains at least 2 elements? \$\endgroup\$ Commented May 16, 2017 at 14:09
  • 1
    \$\begingroup\$ Can we choose an empty output for falsey and 1 for truthy? \$\endgroup\$ Commented May 16, 2017 at 15:43
  • 4
    \$\begingroup\$ I think the other challenge should be closed as a duplicate of this one instead. I like this one better. \$\endgroup\$ Commented May 16, 2017 at 19:12

25 Answers 25

9
\$\begingroup\$

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 
\$\endgroup\$
1
  • 1
    \$\begingroup\$ @Fatalize For the love of God, I was having a dinner. \$\endgroup\$ Commented May 16, 2017 at 12:27
6
\$\begingroup\$

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!

4 bytes

Œc§i 

This does the same thing but with a newer language feature of vectorize-at-depth-1 sum. Thanks Dennis! :D Credit to @Riolku for noticing this.

\$\endgroup\$
4
  • \$\begingroup\$ You can use ċ instead of ⁹e to outgolf MATL. The rules don't specify that the values must be consistent, only truthy/falsey. \$\endgroup\$ Commented May 16, 2017 at 13:25
  • \$\begingroup\$ @EriktheOutgolfer Oh thanks :D Outgolfed MATL and 05AB1E :) \$\endgroup\$ Commented May 16, 2017 at 13:45
  • \$\begingroup\$ Umm, your TIO doesn't contain any code? ;) And you forgot to change the 6 to <s>6</s> 5 based on your edit? \$\endgroup\$ Commented May 16, 2017 at 13:56
  • \$\begingroup\$ @KevinCruijssen Ehhh lol thanks, I failed at copy-pasting. And yes I forgot that, thanks! :D \$\endgroup\$ Commented May 16, 2017 at 14:01
5
\$\begingroup\$

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!

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

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

Mathematica, 29 bytes

!FreeQ[Tr/@#~Subsets~{2},#2]& 
\$\endgroup\$
0
3
\$\begingroup\$

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 
\$\endgroup\$
2
  • \$\begingroup\$ 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 \$\endgroup\$ Commented May 16, 2017 at 14:20
  • \$\begingroup\$ @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 \$\endgroup\$ Commented May 16, 2017 at 16:20
3
\$\begingroup\$

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

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

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>

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Doesn't work for f([1,2,3,4,5,6])(3). Try using [...a].some instead? \$\endgroup\$ Commented May 16, 2017 at 14:53
  • \$\begingroup\$ Out of interest I tried porting Rod's Python answer, it also came out at 43 bytes. \$\endgroup\$ Commented May 16, 2017 at 14:58
  • \$\begingroup\$ @Neil, I was trying to figure out a shorter way, without using includes() but I couldn't see it. \$\endgroup\$ Commented May 16, 2017 at 15:20
2
\$\begingroup\$

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

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.

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

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

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

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 !

\$\endgroup\$
6
  • \$\begingroup\$ You forget the <? and if the terminate in true cases should be printable the shortest status i Know is !0 \$\endgroup\$ Commented May 16, 2017 at 13:36
  • \$\begingroup\$ @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. \$\endgroup\$ Commented May 16, 2017 at 13:45
  • \$\begingroup\$ Can you explain me how you will get the exit code when it not is printed with using the $_GET array as input? sandbox.onlinephpfunctions.com/code/… \$\endgroup\$ Commented May 16, 2017 at 13:59
  • \$\begingroup\$ @JörgHülsermann Using CGI \$\endgroup\$ Commented May 16, 2017 at 14:07
  • 1
    \$\begingroup\$ You can save a few bytes with variable variables instead of $q: $$c and ${$_GET[1]-$c}. \$\endgroup\$ Commented May 17, 2017 at 6:06
1
\$\begingroup\$

Mathematica, 38 bytes

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

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

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

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.

\$\endgroup\$
1
  • \$\begingroup\$ This doesn't work for test case [], -43. Try it online \$\endgroup\$ Commented May 16, 2017 at 19:48
1
\$\begingroup\$

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!

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

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

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.

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

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.

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

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;}; 
\$\endgroup\$
0
\$\begingroup\$

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.

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

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.

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

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

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
\$\endgroup\$
6
  • \$\begingroup\$ (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. \$\endgroup\$ Commented May 16, 2017 at 15:06
  • \$\begingroup\$ 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 :) \$\endgroup\$ Commented May 16, 2017 at 15:15
  • \$\begingroup\$ 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. \$\endgroup\$ Commented May 16, 2017 at 15:40
  • \$\begingroup\$ 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. \$\endgroup\$ Commented May 16, 2017 at 15:41
  • 1
    \$\begingroup\$ 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). \$\endgroup\$ Commented May 16, 2017 at 16:12

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.