Skip to content

Commit

Permalink
Optimize weighted_choice
Browse files Browse the repository at this point in the history
This should have no noticeable impact right now because the weight values are small anyway, but for huge weight values this should be a significant optimization as it avoids creating huge lists of duplicates in memory.
  • Loading branch information
LagoLunatic committed Jan 3, 2024
1 parent 117a07e commit 2d0ab80
Showing 1 changed file with 3 additions and 3 deletions.
6 changes: 3 additions & 3 deletions randomizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,7 @@ def get_new_rng(self):
return rng

def weighted_choice(self, rng: Random, seq: list[T], weight_conditions: list[tuple[int, Callable[[T], bool]]]) -> T:
weighted_seq = []
element_weights = []

for element in seq:
weight_for_element = 1
Expand All @@ -963,9 +963,9 @@ def weighted_choice(self, rng: Random, seq: list[T], weight_conditions: list[tup
if condition_callback(element):
weight_for_element *= weight

weighted_seq += weight_for_element*[element]
element_weights.append(weight_for_element)

return rng.choice(weighted_seq)
return rng.sample(seq, 1, counts=element_weights)[0]

def get_seed_hash(self):
# Generate some text that will be shown on the name entry screen which has two random character names that vary based on the permalink (so the seed and settings both change it).
Expand Down

0 comments on commit 2d0ab80

Please sign in to comment.