Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Only one from each set

Your input is a non-empty set of non-empty sets of positive integers. For example:

{{1}, {2, 3}, {2,4}, {1,4}}

Your task is to output the maximal number of elements that can be picked from the sets with the following conditions:

  • You can only pick at most 1 element from a set
  • You can't pick the same element from 2 different sets

In this example you can pick 1 from the first set, 3 from the second set, 2 from the third set and 4 from the last set, for a total of 4 elements.

Io is flexible. You can take a list, instead of sets, etc.

There are no gaps in the numbers (eg. {{2,3},{3,4}} is not a valid input). Or in other words, the input flattened must contain all numbers [1,n] where n is the largest number in the input.

This is , so shortest code wins.

Examples

{{1}}
-> 1
{{1}, {2, 3}, {2,4}, {1,4}}
-> 4
{{1}, {2}, {1,2,3,4}}
-> 3
{{1}, {2}, {2,3}}
-> 3
{{1, 2, 3}, {2, 4, 5, 6}, {3, 5, 6, 7}, {1, 2}, {2, 3}, {1, 3}}
-> 5
{{1,2,3,4,5}, {1,2}, {2,3}, {1,3}}
-> 4
{{1,2},{1,3},{1,4},{2,3},{2,4},{3,4},{1,2,3},{1,2,4},{1,3,4},{2,3,4},{5,6,7,8,9,10}}
-> 5
{{1,4}, {2,3}, {1,3}, {1,2,3}}
-> 4

Background

Recently @AnishSharma posted this question on Stack Overflow. This is a slightly modified version of that question

Answer*

Draft saved
Draft discarded
Cancel
7
  • 1
    \$\begingroup\$ TIL about lengths function. Thanks! \$\endgroup\$ Commented Jan 23, 2022 at 16:47
  • 1
    \$\begingroup\$ @pajonk - You're welcome. It's quite disconcerting when you accidentally learn something potentially useful while deliberately trying to write difficult-to-understand code, isn't it? This has often happened to me, too... \$\endgroup\$ Commented Jan 23, 2022 at 18:51
  • \$\begingroup\$ You're absolutely right... BTW, you "stole" the test setup from me, but not the table function (for -1) ;-) \$\endgroup\$ Commented Jan 23, 2022 at 19:51
  • \$\begingroup\$ @pajonk - Dang, you're right! But if I use table instead of unique, it'd be the same as you using lengths instead of sapply(,length)... we should flip a coin somehow do decide who gets to use the other's function... \$\endgroup\$ Commented Jan 23, 2022 at 22:19
  • 1
    \$\begingroup\$ "pajonk_guesses_heads" ends in letter st (by odd/even position). \$\endgroup\$ Commented Jan 24, 2022 at 7:33

AltStyle によって変換されたページ (->オリジナル) /