Created
May 26, 2023 19:23
-
-
Save RagingTiger/f71ac23020fce084f66b3325f53763d2 to your computer and use it in GitHub Desktop.
Sun Bin's, the descendant of Sun Tzu, generalized solution for how General Tianji should race his horses against the King of Qi.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
References: | |
+ Shu, J. (2012). On Generalized Tian Ji's Horse Racing Strategy. | |
Interdisciplinary Science Reviews, 37, 187 - 193. | |
+ Leng, M., & Parlar, M. (2006). Game-theoretic analysis of an ancient Chinese | |
horse race problem. Comput. Oper. Res., 33, 2033-2055. | |
""" | |
def get_horses(n): | |
for horse in range(1, n+1): | |
yield horse | |
def get_strategy(n): | |
# g(x), h(x), and f(x) definitions | |
g = lambda x: x - 1 | |
h = lambda x, n: n * (0 ** (x - 1)) | |
f = lambda x, n: g(x) + h(x, n) | |
# use generator for horses | |
for horse in get_horses(n): | |
# calculate optimal horse pairs | |
yield (horse, f(horse, n)) | |
def print_choice(n): | |
# loop over choice pairs | |
for matches in get_strategy(n): | |
# pretty print matches | |
print(f'race: {matches[0]:{len(str(n))}} -> {matches[1]}') | |
# executable | |
if __name__ == '__main__': | |
# get argparsing lib | |
import argparse | |
# describe | |
parser = argparse.ArgumentParser( | |
description='Calculate optimal horse racing strategy.' | |
) | |
# add arguments | |
parser.add_argument('horses', metavar='n', type=int, | |
help='number of horses to race') | |
# now get args | |
args = parser.parse_args() | |
# finally execute | |
print_choice(args.horses) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment