Here's a freebie!

This problem was asked by Google.

Given a list of integers S and a target number k, write a function that returns a subset of S that adds up to k. If such a subset cannot be made, then return null.

Integers can appear more than once in the list. You may assume all numbers in the list are positive.

For example, given S = [12, 1, 61, 5, 9, 2] and k = 24, return [12, 9, 2, 1] since it sums up to 24.

Follow

@Absinthe
A few more test cases, for anyone else attempting this later (input list, target number, answer subset):
testdata = [([1, 1, 1, 1], 4, [1, 1, 1, 1]),
([2], 3, nothing),
(1:10, -10, nothing) ’t say target also has to be positive
([2], 2, [2]),
([12, 1, 61, 5, 9, 2], 24, [1, 2, 9, 12]),
([12, 6, 25, 7], 25, [6, 7, 12]),
(1:100, 143, [1, 2, 3, 4, 5, 6, 7, 8, 9, 98]),
]

(The last two have multiple valid solutions.)

@digital_carver I haven’t really been putting up any new ones, because I really wasn’t getting much feedback that anyone was really doing the old ones.

Actually haven’t been in the Fediverse much lately, spending most of my time in FB groups for turning. Gotta love the lathe!

But it is time for me to start ramping up in Java for work, so I may be back again.

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.