-9

If N=405, how do I generate all of it's subsets and then find the product of each subset's numbers? Like in this case, the set would be {0,4,5,40,05,45,405} and their products would result in a set {0,4,5,0,0,20,0}?

EDIT: It's a multi-set of non-empty sub-sequences.

Aulene De
  • 21
  • 5
  • 3
    First and foremost, what have you tried? How are you coming up with the subsets? Why doesn't it have `{40}`? – abhishek_naik Jun 06 '16 at 10:11
  • Eh, could you elaborate a bit more? Why the final set contains `20 == 04 * 05` but doesn't have, say, `180 == 04 * 45`? – Dmitry Bychenko Jun 06 '16 at 10:12
  • 1
    Do we work with *set* or *multiset*? E.g. in case of *multiset* `122 -> {1, 2, 2, 12, 22, 122} -> {..., 4 == 2 * 2, ...}` while in case of set `122 -> {1, 2, 12, 22, 122}` there's no `4` in the answer – Dmitry Bychenko Jun 06 '16 at 10:14

2 Answers2

1

Check this site it will give you the logic for getting the power set of a given set. once you get the power set elements multiply each element within a set to get the product as you require.

Bestin John
  • 1,765
  • 1
  • 20
  • 23
0

Well, there is a very easy and naive recursive solution to retrieving all subsets.

You take away one element from your set, then find all subsets for this new, smaller set. Then you copy the result and add the element you previously removed to the copy. Add the results together and you're done. For example:

{1,2,3}

Take out 1 and find all subsets of {2,3} giving you:
{{}, {2}, {3}, {2,3}}

Now copy this to give you
A = {{}, {2}, {3}, {2,3}}
B = {{}, {2}, {3}, {2,3}}

Now add 1 to each set in A, giving you
{{1}, {1,2}, {1,3}, {1,2,3}}

combine it with B
{{1}, {1,2}, {1,3}, {1,2,3}, {}, {2}, {3}, {2,3}}

Here's some code:

function subsets(aSet) {
    if (aSet.isEmpty()) {
        return [theEmptySet]
    }

    let lastElement = aSet.getLast()
    let aSmallerSet = aSet.removeLast()

    let subsetsOfSmallerSet = subsets(aSmallerSet)
    let subsetsContainingLastElement = subsetsOfSmallerSet.map(set => set.insert(lastElement))

    return subsetsOfSmallerSet.concat(subsetsContainingLastElement)
}

I am assuming you mean to get all subsets of the digits of a given number. So, assuming you have split the digits and parsed them back into numbers, then you can just use reduce to get the product.

let digits = //... an array such as [4,0,5]
let subsetsOfDigits = subsets(digits)
subsetsOfDigits.map(subset => subset.reduce((a,b) => a * b))

Ahh, but here you have a problem with the empty set, because you are not passing an initial value to reduce. However, it seems that you've ignored the empty set in your example, so you could just filter it out, and then, this code works.

Alex Watt
  • 34
  • 3