I need an efficient algorithm in Python for the following requirement.
Consider I am having N JavaScript functions in a file. I have to include any M JavaScript among N in any particular order. (For example, in one page I may include N1, N4, N5, N6 and another page N1, N5, N4, N3, but it should get included in the same order.)
What is an efficient way to do it?
This is known as the maximum coverage problem, and is NP-Hard (non-deterministic polynomial-time hard)… There do, however, exist some approximation algorithms, the easiest to implement would be a greedy based algorithm.
Say you need to include N_1 … N_m JavaScript files. You would want to order your JavaScript code based upon how many of these elements they contain, and recompute their weight at every iteration.
Simple example:
Say you want to include n_1…n_6. You would sort these JavaScript files such that the original ordering would be [JavaScript1, JavaScript2, JavaScript3] (in the order of how much coverage they provide). You would use JavaScript1 first, now you just need n4 and n6… If you resort the remaining JavaScript files based upon the ones that would provide the most coverage the new ordering would be [JavaScript3, JavaScript2]. Note that even though the second file contains more definitions, JavaScript3 is more useful as it will cover the remaining uncovered definitions.
You can write up the algorithm yourself though! 🙂