ぼんやりDTP

DTPに関係したりしなかったりするぼんやりとした話をなんとなく。

AppleScript でコラッツの数列を計算する

なんか未解決問題の「コラッツ予想」というのがあるらしいというのを知って、その数列の計算自体は簡単そうだったので、なんとなくAppleScriptで計算できるように書いてみた。

display dialog "正の整数を入力してください" default answer "1"

set theValue to text returned of result as integer

set theValues to {}

(*
if theValue is not 1 then
   repeat while theValue is not 1
       set end of theValues to theValue as integer
       if theValue mod 2 = 0 then
           set theValue to theValue / 2
       else
           set theValue to theValue * 3 + 1
       end if
   end repeat
end if
set end of theValues to theValue as integer
*)
collatz(theValue, theValues)

set theResultString to my listItemsToString(theValues, ", ")

display dialog "結果" default answer theResultString

on collatz(n, values)
    set end of values to n as integer
    if n mod 2 is 1 and n > 1 then
        collatz(3 * n + 1, values)
    else if n mod 2 = 0 then
        collatz(n / 2, values)
    end if
end collatz

on listItemsToString(theList, theDelimiters)
    set tmp to AppleScript's text item delimiters
    set AppleScript's text item delimiters to theDelimiters
    set theListString to theList as string
    set AppleScript's text item delimiters to tmp
    return theListString
end listItemsToString

途中のコメントアウトしてるのは初めに自分でrepeatで組んだやつで、実際動いたけど、Wikipedia再帰を利用したスマートっぽい疑似コードがあったので、それを元に書き直してみた。

AppleScript再帰を用いると割と早めにスタックオーバーフローが起こるらしいけれども、まあ、お遊びなのであまり気にしない。

参考ページ: