4 ms·
In scripting languages it is a truism that anything you would want to do with a linked list is probably better done with an array. And given the overhead of wo
by btilly 4y ago
In scripting languages it is a truism that anything you would want to do with a linked list is probably better done with an array. And given the overhead of working in the language versus things implemented in C, this is generally true.
However I have a fun use for linked lists where this is NOT true.
Anyone who has played around with algorithms has encountered dynamic programming. So you can, for example, find the count of subsets that sum to a particular number without actually enumerating them all. But what if instead of counting them, you wanted to actually find some?
The answer turns out to be that instead of using dynamic programming to get a count, you use dynamic programming to build up a data structure from which you can get the answer. And the right data structure to use turns out to be...a type of linked list! There is no faster array equivalent for what you get.
In other words, with a few extra fields for clarity, here is the basic structure for subset sum of positive integers:
{
current_sum: ...,
count_of_solutions: ...,
current_value: ...,
solutions_using_current_value: (link in one dim of linked list),
solutions_using_previous_values: (link on other dim of linked list),
}
I leave figuring out the dynamic programming code to generate this as a fun exercise. Likewise how to extract, say, the 500'th subset with this sum. Both are easy if you understand linked lists. If not...well...consider it education!
- wwweston 4y agoSuspicion: this is because a positive integer is a linked list. Every integer is defined by a unary root element and then a series of successors until its cardinality matches the corresponding symbol (counting is correspondence). > find the count of subsets that sum to a particular number without actually enumerating them all. Would the generating formula for partition numbers[0] work, or am I misunderstanding this problem? (I think actually generating the subsets is necessarily a dynamic programming problem...) [0] https://en.wikipedia.org/wiki/Partition_(number_theory)#:~:text=the%20generating%20function%20formula%20described%20below%3A https://en.wikipedia.org/wiki/Partition_(number_theory)#:~:t...
- btilly 4y agoYou are misunderstanding the problem. Given a particular set, the question is enumerating the subsets that add to a particular thing. The fact that numbers themselves could be represented as a linked list has nothing to do with it. And there is no particularly useful generating function to use either. For example there are 303 primes less than 2000, and 47,839,398,752,301 subsets of them add up to 2000. If you arrange them in lexicographic order, what is the 5 trillionth one?