Is it a sum-free set?

32

4

A set is sum-free if no two (not necessarily distinct) elements when added together are part of the set itself.

For example, {1, 5, 7} is sum-free, because all members are odd, and two odd numbers when added together are always even. On the other hand, {2, 4, 9, 13} is not sum-free, as either 2 + 2 = 4 or 4 + 9 = 13 add together to a member of the set.

Write a program or function that takes a set as input, and outputs a Truthy value if the set is sum-free, and Falsy otherwise.

Examples:

Sum-free:
{}
{4}
{1, 5, 7}
{16, 1, 4, 9}

Not sum-free:
{0}
{1, 4, 5, 7}
{3, 0}
{16, 1, 4, 8}

orlp

Posted 2016-07-07T01:00:35.973

Reputation: 37 067

Can the set be an array/list? – Conor O'Brien – 2016-07-07T01:05:03.233

@CᴏɴᴏʀO'Bʀɪᴇɴ Sure. – orlp – 2016-07-07T01:17:24.080

Related and related. – FryAmTheEggman – 2016-07-07T01:32:04.917

@FryAmTheEggman Except for {0}... – feersum – 2016-07-07T01:47:05.623

@FryAmTheEggman No clarification is necessary, you can logically derive that the empty set is sum free (no two elements when added together are part of the set itself, in fact, nothing is part of the set), and that any set containing one element is sum-free, except for {0}, as 0+0 is in the set. – orlp – 2016-07-07T01:51:33.550

5Some more test cases might be nice! – Lynn – 2016-07-07T01:52:53.230

4Badly needs test cases. Are sets purely unique? – cat – 2016-07-07T02:33:55.710

I'd be interested in your motivation for this concept. There's a related concept that you may or may not find more useful; let X denote a closure system. Call a subset A of X minimalistic iff for all proper subsets B of X, we have that cl(B) is a proper subset of cl(A). In other words, A is minimalistic iff it is minimal among those sets that generate its closure. Now make the set of natural numbers into a closure system as follows: if A is a subset of Nat, then cl(A) is the intersection of all subsets of Nat that include A and are closed under addition and 0. Question: is a subset – goblin – 2016-07-07T05:16:38.757

... of Nat is minimalistic with respect to this closure operator? Its clear that minimalistic implies sum-free. On the other hand {2,6} is an example of a sum-free set that isn't minimalistic. Here's the wikipedia link about closure systems.

– goblin – 2016-07-07T05:18:21.640

is [0,1] sum free, not sum free, or undefined? (I.e.: what about repeats?) – Titus – 2016-07-07T07:50:36.607

@Titus 0+1 = 1, which is in the set, so, not sum free – Lulhum – 2016-07-07T07:59:55.880

@Lulhum That only applies if repeats are allowed. And that was my actual question. update: I just saw that orlp already has answered my question to FryAmTheEggman. – Titus – 2016-07-07T08:31:22.000

Can we assume the input is sorted? – Martin Ender – 2016-07-07T08:39:02.377

@MartinEnder No. Sets are unordered without duplicates. You may take an array, tuple, etc, but not assume that it is sorted. – orlp – 2016-07-07T13:57:00.887

@orlp can you please update the question with some (lots) more test cases and clear spec and explanations about empty, length-1 and the { 0 1 } sets? – cat – 2016-07-07T18:02:48.390

@cat The spec is clear. Examples I can add. – orlp – 2016-07-07T18:22:01.113

2+2=4 cannot be a valid addition in the set {2,4,9,13} as it has utilised two 2s. Or are duplicates allowed. And in that case {0} is sum free surely? – george – 2016-07-08T18:16:39.787

@george Adding the same element to itself is allowed. And {0} is not sum-free precisely for that reason: 0 + 0 = 0. – orlp – 2016-07-08T18:43:15.380

3I think you should clarify that you mean the sum of two not necessarily distinct elements from the set. – Gregory Nisbet – 2016-07-09T00:32:21.417

Is this a NP-complete problem? – palsch – 2016-07-10T10:19:24.047

@palsch No, it's a O(n^2) simple loop. – orlp – 2016-07-10T19:30:17.300

Answers

14

Pyth - 8 5 bytes

Thanks to @FryAmTheEggman for saving me 3 bytes.

!@sM*

Test Suite.

!             Logical not. This makes the empty intersection true and vice versa.
 @    Q       Setwise intersection with input (implictly).
  sM          Map sum to all the pairs.
   *QQ        Get all pairs by doing cartesian product with input*input (implicit).

Maltysen

Posted 2016-07-07T01:00:35.973

Reputation: 25 023

@FryAmTheEggman smart.... – Maltysen – 2016-07-07T01:55:28.580

I just got the same answer, but then realized *QQ actually produces [1,1], which are two same elements, and should not appear in the map. – busukxuan – 2016-07-07T02:41:52.537

@busukxuan the question actually asks you to consider duplicates: 2 + 2 = 4 from OP. My answer before FryAmTheEggman's golf actually used .Combinations with replacement because of this. – Maltysen – 2016-07-07T02:49:05.887

@Maltysen Oh nice! – busukxuan – 2016-07-07T03:09:01.470

40

Python 2, 41 bytes

lambda s:s==s-{a+b for a in s for b in s}

s should be a Python set.

Fun fact: sum-free is an anagram of my name.

feersum

Posted 2016-07-07T01:00:35.973

Reputation: 29 566

lambda s:not{a+b for a in s for b in s}&s is the same length. I can't find a way to shorten the negation, sadly. – FryAmTheEggman – 2016-07-07T01:41:11.317

16Upvoted for anagram. – Neil – 2016-07-07T07:56:20.457

@feersum this is your question. – Filip Haglund – 2016-07-07T17:21:47.487

@FilipHaglund No, it's orlp's. – mbomb007 – 2016-07-14T21:48:46.313

@mbomb007 If serious, yes. But, that can have a non-serious meaning: This is your question/You OWND the question/You beat everyone else here (Python). They didn't say "You are the OP." – Erik the Outgolfer – 2016-07-15T08:57:51.137

26

Jelly, 5 bytes

ṗ3ḅ-P

Try it online!

How it works

ṗ3ḅ-P  Main link. Argument: A (array)

ṗ3     Take the third Cartesian power of A, i.e., generate all triplets that
       consist of elements of A.
  ḅ-   Convert each triplet from base -1 to integer.
       This maps [a, b, c] to a - b + c = (a + c) - b.
       If (a + c) belong to A, this will yield 0 for some b.
    P  Take the product of all resulting integers. 

Dennis

Posted 2016-07-07T01:00:35.973

Reputation: 196 637

13

JavaScript, 86 42 41 bytes

n=>!n.some(m=>n.some(o=>n.includes(m+o)))

Thanks Cᴏɴᴏʀ O'Bʀɪᴇɴ for saving me a ton of bytes off parentheses/curly brackets. Also thanks Neil for pointing out that the function was returning the opposite boolean value than it should have.

I tried to cut down on bytes by redefining n.some but that doesn't work because it's a prototype function unfortunately. There might be a better solution with Array.prototype.map in JS but the some function is really fun.

I'm now wondering if there's a shorter way than .includes using something such as .indexOf and adding 1 (which would give it a truthy value if it contains the number).


Testing:

> (n=>!n.some(m=>n.some(o=>n.includes(m+o))))([1,5,7]);
true
> (n=>!n.some(m=>n.some(o=>n.includes(m+o))))([1,5,7,12]);
false

charredgrass

Posted 2016-07-07T01:00:35.973

Reputation: 935

1Try n=>n.some(m=>n.some(o=>n.some(p=>m+o==p))) – Conor O'Brien – 2016-07-07T03:02:09.603

@CᴏɴᴏʀO'Bʀɪᴇɴ Thanks! I had no idea I could omit the parentheses and braces. – charredgrass – 2016-07-07T03:04:53.717

1No problem! it works because of the behaviour of the anonymous functions. Look at other ES6 answers around here, you'll learn quite a lot :) – Conor O'Brien – 2016-07-07T03:05:48.683

1Hello, and welcome to PPCG! – NoOneIsHere – 2016-07-07T03:09:54.087

I dont know if it'll work but try: n=>(s=n.some)(m=>s(o=>s(p=>m+o==p))) – Downgoat – 2016-07-07T07:31:55.290

@Downgoat unfortunately, no - the .some function has to be on the Array. I tried this and got a TypeError: Array.prototype.some called on null or undefined. – charredgrass – 2016-07-07T07:41:32.307

1The sense of this is wrong, it tells you if the set is not sum-free. Also, use n.contains(o+p) which saves you 2 bytes over the innermost some. – Neil – 2016-07-07T07:59:09.800

@Neil No idea how I missed the fact that it does the opposite, thanks for the correction. And there's no contains function in JS but there is includes which is the same and I assume is what you meant. – charredgrass – 2016-07-07T08:07:24.817

1Sorry, yes, I meant includes (it was originally going to be called contains but some library has a conflicting definition). – Neil – 2016-07-07T08:27:34.593

Using ~n.indexOf(o+p) is equivalent to n.includes(o+p) but may lead to byte shaving in the future – MayorMonty – 2016-07-13T01:52:12.353

12

MATL, 5 bytes

t&+m~

This outputs an array which is truthy if all entries are 1 and falsey otherwise. Here is a demo to show various truthy/falsey values in MATL.

Try it Online

Explanation

        % Implicitly grab input
t       % Duplicate
&+      % Compute sum of each element with every other element (2D Matrix)
m       % Check which members of the input are present in this matrix of sums
~       % Negate the result to yield a truthy value for sum-free sets
        % Implicitly display truthy/falsey value

Suever

Posted 2016-07-07T01:00:35.973

Reputation: 10 257

12

Mathematica, 23 Bytes

{}==#⋂Tr/@#~Tuples~2&

A Simmons

Posted 2016-07-07T01:00:35.973

Reputation: 4 005

I mistakenly edited your submission, but then rolled it back to the way it was. Sorry! – DavidC – 2016-07-07T12:27:13.527

By the way, nice insight that no element had to be removed from the list before making tuples. – DavidC – 2016-07-07T12:32:57.043

1Please replace with (U-22C2). The code right now isn't copypastable into Mathematica. – LLlAMnYP – 2016-07-07T13:47:45.973

@LLlAMnYP Thanks, I had to manually find the unicode character since Mathematica automatically formats expressions when you copy them; I must have found the wrong one. – A Simmons – 2016-07-07T14:35:34.250

1@ASimmons If you highlight the character in Mathematica and hit F1 it will show you the help page for that specific character which always contains the character's Unicode code point (in hexadecimal). It's really annoying though that you can't just copy it as Unicode. I think there's a solution for "copy as Unicode" somewhere on Mathematica.SE but IIRC it was far from trivial. – Martin Ender – 2016-07-07T14:59:12.090

@MartinEnder Thanks for the advice. I did find that once but it's too complicated for me to reconstruct every time and it's usually easier to find the unicode characters than that code... – A Simmons – 2016-07-07T15:34:01.290

@MartinEnder There's a greasemonkey script for Firefox and a plugin for Chrome that adds buttons to the answer form in Mathematica.SE which convert things like [Alpha] in the answer box to the unicode characters. I usually paste code from Mathematica, select it and click that button to get the right Unicode characters. – LLlAMnYP – 2016-07-07T15:40:51.037

@MartinEnder that tool is here.

– LLlAMnYP – 2016-07-07T15:42:12.467

@LLlAMnYP That looks really useful, thanks for the heads up! :) – Martin Ender – 2016-07-07T15:43:30.380

Martin, You can copy Mathematica code as MathML. Then paste it into your entry. Then copy the desired character(s) from the display below and paste it into your entry. Finally, remove the MathML code. – DavidC – 2016-07-07T21:39:49.737

@DavidC the poster's comments under the specification imply that any set containing zero is not sum-free; he mentions specifically the set {0} and I believe the program above behaves as I'd expect given this interpretation! – A Simmons – 2016-07-07T22:34:50.193

you are correct! – DavidC – 2016-07-07T22:35:50.440

11

Haskell, 32, 30 bytes

Simple solution:

f x=and[a+b/=c|a<-x,b<-x,c<-x]

Two bytes saved by @Lynn

Michael Klein

Posted 2016-07-07T01:00:35.973

Reputation: 2 111

f x=and[a+b/=c|a<-x,b<-x,c<-x] for 30 bytes. – Lynn – 2016-07-07T14:52:22.570

7

Julia, 18 bytes

!x=x∩(x'.+x)==[]

Try it online!

Dennis

Posted 2016-07-07T01:00:35.973

Reputation: 196 637

6

J, 18 10 8 bytes

8 bytes saved thanks to miles, and 2 thanks to FrownyFrog!

-:]-.+/~

Matches the original list with the set difference of tabulated sums. This is equivalent to:

(-: (] -. +/~)) y

for input y. This translates to:

y -: (] -. +/~) y
y -: (y -. +/~ y)

+/~ returns a table of sums using y. For y =: 16 1 4 9, this gives:

   +/~ 16 1 4 9
32 17 20 25
17  2  5 10
20  5  8 13
25 10 13 18

Then, we use -., which produces a list consisting of all elements in y not in this table. If the list is sum-free, this will produce the same list. Then, -: checks for equality of lists, which produces the desired output.

Old, 18 bytes

[:-.[:>./^:_+/~e.]

+/~ creates a table of the values of the set added to itself, and e. checks if those members are in the original set. The rest of that is negating the maximal element.

Conor O'Brien

Posted 2016-07-07T01:00:35.973

Reputation: 36 228

-:]-.&,+/~ for 10 bytes using set difference -. and list matching -: – miles – 2016-07-07T02:18:08.643

Ooo, very nice! – Conor O'Brien – 2016-07-07T02:18:43.040

You don't need &, -. already works with cells of y. – FrownyFrog – 2018-05-24T11:14:18.080

@FrownyFrog Fascinating, TIL. Thanks! – Conor O'Brien – 2018-05-24T15:54:14.723

5

Retina, 45 44 bytes

\d+
<$&$*1>
$
$`$`
M`(<1*)>.*<(1*>).*\1\2
^0

Input is a decimal list of comma-separated numbers. Output is 0 (falsy) or 1 (truthy).

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

Stage 1: Substitution

\d+
<$&$*1>

This converts all elements of the input to unary and wraps them in <...>. The purpose of the angle brackets is to distinguish a list containing only 0 from an empty list (since the unary representation of 0 is empty itself).

Stage 2: Substitution

$
$`$`

We repeat the string 3 times by append it twice at the end.

Stage 3: Match

M`(<1*)>.*<(1*>).*\1\2

We now try to find three numbers in the result such that the first two add up to the third. Those matches are counted (this doesn't actually count all such tuples, because matches cannot overlap, but if such a tuple exists it will be found). Hence, we get 0 for sum-free sets and something positive otherwise.

Stage 4: Match

^0

Since the previous stage gave the opposite of what we want, we negate the result by counting the matches of ^0 which is 1 for input 0 and 0 for everything else.

Martin Ender

Posted 2016-07-07T01:00:35.973

Reputation: 184 808

5

Clojure, 47 37 bytes

#(=(for[a % b % :when(%(+ a b))]a)[])

quite plain solution. uses list comprehension to find all elements which sum is equal to another element.

38 bytes variant:

#(every? nil?(for[a % b %](%(+ a b))))

cliffroot

Posted 2016-07-07T01:00:35.973

Reputation: 1 080

1Since in the challenge you are taking a set as your input, you can simply use the set to check for membership as in #(=(for[a % b % :when(%(+ a b))]a)[]) which can save 10 bytes – miles – 2016-07-07T13:24:29.380

@miles oh wow, thanks, i did kinda ignore that fact and worked with lists. – cliffroot – 2016-07-07T13:32:14.743

5

Octave, 29 21 25 bytes

@(s)~[ismember(s,s+s') 0]

Thanks to Suever! It returns an array. I added 0 at the end to make [] become sum-free. To verify truthy and falsey in Octave, you can do this:

> f=@(s)~[ismember(s,s+s') 0]

> if f([]) "sum-free" else "not sum-free" end
ans = sum-free

> if f([0]) "sum-free" else "not sum-free" end
ans = not sum-free

> if f([4]) "sum-free" else "not sum-free" end
ans = sum-free

> if f([1 3]) "sum-free" else "not sum-free" end
ans = sum-free

> if f([2 4]) "sum-free" else "not sum-free" end
ans = not sum-free

An alternative that returns 0 or 1 is:

@(s)~numel(intersect(s+s',s))

Marco

Posted 2016-07-07T01:00:35.973

Reputation: 581

You could change it to be @(s)~ismember(s+s',s) since arrays can be truthy/falsey – Suever – 2016-07-07T12:32:52.030

4

Mathematica 63 62 42 bytes

This shorter version benefitted from A Simmons' submission. No element needs to be removed from the list before IntegerPartitions is applied.

If an element cannot be partitioned into two integers (each from the list), then IntegerPartitions[#,{2},#]=={} holds. And checks whether this holds for every element in the list. If so, the list is sum-free.

And@@(IntegerPartitions[#,{2},#]=={}&/@#)&

Examples

 And@@(IntegerPartitions[#,{2},#]=={}&/@ #)&@{2, 4, 9, 13}

False


 And@@(IntegerPartitions[#,{2},#]=={}&/@ #)&@{1, 5, 7}

True


There is a 2, but no odd numbers that differ by 2.

 And@@(IntegerPartitions[#,{2},#]=={}&/@#)&@{2, 3, 7, 11, 17, 23, 29, 37, 41, 47, 53, 59, 67, 71}

True

DavidC

Posted 2016-07-07T01:00:35.973

Reputation: 24 524

Do you have a defined somewhere else in your workbook? These expressions don't give the desired output when I evaluate them. – A Simmons – 2016-07-07T14:38:42.650

Thanks. That a should have been a #. I corrected it and removed a superfluous @. – DavidC – 2016-07-07T21:35:57.787

4

Perl 6,  24 21 20  19 bytes

{not any (@_ X+@_)X==@_}
{so all (@_ X+@_)X!==@_}
{not @_ (&)(@_ X+@_)}
{not @_∩(@_ X+@_)}

{!(@_∩(@_ X+@_))}

Input is any Positional value like a List.
( a Set is an Associative so you would have to call .keys on it. )

Test:

#! /usr/bin/env perl6
use v6.c;
use Test;

my @sum-free = (
  (),
  (4,),
  (1, 5, 7),
  (16, 1, 4, 9),
);

my @not-sum-free = (
  (0,),
  (1, 4, 5, 7),
  (3, 0),
  (16, 1, 4, 8),
);

my @tests = ( |(@sum-free X=> True), |(@not-sum-free X=> False) );

plan +@tests;

# store the lambda in lexical namespace for clarity
my &sum-free-set = {!(@_∩(@_ X+@_))}

for @tests -> $_ ( :key(@list), :value($expected) ) {
  is sum-free-set(@list), $expected, .gist
}
1..8
ok 1 - () => True
ok 2 - (4) => True
ok 3 - (1 5 7) => True
ok 4 - (16 1 4 9) => True
ok 5 - (0) => False
ok 6 - (1 4 5 7) => False
ok 7 - (3 0) => False
ok 8 - (16 1 4 8) => False

Brad Gilbert b2gills

Posted 2016-07-07T01:00:35.973

Reputation: 12 713

3

Ruby, 36 bytes

Constructs a cartesian product of the set against itself and finds the sum of all elements, then checks for intersection with the original set. Input is arrays, but in Ruby they have enough set operations to make it work out nicely anyways.

-1 byte over my original solution (used & instead of - and compared with []) because of inspiration from @feersum

Try it here!

->s{s-s.product(s).map{|x,y|x+y}==s}

Value Ink

Posted 2016-07-07T01:00:35.973

Reputation: 10 608

3

Racket, 58 bytes

(λ(l)(andmap(λ(m)(andmap(λ(n)(not(memq(+ n m)l)))l))l))

Explanation:

(λ(l)(andmap(λ(m)(andmap(λ(n)(not(memq(+ n m)l)))l))l))
(λ(l)                                                 ) # Define a lambda function that takes in one parameter
     (andmap(λ(m)                                  )l)  # If for all m in l
                 (andmap(λ(n)                   )l)     # If for all n in l
                             (not(memq(+ n m)l))        # n + m is not in l

Steven H.

Posted 2016-07-07T01:00:35.973

Reputation: 2 841

3

R, 39 36 bytes

w<-function(s)!any(outer(s,s,'+')%in%s)

Call as w(s), where s is the set (actually vector) of values. Here is the output for some test cases:

> w(numeric(0)) # The empty set
[1] TRUE
> w(0)
[1] FALSE
> w(1)
[1] TRUE
> w(c(1, 5, 7))
[1] TRUE
> w(c(2, 4, 9, 13))
[1] FALSE

Where c() is the concatenation function that takes a bunch of values and makes it a vector.

EDIT: Making it an anonymous function to save 3 bytes, thanks to @MickyT.

function(s)!any(outer(s,s,'+')%in%s)

ConMan

Posted 2016-07-07T01:00:35.973

Reputation: 203

Very nice. You can post these as an unnamed function if you like. That would save you 3 bytes. eg function(s)!any(outer(s,s,'+')%in%s) – MickyT – 2016-07-07T10:29:13.600

3

05AB1E, 9 5 bytes

Saved 4 bytes thanks to Magic Octopus Urn

ãOå_P

Try it online!

Explanation

ã       # cartesian product
 O      # sum
  å     # check each if it exists in input
   _    # logical negation
    P   # product

Emigna

Posted 2016-07-07T01:00:35.973

Reputation: 50 798

Is 0 really truthy in 05AB1E? – Dennis – 2016-07-07T15:53:30.590

@Dennis I defined 0 as truthy for this challenge and anything else as falsy. Isn't that normally OK as long as it is unambiguous and OP hasn't specified a specific format? – Emigna – 2016-07-07T15:54:49.377

This is our default interpretation of truthy/falsy. – Dennis – 2016-07-07T16:05:56.523

@Dennis: Ah, too bad. sum-free = 0 and non-sum-free = "a sum" fitted nicely to the challenge imo. Seen a lot of other challenges which defined sums and similar non-standard values as true/false so I figured un-ambiguity was the default. I'll edit the answer then. Thanks for the heads up. – Emigna – 2016-07-07T16:09:33.307

Try it online! is 5 bytes ãOåZ_ unless (as per usual) I missed something. I don't think you need the loop or the 2 (2 is default on lists). ãv¹yOåO_ for 1 byte less is definitely fine if the 5 byte is somehow wrong. – Magic Octopus Urn – 2018-05-24T16:36:22.980

1@MagicOctopusUrn: Thanks! Unsure if these commands worked this way back then, but they do now so thanks :) (I could just have missed it as well, I was pretty new to 05AB1E when I did this challenge) – Emigna – 2018-05-24T19:37:15.797

Oh, didn't realize how old this is. Whoops! – Magic Octopus Urn – 2018-05-24T21:10:17.343

3

Brachylog, 13 bytes

'(p:?+L:?x'L)

Explanation

'(          )  True if what's in the parentheses is impossible, false otherwise
  p            Get a permutation of Input
   :?+L        L is the list of element-wise sums of the permutation with Input
       :?x'L   There is at least one element of Input in L

Fatalize

Posted 2016-07-07T01:00:35.973

Reputation: 32 976

Is [2:2] a subset of 2 elements of [2:4:9]? – Leaky Nun – 2016-07-07T09:52:03.923

@LeakyNun No, because 2 only appears once in [2:4:9]. – Fatalize – 2016-07-07T10:00:02.677

3

Python, 40 bytes

lambda s:s^{a+b for a in s for b in s}>s

^ = symmetric difference, new set with elements in either sets but not both

> True if the left set is a superset of the right set.

Lulhum

Posted 2016-07-07T01:00:35.973

Reputation: 381

This doesn't work for the empty set, though I don't know if that's required. – xnor – 2016-07-07T08:19:23.667

1

Well, wikipedia says (among other things) that A is sum-free if the equation a + b = c has no solution with a, b, c ∈ A. With this definition, the empty set is not sum free, and my answer is correct. But I may be biased.

– Lulhum – 2016-07-07T08:34:26.427

3That definition implies that the empty set is sum-free, as there are no a, b and c in the empty set that satisfy the equation. The OP's newly added test cases support this. – Dennis – 2016-07-07T18:47:44.293

2

APL, 8 bytes

⊢≡⊢~∘.+⍨

Explanation:

⊢         argument
 ≡        equals
  ⊢       argument
   ~      without 
    ∘.+⍨  sums of its elements

Test:

      ( ⊢≡⊢~∘.+⍨ ) ¨ (1 5 7)(2 4 9 13)
1 0

marinus

Posted 2016-07-07T01:00:35.973

Reputation: 30 224

2

Haskell, 30 bytes

f s=and[x+y/=z|x<-s,y<-s,z<-s]

I think there exists a shorter solution that's more interesting, but I haven't found it.

These are 33 and 34 bytes:

f s=and$((/=)<$>s<*>)$(+)<$>s<*>s
f s|q<-((-)<$>s<*>)=all(/=0)$q$q$s

xnor

Posted 2016-07-07T01:00:35.973

Reputation: 115 687

does using elem on s and getting rid of the last part of the comprehsion work? – Maltysen – 2016-07-07T05:43:12.190

@Maltysen If you mean f s=and[notElem(x+y)s|x<-s,y<-s], that's 32. There's also f s=all(`notElem`s)$(+)<$>s<*>s for 31. – xnor – 2016-07-07T06:11:55.110

2

Actually, 7 bytes

;;∙♂Σ∩Y

Try it online!

;;∙♂Σ∩Y              Stack: [1,5,7]
;         duplicate         [1,5,7] [1,5,7]
 ;        duplicate         [1,5,7] [1,5,7] [1,5,7]
  ∙       cartesian product [1,5,7] [[1,1],[1,5],[1,7],[5,1],[5,5],[5,7],[7,1],[7,5],[7,7]]
   ♂Σ     sum each          [1,5,7] [2,6,8,6,10,12,8,12,14]
     ∩    intersect         []
      Y   negate            1

Leaky Nun

Posted 2016-07-07T01:00:35.973

Reputation: 45 011

Maybe make your code more gender-equal? () – Erik the Outgolfer – 2016-07-15T09:08:24.423

1

Clojure, 34 bytes

#(not-any? %(for[i % j %](+ i j)))

I wrote this before noticing the earlier Clojure solution. Anyway, this one is more compact as it uses the input set as a pred function for not-any?.

NikoNyrh

Posted 2016-07-07T01:00:35.973

Reputation: 2 361

1

Prolog (SWI), 66 56 49 bytes

A/B:-member(A,B).
-L:- \+ (E/L,F/L,G is E+F,G/L).

Try it online!

ASCII-only

Posted 2016-07-07T01:00:35.973

Reputation: 4 687

1

PHP, 73 bytes

+8 to turn the snippet into a program, -8 on obsolete variables thanks to insertusernamehere

<?foreach($argv as$p)foreach($argv as$q)if(in_array($p+$q,$argv))die;echo 1;

prints 1 for true, empty output for false
usage: php <filename> <value1> <value2> ...

qualified function for testing (94 86): returns 1 or nothing

function f($a){foreach($a as$p)foreach($a as$q)if(in_array($p+$q,$a))return;return 1;}

tests

function out($a){if(!is_array($a))return$a;$r=[];foreach($a as$v)$r[]=out($v);return'['.join(',',$r).']';}
function cmp($a,$b){if(is_numeric($a)&&is_numeric($b))return 1e-2<abs($a-$b);if(is_array($a)&&is_array($b)&&count($a)==count($b)){foreach($a as $v){$w = array_shift($b);if(cmp($v,$w))return true;}return false;}return strcmp($a,$b);}
function test($x,$e,$y){static $h='<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';echo"$h<tr><td>",out($x),'</td><td>',out($y),'</td><td>',out($e),'</td><td>',cmp($e,$y)?'N':'Y',"</td></tr>";$h='';}
$samples = [
    [], 1,
    [0], false,
    [1], 1,
    [0,1], false,
    [2, 4, 9, 13], false,
    [1,5,7], 1
];
while($samples)
{
    $a=array_shift($samples);
    $e=array_shift($samples);
    test($a,$e,f($a));
}

Titus

Posted 2016-07-07T01:00:35.973

Reputation: 13 814

1As you never use $i and $j you can discard $i=> as well as $j=> and save 8 bytes. Unfortunately code snippets are not valid answers. Make it a function or a full program and include that in your byte count and you're ready to go. :) – insertusernamehere – 2016-07-08T22:14:19.127

1

TSQL, 47 bytes

CREATE table T(a int)
INSERT T values(1),(5),(7),(12)

SELECT min(iif(a.a+b.a<>T.a,1,0))FROM T a,T b,T

Note: This will only run once, then the table needs to be deleted or dropped to run again. The fiddle editor doesn't allow creation of tables. Therefore the fiddle included in my answer uses 2 extra bytes to compensate for this - the fiddle version doesn't require cleanup.

Fiddle

t-clausen.dk

Posted 2016-07-07T01:00:35.973

Reputation: 2 874

1

Perl, 46 bytes

45 bytes code + 1 byte command line (-p)

$_="$_ $_ $_"!~/(\b\d++.*)((?1))(??{$1+$2})/

Uses a single regex match with Perl's support for 'code expressions' inside the regex to allow for evaluation within a match.

To get around the requirement that the input is unsorted, we repeat the input string three times. This guarantees that the result is after the two operands, and allows the same digit to be matched again (e.g. in the case of input 2 4).

Usage example:

echo "3 5 6 8" | perl -p entry.pl

Jarmex

Posted 2016-07-07T01:00:35.973

Reputation: 2 045

1

Factor, 47 bytes

[ dup dup 2array [ Σ ] product-map ∩ { } = ]
  • ∩ { } = is equivalent to but shorter than intersects?.
  • Σ is shorter than but equivalent to sum.

Thanks, math.unicode!

testing code:

USING: arrays kernel math.unicode sequences sequences.product ;
IN: sum-free

: sum-free? ( seq -- ? )
  dup dup 2array [ Σ ] product-map ∩ { } = ;

USING: tools.test sum-free ;
IN: sum-free.tests

{ t } [ { 5 7 9 } sum-free? ] unit-test
{ f } [ { 2 4 9 13 } sum-free? ] unit-test
{ t } [ { } sum-free? ] unit-test
{ f } [ { 0 } sum-free? ] unit-test
{ t } [ { 1 } sum-free? ] unit-test
{ f } [ { 0 1 } sum-free? ] unit-test

I'm only confident the first two are correct. It's unclear from the question what the rest should be, so I think it's fine for now.

cat

Posted 2016-07-07T01:00:35.973

Reputation: 4 989

1

Java, 67 bytes

s->!s.stream().anyMatch(p->s.stream().anyMatch(q->s.contains(p+q)))

Input is a Set<Integer>. Tests:

import java.util.Arrays;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

public class SumFree {
    public static void main(String[] args) {
        sumFree(s->!s.stream()
            .anyMatch(p->s.stream()
                .anyMatch(q->s.contains(p+q)))); // formatted to avoid wrapping
    }

    public static void sumFree(Function<Set<Integer>, Boolean> func) {
        test(func);
        test(func, 4);
        test(func, 1, 5, 7);
        test(func, 16, 1, 4, 9);
        test(func, 1, 4, 5, 7);
        test(func, 0);
        test(func, 3, 0);
        test(func, 16, 1, 4, 8);
    }

    public static void test(Function<Set<Integer>, Boolean> func, Integer... vals) {
        Set<Integer> set = Arrays.stream(vals).collect(Collectors.toSet());
        System.out.format("%b %s%n", func.apply(set), set);
    }
}

Output:

true []
true [4]
true [1, 5, 7]
true [16, 1, 4, 9]
false [0]
false [1, 4, 5, 7]
false [0, 3]
false [16, 1, 4, 8]

David Conrad

Posted 2016-07-07T01:00:35.973

Reputation: 1 037

0

05AB1E, 6 4 bytes

âOмQ

Try it online or verify all test cases.

Explanation:

â       # Take all pairs of the input-list
        #  i.e. [1,5,7] → [[1,1],[1,5],[1,7],[5,1],[5,5],[5,7],[7,1],[7,5],[7,7]]
        #  i.e. [1,4,5] → [[1,1],[1,4],[1,5],[4,1],[4,4],[4,5],[5,1],[5,4],[5,5]]
 O      # Sum all pairs
        #  i.e. [[1,1],[1,5],[1,7],[5,1],[5,5],[5,7],[7,1],[7,5],[7,7]]
        #    → [2,6,8,6,10,12,8,12,14]
        #  i.e. [[1,1],[1,4],[1,5],[4,1],[4,4],[4,5],[5,1],[5,4],[5,5]]
        #    → [2,5,6,5,8,9,6,9,10]
  м     # Remove all values in the input-list that are also in the list above
        #  i.e. [1,5,7] and [2,6,8,6,10,12,8,12,14] → ['1','5','7']
        #  i.e. [1,4,5] and [2,5,6,5,8,9,6,9,10] → ['1','4','']
   Q    # Is the current list still equal to the input-list?
        #  i.e. [1,5,7] and ['1','5','7'] → 1
        #  i.e. [1,4,5] and ['1','4',''] → 0

Kevin Cruijssen

Posted 2016-07-07T01:00:35.973

Reputation: 67 575

0

Japt -!, 9 bytes

ø¡UË+XÃÃc

Try it online!

Unpacked & How it works

UøUmX{UmD{D+X} } c

Uø  Does the input array have any common element with...
UmX{  the input array mapped with...
UmD{    the input array mapped with...
D+X       sum of the two elements
}
}
c     ... flattened

The result is the opposite of what is requested, so -! flag is used to flip true and false.

Bubbler

Posted 2016-07-07T01:00:35.973

Reputation: 16 616

0

Cjam, 10 bytes

__m*::+&!!

Not very golfed. If someone can help me shave off more bytes, please help!

Explanation:

__         Duplicate the list twice
  m*       Take the Cartesian Product of the two
    ::+    For every item in the list (which is a list in this case), sum the elements
       &   Take the intersection with the original list
        !! Logical-not twice; take the "truthness" of the value

Chromium

Posted 2016-07-07T01:00:35.973

Reputation: 201

0

PowerShell 50 bytes

param($a)$a|%{$b=$_;$a|%{if($b+$_-in$a){1;break}}}

Where 1 is true and no output is false.

Though, if outputting multiple truthy values is allowed, then I could save 6 bytes:

param($a)$a|%{$b=$_;$a|%{if($b+$_-in$a){1}}}

But I will wordsmith myself and agree that the OP asked for 'a Truthy value'

Explanation:

param($a)$a|%{$b=$_;$a|%{if($b+$_-in$a){1;break}}}
param($a)                                          # assigns first passed parameter to variable $a
         $a|${                                   } # foreach $_ in $a
              $b=$_;                               # assign $_ to $b for access from further down the pipe
                    $a|%{                       }  # foreach $_ in $a
                         if($b+$_-in$a){       }   # if $a contains the value $b+$_
                                        1;         # implicit output of 1 (true)
                                          break    # exit the loops

ThePoShWolf

Posted 2016-07-07T01:00:35.973

Reputation: 171