Skip to content

Instantly share code, notes, and snippets.

@takashioya
Last active February 26, 2019 12:06
Show Gist options
  • Save takashioya/6d68d9057f8d1addcb2faa8ccc223998 to your computer and use it in GitHub Desktop.
Save takashioya/6d68d9057f8d1addcb2faa8ccc223998 to your computer and use it in GitHub Desktop.
from itertools import permutations
import numpy as np
import pandas as pd
def get_optimal_solution(random_seed, answers_df):
answers = answers_df.values
names = answers_df.index.values
N = answers.shape[0]
# 全パターンの順位を取得 (8!通り)
all_orders = np.array(list(permutations(range(N))))
# 全パターンについて幸福度を計算
happiness = answers[np.arange(N), all_orders].sum(axis = 1)
min_happiness = np.min(happiness)
# 幸福を最大化するような順位を選択
optimal_solutions = all_orders[happiness == min_happiness]
np.random.seed(random_seed)
random_idx = np.random.choice(np.arange(optimal_solutions.shape[0]))
optimal_solution = optimal_solutions[random_idx]
result = names[np.argsort(optimal_solution)]
scores = answers[np.arange(N), optimal_solution]
hope_rank = {name : score for (name, score) in zip(names, scores)}
return list(result), hope_rank
if __name__ == '__main__':
names = ['岩住', '小池', '辻', '岩瀬', '田中', '小林', '中村', '大矢']
raw_data = pd.DataFrame([[3,4,6,7,2,5,1,8],
[3, 6, 2, 7, 1, 8, 4, 5],
[5, 6, 4, 3, 7, 2, 8, 1],
[0, 0, 0, 0, 0, 0, 0, 0],
[4, 5, 6, 3, 7, 2, 8, 1],
[2, 3, 4, 5, 6, 1, 7, 8],
[5, 3, 1, 2, 4, 6, 7, 8],
[1, 2, 3, 4, 5, 6, 7, 8]], index = names)
answers = raw_data.apply(lambda x : x.argsort(), axis = 1)
answers.loc['岩瀬'] = 0
result, hope_rank = get_optimal_solution(0, answers)
print(raw_data)
print('順番: ' + str(result))
print('希望度: ' + str(hope_rank))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment