import array ; sort import case ; upcase import stack ; to_a import string ; isalpha, strcat, strjoin, strrev, strunpack import util ; eq
; returns whether the string S is the same forwards and backwards ; [S] => [0 | 1] ; ; [“racecar”] => [1] ; [“divider”] => [0] ; [“redivider”] => [1] palindrome?: dup :strrev :eq ret
; returns whether the strings S and T are composed of the same characters ; [S T] => [0 | 1] ; ; [“allergy” “gallery”] => [1] ; [“largely” “regally”] => [1] ; [“foo” “bar”] => [0] anagrams?:
:strunpack push 0 :to_a :sort :strjoin swap :strunpack push 0 :to_a :sort :strjoin :eq ret
; returns the sum of the alphabetical characters in string S where A=1, B=2… ; [S] => [sum] ; ; [“Math”] => [42] ; [“wizards”] => [100] ; [“AbCd”] => [10] isop: :upcase push 0 swap _isop_loop: dup jz _isop_done
swap copy 1 push 128 mod dup :isalpha jz _isop_no push 64
_isop_resume: sub add swap push 128 div jump _isop_loop _isop_no: dup jump _isop_resume _isop_done: pop ret
$_do_collatz() {
dup push 2 mod swap copy 1 push 2 mul $++ mul push 2 copy 2 sub div add
}
; returns the elements of the Collatz sequence for integer N as a pseudo-array ; ! may run forever on some as-yet-unknown input ; [N] => [A] ; ; [1] => [1 1] ; [2] => [2 1 2] ; [3] => [3 10 5 16 8 4 2 1 8] ; [4] => [4 2 1 3] ; [5] => [5 16 8 4 2 1 6] collatz: push 1 ; sequence length _collatz_loop:
copy 1 dup push 1 sub jz _collatz_done $_do_collatz() swap $++ jump _collatz_loop
_collatz_done: pop ret
; returns the length L of the Collatz sequence for integer N ; ! may run forever on some as-yet-unknown input ; [N] => [L] ; ; [1] => [1] ; [4] => [3] ; [7] => [17] ; [189] => [107] collatz_len: push 1 swap _collatz_len_loop:
dup $-- jz _collatz_done $_do_collatz() swap $++ swap jump _collatz_len_loop copy 1 dup push 1 sub jz _collatz_done
; ruby: ; push “'” :strcat push “ruby -e 'p ” swap :strcat shell ret
$_to_roman(r, v) {
push `v` :divmod swap push `r` swap :strrep @-2 swap :strcat ^-2
}
; converts the number N to a string of roman numerals R ; [N] => [R] ; ; [2020] => [“MMXX”] ; [1666] => [“MDCLXVI”] ; [1337] => [“MCCCXXXVII”] ; [94] => [“XCIV”] to_roman: push -2,0 store
$_to_roman("M", 1000) $_to_roman("CM", 900) $_to_roman("D", 500) $_to_roman("CD", 400) $_to_roman("C", 100) $_to_roman("XC", 90) $_to_roman("L", 50) $_to_roman("XL", 40) $_to_roman("X", 10) $_to_roman("IX", 9) $_to_roman("V", 5) $_to_roman("IV", 4) $_to_roman("I", 1) push 2 sub load ret
; applies the ROT13 “cipher” to the string S ; [S] => [S'] ; ; [“gnat”] => [“tang”] ; [“purely”] => [“cheryl”] ; [“cat.PNG”] => [“png.CAT”] ; [“Hello, world.”] => [“Uryyb, jbeyq.”] ; [“a123z”] => [“n123m”] ROT13:
push "AZ" :strexpand push "az" :strexpand :strcat push "NZ" :strexpand push "AM" :strexpand push "nz" :strexpand push "am" :strexpand :strcat :strcat :strcat :strtrans ret