Greasy Fork is available in English.

AtCoder Difficulty Display

AtCoder Problemsの難易度を表示します。

Fra 16.10.2021. Se den seneste versjonen.

  1. // ==UserScript==
  2. // @name AtCoder Difficulty Display
  3. // @namespace https://github.com/hotarunx
  4. // @homepage https://github.com/hotarunx/AtCoderDifficultyDisplay
  5. // @supportURL https://github.com/hotarunx/AtCoderDifficultyDisplay/issues
  6. // @version 1.0.8
  7. // @description AtCoder Problemsの難易度を表示します。
  8. // @description:en display a difficulty of AtCoder Problems.
  9. // @author hotarunx
  10. // @match https://atcoder.jp/contests/*
  11. // @exclude https://atcoder.jp/contests/
  12. // @grant none
  13. // @connect https://kenkoooo.com/atcoder/resources/problem-models.json
  14. // @connect https://kenkoooo.com/atcoder/atcoder-api/results?user=*
  15. // @license MIT
  16. //
  17. // Copyright(c) 2020 hotarunx
  18. // This software is released under the MIT License, see LICENSE or https://github.com/hotarunx/AtCoderMyExtensions/blob/master/LICENSE.
  19. //
  20. // ==/UserScript==
  21.  
  22. // 現在時間、コンテスト開始時間、コンテスト終了時間(UNIX時間 + 時差)
  23. const nowTime = Math.floor(Date.now() / 1000);
  24. const contestStartTime = Math.floor(Date.parse(startTime._i) / 1000);
  25. const contestEndTime = Math.floor(Date.parse(endTime._i) / 1000);
  26.  
  27. (async function () {
  28. // URLから問題ID(ex: abc170_a)を取得
  29. const path = location.pathname.split("/");
  30. const problemId = path[path.length - 1];
  31. const isABS = path[2] == "abs";
  32.  
  33. // 問題のコンテストが開催中ならば全ての処理をスキップする。
  34. if (!isABS && !isContestOver(nowTime)) return;
  35.  
  36. const diffURL = "https://kenkoooo.com/atcoder/resources/problem-models.json";
  37. const diffKey = "atcoderDifficultyDisplayEstimatedDifficulties";
  38.  
  39. const submissionsURL = "https://kenkoooo.com/atcoder/atcoder-api/results?user=" + userScreenName;
  40. const submissionsKey = "atcoderDifficultyDisplayUserSubmissions";
  41.  
  42. const estimatedDifficulties = await fetchAPIData(diffURL, diffKey, 1 * 60 * 60);
  43. // const userSubmissions = await fetchAPIData(submissionsURL, submissionsKey, 1 * 60 * 60);
  44.  
  45.  
  46. if (path[path.length - 2] == "tasks") {
  47. const problemStatus = getElementOfProblemStatus();
  48. const problemTitle = document.getElementsByClassName("h2")[0];
  49.  
  50. changeProblemTitle(problemId, estimatedDifficulties, problemTitle, false);
  51. addDifficultyText(problemId, estimatedDifficulties, problemStatus);
  52. // if (!isABS)
  53. // addIsSolvedText(problemId, userSubmissions, problemStatus);
  54. }
  55.  
  56. const as = document.getElementsByTagName("a");
  57. for (const item of as) {
  58. const h = item.getAttribute("href");
  59. if (typeof (h) != "string") continue;
  60. const hpath = h.split("/");
  61.  
  62. if (hpath[hpath.length - 2] == "tasks") {
  63. // itemが*/tasksページの表の一番左なら色付けしない
  64. if (item.parentElement.className === "text-center no-break") continue;
  65.  
  66. const hProblemId = hpath[hpath.length - 1];
  67. changeProblemTitle(hProblemId, estimatedDifficulties, item, true);
  68. }
  69.  
  70. }
  71. })();
  72.  
  73. // コンテストが終了した?
  74. function isContestOver(time) {
  75. // 緩衝時間(20分)
  76. const bufferTime = 20 * 60;
  77.  
  78. // 現在時間 > コンテスト終了時間 + 緩衝時間?
  79. if (time > contestEndTime + bufferTime) return true;
  80. return false;
  81. }
  82.  
  83. // APIサーバからデータを取得してlocalStorageに保存して返す
  84. // 直前の取得から時間が経過していないならば保存したデータを返す
  85. async function fetchAPIData(url, keyData, timeInterval) {
  86. const keyLastFetch = keyData + "lastFetchedAt";
  87. let jsondata = JSON.parse(localStorage.getItem(keyData));
  88. const fetchTime = parseInt(localStorage.getItem(keyLastFetch));
  89.  
  90. // コンテストが終了していないならばデータ取得はしない
  91. if (!isContestOver(nowTime)) return jsondata;
  92.  
  93. // 次のいずれかを満たすならば取得する
  94. // * データが保存されていない
  95. // * 直前の取得からtimeInterval経過した
  96. // * 直前の取得時にコンテストが終了していなかった
  97.  
  98. let need2Fetch = false;
  99. if (isNaN(fetchTime)) need2Fetch = true;
  100. else if (nowTime >= timeInterval + fetchTime) need2Fetch = true;
  101. else if (!isContestOver(fetchTime)) need2Fetch = true;
  102.  
  103. // データを取得する
  104. if (need2Fetch) {
  105. // alert(keyData + "is fetched.");
  106. jsondata = await (await (fetch(url))).json();
  107. removeUnusedValues(jsondata);
  108. localStorage.setItem(keyData, JSON.stringify(jsondata));
  109. localStorage.setItem(keyLastFetch, nowTime);
  110. }
  111.  
  112. return jsondata;
  113. }
  114.  
  115. function removeUnusedValues(jsondata) {
  116. const necessaryKeys = ["difficulty", "is_experimental", "epoch_second", "point", "result", "problem_id"];
  117.  
  118. for (const item in jsondata) {
  119. for (const key in jsondata[item]) {
  120. if (!necessaryKeys.includes(key)) {
  121. delete jsondata[item][key];
  122. }
  123. }
  124. }
  125. }
  126.  
  127. // Webページの問題ステータス(実行時間制限とメモリ制限が書かれた部分)のHTMLオブジェクトを取得
  128. function getElementOfProblemStatus() {
  129. let element_status;
  130.  
  131. const main_container = document.getElementById('main-container');
  132. const elements_p = main_container.getElementsByTagName("p");
  133.  
  134. for (let i = 0; i < elements_p.length; i++) {
  135. const element = elements_p[i];
  136. if (element.textContent.match("メモリ制限:") || element.textContent.match("Memory Limit:")) {
  137. element_status = element;
  138. break;
  139. }
  140. }
  141.  
  142. return element_status;
  143. }
  144.  
  145. // レーティングに対応する色のカラーコード
  146. function colorRating(rating) {
  147. if (rating < 400) return '#808080'; // gray
  148. else if (rating < 800) return '#804000'; // brown
  149. else if (rating < 1200) return '#008000'; // green
  150. else if (rating < 1600) return '#00C0C0'; // cyan
  151. else if (rating < 2000) return '#0000FF'; // blue
  152. else if (rating < 2400) return '#C0C000'; // yellow
  153. else if (rating < 2800) return '#FF8000'; // orange
  154. return '#FF0000'; // red
  155. }
  156.  
  157. // レートを表す難易度円(◒)を生成
  158. function generateDifficultyCircle(rating, isSmall = true) {
  159. const size = (isSmall ? 12 : 36);
  160. const borderWidth = (isSmall ? 1 : 3);
  161.  
  162. if (rating < 3200) {
  163. // 色と円がどのぐらい満ちているかを計算
  164. const color = colorRating(rating);
  165. const percentFull = (rating % 400) / 400 * 100;
  166.  
  167. // ◒を生成
  168. return "<span style = 'display: inline-block; border-radius: 50%; border-style: solid;border-width: " + borderWidth + "px; margin-right: 5px; vertical-align: initial; height: " + size + "px; width: " + size + "px;border-color: " + color + "; background: linear-gradient(to top, " + color + " 0%, " + color + " " + percentFull + "%, rgba(0, 0, 0, 0) " + percentFull + "%, rgba(0, 0, 0, 0) 100%); '></span>";
  169.  
  170. }
  171. // 金銀銅は例外処理
  172. else if (rating < 3600) {
  173. return '<span style="display: inline-block; border-radius: 50%; border-style: solid;border-width: ' + borderWidth + 'px; margin-right: 5px; vertical-align: initial; height: ' + size + 'px; width: ' + size + 'px; border-color: rgb(150, 92, 44); background: linear-gradient(to right, rgb(150, 92, 44), rgb(255, 218, 189), rgb(150, 92, 44));"></span>';
  174.  
  175. } else if (rating < 4000) {
  176. return '<span style="display: inline-block; border-radius: 50%; border-style: solid;border-width: ' + borderWidth + 'px; margin-right: 5px; vertical-align: initial; height: ' + size + 'px; width: ' + size + 'px; border-color: rgb(128, 128, 128); background: linear-gradient(to right, rgb(128, 128, 128), white, rgb(128, 128, 128));"></span>';
  177.  
  178. } else {
  179. return '<span style="display: inline-block; border-radius: 50%; border-style: solid;border-width: ' + borderWidth + 'px; margin-right: 5px; vertical-align: initial; height: ' + size + 'px; width: ' + size + 'px; border-color: rgb(255, 215, 0); background: linear-gradient(to right, rgb(255, 215, 0), white, rgb(255, 215, 0));"></span>';
  180.  
  181. }
  182. }
  183.  
  184. // 400未満のレーティングを補正
  185. // 参考 https://qiita.com/anqooqie/items/92005e337a0d2569bdbd#性質4-初心者への慈悲
  186. function correctLowerRating(rating) {
  187. if (rating >= 400) return rating;
  188. return 400 / Math.exp((400 - rating) / 400);
  189. }
  190.  
  191. function changeProblemTitle(problemId, estimatedDifficulties, problemTitle, isSmall = true) {
  192. const problem = estimatedDifficulties[problemId];
  193.  
  194. // 問題が存在しなければ終了
  195. if (problem == null) return;
  196. if (problem.difficulty != null) {
  197. const difficulty = correctLowerRating(problem.difficulty).toFixed();
  198. problemTitle.style.color = colorRating(difficulty);
  199. if (problem.is_experimental) problemTitle.insertAdjacentHTML("afterbegin", "🧪");
  200. problemTitle.insertAdjacentHTML("beforebegin", generateDifficultyCircle(difficulty, isSmall));
  201. }
  202. else {
  203. problemTitle.style.color = "#17a2b8";
  204. const unavailableCircle = "(?)";
  205. problemTitle.insertAdjacentHTML("afterbegin", unavailableCircle);
  206. }
  207. }
  208.  
  209. // 推定難易度文字列を生成
  210. function generateDifficultyText(difficulty, is_experimental) {
  211. // 推定難易度を補正して四捨五入
  212. difficulty = correctLowerRating(difficulty);
  213. difficulty = difficulty.toFixed();
  214.  
  215. const textValue = "<span style='font-weight: bold; color: " + colorRating(difficulty) + ";'>" + difficulty + "</span>";
  216. // textDiff = "<a href='https://kenkoooo.com/atcoder/#/table/" + userScreenName + "'>Difficulty</a>";
  217. const textDiff = "Difficulty";
  218.  
  219. return textDiff + ": " + textValue + (is_experimental ? " (🧪)" : "");
  220. }
  221.  
  222. // 推定難易度表示を追加する
  223. function addDifficultyText(problemId, estimatedDifficulties, problemStatus) {
  224. const problem = estimatedDifficulties[problemId];
  225.  
  226. // 問題が存在しなければ終了
  227. if (problem == null) return;
  228.  
  229. if (problem.difficulty != null) {
  230. // 難易度を表示する文字列を生成
  231. const text = generateDifficultyText(problem.difficulty, problem.is_experimental);
  232. problemStatus.insertAdjacentHTML('beforeend', " / " + text);
  233. } else
  234. problemStatus.insertAdjacentHTML('beforeend', " / Difficulty: <span style='font-weight: bold; color: #17a2b8;'>Unavailable</span>");
  235. }
  236.  
  237. // AC、コンテスト中AC、ペナルティ数、AC時間、最大得点、コンテスト中最大得点を計算
  238. function searchSubmissionsResult(submissions) {
  239. const nonPenaltyJudge = ["AC", "CE", "IE", "WJ", "WR"];
  240. submissions.sort((a, b) => a.epoch_second - b.epoch_second);
  241.  
  242. let accepted = false;
  243. let acceptedDuringContest = false;
  244. let penalties = 0;
  245. let acceptedTime = contestEndTime;
  246. let maxPoint = 0;
  247. let maxPointDuringContest = 0;
  248.  
  249. for (const item of submissions) {
  250. const duringContest = contestStartTime <= item.epoch_second && item.epoch_second < contestEndTime;
  251.  
  252. if (item.result == "AC") {
  253. accepted = true;
  254. if (duringContest) {
  255. acceptedDuringContest = true;
  256. acceptedTime = Math.min(item.epoch_second, acceptedTime);
  257. }
  258. }
  259.  
  260. if (!accepted && duringContest && !nonPenaltyJudge.includes(item.result)) {
  261. penalties++;
  262. }
  263.  
  264. maxPoint = Math.max(item.point, maxPoint);
  265. if (duringContest)
  266. maxPointDuringContest = Math.max(item.point, maxPointDuringContest);
  267. }
  268.  
  269. return { accepted, acceptedDuringContest, penalties, acceptedTime, maxPoint, maxPointDuringContest };
  270. }
  271.  
  272. function epochTime2HHMM(time) {
  273. return Math.floor(time / 60).toFixed() + ":" + (time % 60).toFixed().padStart(2, '0');
  274. }
  275.  
  276. // ACしたか、AC時間、ペナルティ数を表示
  277. function addIsSolvedText(problemId, userSubmissions, problemStatus) {
  278. const submissions = userSubmissions.filter(function (item, index) { if (item.problem_id == problemId) return true; });
  279. const submitted = submissions.length > 0;
  280. const { accepted, acceptedDuringContest, penalties, acceptedTime, maxPoint, maxPointDuringContest } = searchSubmissionsResult(submissions);
  281.  
  282. let text = "Is Solved: ";
  283. if (acceptedDuringContest) text += "<span style='font-weight: bold; color: white; background: green; border-radius: 20%;'>✓</span>";
  284. else if (accepted) text += "<span style='font-weight: bold; color: green;'>✓</span>";
  285. else if (submitted) text += "<span style='font-weight: bold; color: orange;'>✘</span>";
  286. else text += "<span style='font-weight: bold; color: gray;'>✘</span>";
  287.  
  288. if (acceptedDuringContest)
  289. text += " <span style='font-size: x-small; color: grey;'>" + epochTime2HHMM(acceptedTime - contestStartTime) + "</span> ";
  290.  
  291. if (penalties > 0)
  292. text += " <span style='font-size: x-small; color: red;'>(" + penalties + ")</span> ";
  293.  
  294. if (maxPoint >= 10000) {
  295. text += " <span style='font-size: x-small; color: orange;'>" + maxPoint + "</span> ";
  296. if (maxPointDuringContest != maxPoint)
  297. text += " <span style='font-size: x-small; color: orange;'>(" + maxPointDuringContest + ")</span> ";
  298. }
  299.  
  300. problemStatus.insertAdjacentHTML('beforeend', " / " + text);
  301. }