AppleScriptで競プロ

AppleScript歴1ヶ月ですが競プロに使えるかなと思ったのでやってみた。

出力

これは簡単で、変数`hoge`を出力するなら

do shell script "echo " & hoge

入力

普通はコマンドを実行したあと、入力例をペーストしてると思う。ジャッジも多分そうしてるんだろう。そこで方針としては、

  1. ターミナルを呼び出す
  2. コマンド osascript hoge.scptを実行
  3. すかさず入力例をペーストしてエンター
  4. ターミナルのhistoryを呼び出して、逆順にwordをたどって”scpt”を含んだら止める

さっそく実装しよう。

delay 3  # 3秒間待ってやる

tell application "Terminal"
	set hist to history of tab 1 of window 1 as string
	set wordNum to count word of hist
	set args to {}
	repeat with j from 1 to wordNum
		set i to (wordNum - j + 1)
		if word i of hist contains "scpt" then
			exit repeat
		end if
		set args to {word i of hist as number} & args
	end repeat
end tell

入力した数字とかがコマンドとして後で実行されるけど、無視しよう。

基本文法

set someVariable to someValue #代入

1 + 1 #--> 2
1 - 1 #--> 0
1 * 1 #--> 1
514 mod 114 #--> 58

set lst to {8, 1, 0} #リスト
item 2 of lst #--> 1

set dct to {apple: 4, orange: 5} #レコード
apple of dct #--> 4

"52149" as number #--> 52149
lst as string #--> "810"

if hogehoge then
else if fugafuga then
else
end if

repeat n times
repeat with i from 1 to n
repeat with element in list
repeat while hoge
...
end repeat

on Handler(arg1, arg2)
on Handler given a1:arg1, a2:arg2
...
    return hoge
end Handler

Handler(hoge, fuga)
Handler given a1:hoge, a2:fuga

解いてみた

ABC116-B

delay 3 #3秒間待ってやる
tell application "Terminal"
	## 省略 ##
	
	set s to item 1 of args
	set arr to {s}
	set appd to s
	
	repeat
		set l to appd
		if l mod 2 = 0 then
		        set appd to l / 2
		else
			set appd to (3 * l + 1)
		end if
		if arr contains appd then
			exit repeat
		end if
		set arr to arr & {appd}
	end repeat
	
	do shell script "echo " & (count arr) + 1 as string
end tell

ところで

AppleScriptでできるコンテストのサイトあったら教えてください。

Posted by mya_f