はじめに
atcoder-toolsを使うとき、コンテストのディレクトリを作成したり、問題ごとのディレクトリを移動するのは面倒ですよね?シェル関数を利用してもっと簡単にしちゃいましょう!!
環境
OS: macOS
シェル: VSCodeのzsh, (bash)
エディタ: VSCode
ステップ1 zshの設定ファイルを開く
シェル関数を定義するために、ホームディレクトリにあるシェルの設定ファイルを開きます。~/.zhrc
です。
bash
の場合~/.bashrc
を編集します。動くか試してないです。多分問題ないとは思いますが・・・
ステップ2 atcoderコマンドの作成
まずatcoder
コマンドを作成し、追記します。このコマンドは、指定されたコンテスト名のディレクトリを作成(atcoder-tools gen abc
)し、その中のA問題に移動、main.py
を開きます。
ちなみに--lang
などのオプションはatcoder-toolsの設定ファイルに記述してるので省略してます。このコマンドに書けば設定ファイルを弄らなくてもいいですね。
function atcoder() {
if [ "$#" -ne 1 ]; then
echo "Usage: atcoder <contest>"
return 1
fi
CONTEST=$1
atcoder-tools gen $CONTEST
cd ~/YOUR_PATH_TO_CONTEST_DIR/$CONTEST/a
open main.py
}
ステップ3 next,pre コマンドの作成
次のアルファベットのディレクトリに移動するための next
コマンドを作成し、追記します。これにより、a
からb
、b
からc
へと順番に移動できます。同時に、各問題のmain.py
を開きます。
またこれと逆の処理であるpre
コマンドも実装します。
function move_to_directory() {
local direction=$1
# 現在のディレクトリを取得
current_dir=$(pwd)
# 現在のディレクトリの親ディレクトリを取得
parent_dir=$(dirname "$current_dir")
# 親ディレクトリ内の全ての子ディレクトリを取得し、ソートする
child_directories=$(find "$parent_dir" -mindepth 1 -maxdepth 1 -type d | sort)
# ソートされた子ディレクトリのリストから現在のディレクトリの位置を取得
current_dir_position=$(echo "$child_directories" | grep -n "$current_dir" | cut -d ":" -f 1)
# 次のディレクトリの位置を計算
next_dir_position=$((current_dir_position + direction))
# 次のディレクトリが存在する場合のみ移動する
if [ "$next_dir_position" -gt 0 ] && [ "$next_dir_position" -le "$(echo "$child_directories" | wc -l)" ]; then
next_directory=$(echo "$child_directories" | sed -n "${next_dir_position}p")
cd "$next_directory"
open main.py
else
echo "No such directory"
fi
}
function next() {
move_to_directory 1
}
function pre() {
move_to_directory -1
}
ステップ4 コマンドの実行
これで、atcoder
コマンドを使用してコンテストディレクトリに移動し、atcoder next
コマンドを使用して次のディレクトリに移動できます。
atcoder abc200 # コンテストディレクトリに移動
next # 次の問題に移動
pre # 前の問題に移動
おわりに
これでAtCoder-toolsのコマンド入力がよりストレスフリーになりました!
pre
とnext
は知らないだけで同じ機能が標準であったらどうしようと、これを書きながら震えてます・・・