Re: Using a list as a variable

• To: mathgroup at smc.vnet.net
• Subject: [mg67087] Re: [mg67069] Using a list as a variable
• From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
• Date: Fri, 9 Jun 2006 01:07:22 -0400 (EDT)
• References: <200606080854.EAA12414@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```On 8 Jun 2006, at 17:54, Bonny Banerjee wrote:

> I would like to use a list (or set) as a variable. I am working on the
> Subset-Sum problem. Given a set S of integers, the goal is to find
> a subset
> of S (say Q) whose elements add to a given integer x. This is how I
> would
> like to define the function:
>
> SubsetSum(S, x) := {Q such that Q is a subset of S and sum of the
> elements
> of Q is x}
>
> In Mathematica functional programming language, this would look like:
>
> SubsetSum[S_, x_] := Reduce[Q \[Element] Subsets[S] && Sum[Q,
> {i,1,Length[Q]}]==x, Q, Reals]
>
> Now when I try to evaluate SubsetSum[{1, 3, 5, 2, 7, 100, 6}, 101],
> the
> output is as follows:
>
> Reduce : : naqs :
>         \[Exists]{Q} Q is not a quantified system of equations and
> inequalities. More ...
>
> Out[365]= Reduce[Q, False, Q, Reals]
>
>
> I guess, Mathematica is not being able to understand from my
> statement that
> the variable Q is not an atom but a list. But it should since I
> stated that
> Q is an element of the power set of S.
>
> Note that I know how to write a function for Subset-Sum using a
> Module. But
> I am interested in functional programming, similar to the format shown
> above.
>
> Any help would be appreciated.
>
> Thanks much,
> Bonny.
>
>

Reduce solves (or "reduces" ) algebraic and some transcendental (e.g.
trygonometric)  equations and inequalities. Your problem is not of
this kind.

One way to solve it:

SubsetSum[S_, x_] := Select[Subsets[S], Total[#] == x &]

SubsetSum[{1, 3, 5, 2, 7, 100, 6}, 101]

{{1, 100}}

SubsetSum[{1, 3, 5, 2, 7, 100, 6}, 105]

{{5, 100}, {3, 2, 100}}

Andrzej Kozlowski
Tokyo, Japan

```

• Prev by Date: Using Mathlink to export arrays
• Next by Date: Re: Mathematics Packages
• Previous by thread: Using a list as a variable
• Next by thread: Re: Using a list as a variable