Guest User

Brute-force for survivor game

a guest
Oct 16th, 2021
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.94 KB | None | 0 0
  1. #/usr/bin/env python3
  2.  
  3. from fractions import Fraction
  4. import operator
  5.  
  6. def eliminate(n, p_map):
  7.   survivors = set(range(1, n+1))
  8.   for i in range(n, 0, -1):
  9.     if i in survivors:
  10.       survivors.discard(p_map[i])
  11.   return survivors
  12.  
  13. def average_eval_probs(n, evals):
  14.   l = len(evals)
  15.   return {i: Fraction(1, l) * sum([e[2][i] for e in evals]) for i in range(1, n+1)}
  16.  
  17. # return (probability whether current player is alive, # survivors, map of k -> probability that k is alive in this path))
  18. def evaluate_dfs(n, cur_path):
  19.   k = len(cur_path) # how deep we are in the decision tree
  20.   # print('cur_path =', cur_path)
  21.   if k == n: # time to evaluate
  22.     survivors = eliminate(n, cur_path)
  23.     probs = {i: Fraction(1, 1) if i in survivors else Fraction(0,1) for i in range(1, n+1)}
  24.     return (probs[k], -len(survivors), probs) # want to sort the opposite direction by # survivors
  25.   else:
  26.     new_paths = [cur_path | {k+1: i} for i in range(1, n+1)]
  27.     new_path_evals = [evaluate_dfs(n, path) for path in new_paths]
  28.     # print("NEW PATHS")
  29.     # print(list(zip(new_paths, new_path_evals)))
  30.     new_path_evals.sort(key=operator.itemgetter(0, 1))
  31.     # now sorted by [survived, # survivors]
  32.     # get all paths tied with the best path, have to choose randomly between them
  33.     best_path_eval = new_path_evals[-1]
  34.     best_path_evals = [best_path_eval]
  35.     for path_eval in reversed(new_path_evals[:-1]):
  36.       if path_eval[0] == best_path_eval[0] and path_eval[1] == best_path_eval[1]:
  37.         best_path_evals.append(path_eval)
  38.  
  39.     # print("BEST_PATH_EVALS=", best_path_evals)
  40.  
  41.     probs = average_eval_probs(n, best_path_evals)
  42.     # if len(cur_path) == 2:
  43.       # print("RESULT FOR CUR_PATH = ", cur_path, "num_survivors = ", -best_path_eval[1], "probs = ", probs)
  44.     if k > 0:
  45.       return (probs[k], best_path_eval[1], probs)
  46.     else:
  47.       return (Fraction(0, 1), best_path_eval[1], probs)
  48.  
  49. def evaluate(n):
  50.   return evaluate_dfs(n, {})
Advertisement
Add Comment
Please, Sign In to add comment