Advertisement
Guest User

Untitled

a guest
Jul 29th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. # I have a problem at work that I _think_ is the Knapsack Problem but perhaps
  2. # someone here can help me research/find a heuristic solution: we have access
  3. # to the <redacted> and get a finite number of “rules” we can use (e.g. 1000)
  4. # and each rule can only be 1024 characters long and have a maximum of 30
  5. # operators in them (e.g. “foo OR bar OR baz”), we have a list of domains
  6. # (e.g. example.com, example.org) we want to pack domains into rules as
  7. # efficiently as possible in the minimum number of rules.
  8.  
  9. # Here's an attempt at a Sentient program to solve the decision version of
  10. # this problem, i.e. Can 100 domains fit into 5 rules?
  11. # You could then ratchet the number of rules down by binary search to find
  12. # the minimum number of rules.
  13.  
  14. # Some constants of the problem.
  15. maxLength = 1024;
  16. maxOrs = 30;
  17. orLength = 4;
  18.  
  19. # An array containing the length of each domain.
  20. array100<int> domains;
  21.  
  22. # A 2D array containing whether each domain is a member of each rule.
  23. # The number of rules can be reduced to see if the problem can be satisfied with
  24. # fewer rules. The number of members should match the number of domains.
  25. array5<array10<bool>> ruleMembers;
  26.  
  27. # All domain lengths must be positive.
  28. domains.each(function (length) {
  29. invariant length.positive?;
  30. });
  31.  
  32. # Track how many domains have been allocated to rules.
  33. accountedFor = 0;
  34.  
  35. # Go through the members of each rule.
  36. ruleMembers.each(function^ (members, rule) {
  37. numberOfDomains = 0;
  38. lengthOfRule = 0;
  39.  
  40. # Go through all the domains.
  41. domains.each(function^ (length, index) {
  42. # Check whether the current domain is a member of the rule.
  43. isMember = members[index];
  44.  
  45. # If it is, increment the number of domains and add to the rule length.
  46. numberOfDomains += isMember ? 1 : 0;
  47. lengthOfRule += isMember ? length : 0;
  48. });
  49.  
  50. # Add the ' OR ' lengths to the rule length.
  51. numberOfOrs = numberOfDomains - 1;
  52. lengthOfRule += numberOfOrs * orLength;
  53.  
  54. # The rule should not exceed 1024 characters.
  55. invariant lengthOfRule <= maxLength;
  56.  
  57. # The rule should not contain more than 30 ORs.
  58. invariant numberOfOrs <= maxOrs;
  59.  
  60. # These domains are now accounted for.
  61. accountedFor += numberOfDomains;
  62. });
  63.  
  64. # All domains should now be accounted for.
  65. invariant accountedFor == domains.count;
  66.  
  67. # Allow the domains to be set at runtime.
  68. # Return the rule members as output.
  69. expose domains, ruleMembers;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement