Guest User

Brute-force for survivor game v1.11

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