Skip to content

Commit

Permalink
Choose actions according to their weights
Browse files Browse the repository at this point in the history
  • Loading branch information
shakhat committed Feb 15, 2016
1 parent 9ab0802 commit 18e3158
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
3 changes: 1 addition & 2 deletions act/engine/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,7 @@ def produce_task(world, actions):
available_actions[action] = filtered_items

if available_actions:
# todo choose according to action's weight
chosen_action = random.choice(available_actions.keys())
chosen_action = utils.weighted_random_choice(available_actions.keys())
available_items = available_actions[chosen_action]

# pick one random item per type
Expand Down
13 changes: 13 additions & 0 deletions act/engine/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import bisect
import functools
import itertools
import logging as std_logging
Expand Down Expand Up @@ -212,3 +213,15 @@ def algebraic_product(**kwargs):

def strict(s):
return re.sub(r'[^\w\d]+', '_', re.sub(r'\(.+\)', '', s)).lower()


def weighted_random_choice(items):
totals = []
running_total = 0

for item in items:
running_total += item.weight
totals.append(running_total)

rnd = random.random() * running_total
return items[bisect.bisect_right(totals, rnd)]

0 comments on commit 18e3158

Please sign in to comment.