sample/trick2025/: adds the top-five entries of TRICK 2025

See https://github.com/tric/trick2025 for TRICK 2025.
This commit is contained in:
Yusuke Endoh 2025-04-17 17:10:16 +09:00
parent 7e2ba5a91b
commit 25efd09c71
Notes: git 2025-04-17 10:59:46 +00:00
21 changed files with 1444 additions and 0 deletions

View File

@ -0,0 +1,5 @@
* Don Yang
* omoikane@uguu.org
* cctld: us
* bsky.app/profile/omoikane.bsky.social
* twitter.com/uguu_org

View File

@ -0,0 +1,81 @@
#!/usr/bin/ruby -w
# Simple BF interpretor.
#
# This works by translating input code into ruby and evaluating the
# translated ruby code. Doing it this way runs much faster than
# interpreting BF on our own.
#
# There is no error reporting whatsoever. A malformed input may result in
# a syntax error at run time, but good luck in finding where it came from.
# Setup empty tape and initial pointer position. Note that tape size is
# fixed. We can make it infinite by initializing it to "[]" here and
# adding some nil checks in the generated code, but avoiding those checks
# makes the program run ~10% faster.
$code = "t=Array.new(30000,0); p=0;"
# Counters for pending add or shift operations. We buffer incoming +-<>
# operators and output a single merged operation when we encounter a
# different operator.
$buffered_add = 0
$buffered_shift = 0
# Flush pending add operations, if any.
def flush_add
if $buffered_add != 0
$code += "t[p]+=#{$buffered_add};"
$buffered_add = 0
end
end
# Flush pending shift operations, if any.
def flush_shift
if $buffered_shift != 0
$code += "p+=#{$buffered_shift};"
$buffered_shift = 0
end
end
def flush_pending_ops
flush_add
flush_shift
end
# Convert input characters to ruby.
ARGF.each_char{|c|
case c
when '+'
flush_shift
$buffered_add += 1
when '-'
flush_shift
$buffered_add -= 1
when '<'
flush_add
$buffered_shift -= 1
when '>'
flush_add
$buffered_shift += 1
when ','
flush_pending_ops
$code += "if c=STDIN.getc;" +
"t[p]=c.ord;" +
"else;" +
"t[p]=-1;" + # EOF is interpreted as -1.
"end;"
when '.'
flush_pending_ops
$code += "print t[p].chr;"
when '['
flush_pending_ops
$code += "while t[p]!=0;"
when ']'
flush_pending_ops
$code += "end;"
end
}
flush_pending_ops
# Evaluate converted code.
eval $code

View File

@ -0,0 +1,32 @@
a=+Math::PI/13
#Z---z';#za-mRUBY
#A-ZaA-Mn--\[+>+>++
'"N-Z(\++\[->++++@"
b=\[->+> +>+>\[h_
p%{} eact
zoraq ;%{ GF. rin);
%{eb} r A R p *""\]
<<<{{{ }<\]<b
]<l(%w| } ; a;a=%Y/
evar{|c)} <][ #pgny\W{f
chaa,b)]>++[ ->+>>>>>[40v
.tr(= ' ;eval(%w{r=u=b= y =0;%{
(ct;c ) ; ] <<->--<<< < < ] >>[>,
exi}; a * = A RGV.siz e > 0 ? -1:1;
z=[] ; A R G F .ea c h _ l i n e{|i
|i.eac h _ g r aph e m e _ c l u ster
{|j|i f ( k = j.o r d ) < 3 3 ; r+=k<
32?k==9? 8 - r%8 : k = = 1 0 | |k==13
?[u+=1,-r][ 1]: 0 : 1 ; e lse;z+=[[u,
r,j]];b+=r;y+=u;r+=1;end;}};if(s=z.si
ze)>0;b/=s;y/=s;m,n=z[0];i=Math::tan(
a/2);j=Math::sin(a);z.map!{|d|p=d[1]-
b;q=d[0]-y;p-=(i*q).round;m=[m,q+=(j*
p).round].min;n=[n,p-=(i*q).round].
min;[q,p,d[2]]};r=n;u=m;z.sort.eac
h{|d|p,b=d;r=(u<p)?n:r;print"\n"
*(p-u),"\40"*(b-r),d[2];u=p;r=
b+1};print"\n";end}*"");%(]>
"tyvuts(}}.--.>--.>+.<++'
)b\40"gena.(c)2025<<<
#)#ehol""+a*.^_^

View File

@ -0,0 +1,71 @@
### Summary
This is a rot13 filter. Given an input text, it will **rotate** the text by **pi/13** radians. Two modes of operation are available, selected based on number of command line arguments.
Rotate clockwise:
ruby entry.rb < input.txt
Rotate counterclockwise:
ruby entry.rb input.txt
ruby entry.rb - < input.txt
### Details
This program interprets input as an ASCII art with each character representing individual square pixels, and produces a rotated image to stdout. All non-whitespace characters are preserved in output, only the positions of those characters are adjusted. While all the characters are preserved, the words and sentences will not be as readable in their newly rotated form. This makes the program suitable for obfuscating text.
ruby entry.rb original.txt > rotated.txt
ruby entry.rb < rotated.txt > unrotated.txt
But note that while `unrotated.txt` is often the same as `original.txt`, there is no hard guarantee due to integer rounding intricacies. Whether the original text can be recovered depends a lot on its shape, be sure to check that the output is reversible if you are using this rot13 filter to post spoilers and such.
Reversibility does hold for `entry.rb`:
ruby entry.rb entry.rb | ruby entry.rb | diff entry.rb -
ruby entry.rb < entry.rb | ruby entry.rb - | diff entry.rb -
Also, there is a bit of text embedded in the rotated version:
ruby entry.rb entry.rb | ruby
But this text is encrypted! No problem, just rotate `entry.rb` the other way for the decryption tool:
ruby entry.rb < entry.rb > caesar_cipher_shift_13.rb
ruby entry.rb entry.rb | ruby | ruby caesar_cipher_shift_13.rb
If current shell is `bash` or `zsh`, this can be done all in one line:
ruby entry.rb entry.rb | ruby | ruby <(ruby entry.rb < entry.rb)
### Miscellaneous features
To rotate to a different angle, edit the first line of `entry.rb`. Angles between -pi/2 and pi/2 will work best, anything outside that range produces more distortion than rotation, although the output might still be reversible.
Setting angle to zero makes this program a filter that expands tabs, trim whitespaces, and canonicalize end-of-line sequences.
This program preserves non-ASCII characters since input is tokenized with `each_grapheme_cluster`, although all characters that's not an ASCII space/tab/newline are given the same treatment. For example, the full-width space character (U+3000) will be transformed as if it's a half-width non-whitespace ASCII character.
If input contains only whitespace characters, output will be empty.
The layout is meant to resemble a daruma doll. There was still ~119 bytes of space left after fitting in 3 ruby programs, so I embedded a brainfuck program as well.
ruby bf.rb entry.rb
A `sample_input.txt` has been included for testing. After rotating this file 26 times either clockwise or counterclockwise, you should get back the original `sample_input.txt`.
ruby entry.rb < sample_input.txt | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | ruby entry.rb | diff sample_input.txt -
ruby entry.rb sample_input.txt | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | ruby entry.rb - | diff sample_input.txt -
Additional development notes can be found in `spoiler_rot13.txt` (rotate clockwise to decode).
ruby entry.rb < spoiler_rot13.txt
### Compatibility
Program has been verified to work under these environments:
* ruby 3.2.2 on cygwin.
* ruby 2.5.1p57 on linux.
* ruby 2.7.4p191 on linux.
* ruby 2.7.1p83 on jslinux.

View File

@ -0,0 +1,35 @@
T U
S V
R T U W
S V
Q R W X
Q X
P i h g f Y
j e
P k d Y
O l c Z
O Z
m b
* N N n + a A A *
o z
M B
M p y B
L q x C
r w
L s t u v C
K D
K J E D
I F
J H G E
I F
H G

View File

@ -0,0 +1,470 @@
.
text
ted t to
rota tex
dit HTML
to etes oss
sier wri acr
t earb"), ions .
ke itry. etat text
o ma "en erpr tive
ge te.g. e int: erna
L paut ( tiplsteps alt edit,he
a HTM inp muling cted ach dit tu
-w tes nt as havellow expe er ely ere yo
uby neragume can e fo the aftrect whethis
in/rt gee ar hat y th t. has stepindicesshat
usr/bcripingl ext tt tr texsult ion to prois w
#!/his s a s of t migh inale re rotatededis aich ts.
# TTakest. ece you origf th tra ts neike , wh tex
# stdou a piles, the ck i e exemenuld lusly ated the
# ite ang s tod che f th movu wotaneo rot pen
# To wrrent edit, an se orsort yoimul and nd o ne.
# diffe ome tion1-2. ecaue cu Whats s inal t, a en do
# ke srotaeps ous be thve. tex orig ayou t wh
# 1. Maply t st tediecausuitiated hold he l tex this
# 2. Apepea is lt bunint rot to rom ted. ated but
# 3. R cessficu is l and ough le fenabl upd nce, in
# pro diftextgina e en L fiipt the atie dable
# Thisalsoive ori larg HTMascr paste of p reay
# and rnat thedes: at's te a jav opy& bit its. t is Rubke },
# alteeditrovi t th nerawith en c fair l ed thar ine-li, %w{
# can pt p ayou to geser , th h a manua textasiequot %()
# scri a l ipt brow page witose ing 's eple %{},
# Make scrin a TML textn th writt itulti of ter
## 1. thisTML the H dit ly o lly:l, buas m use Ras t
# Run ut H via ly euick ficaiviauby hakestes. eral wan
# 2. outp its anualte q peciy trse R.rb m quo Gen nd we
# y ed to mitera by sactlecauntryouble for rs a
# Appl eed you g Rut exs, b. ele+d ithm acte
# 3. ll nlet ardins nouageientsing Algor char paperpplyg
# stiill regons ilangnvenmon ast ces: are nal ply ardin
# Youol w hingtatither e co com "A Feren els rigi sim regato
# to re trienny o quit the on diff r pix . O andailsnter
# e mole oo ma areourse asedtwo e ous. tionates detn ce o
# Onltiped tthatof c is bith sincalue rotardine toatio is n
# mumparors and ithm h, w ls, er v r of coot du rot here ns d
# coerat//, lgor Paet pixeract enteinput, but to r, tratio, an.
# op{}, on aAlan ing cha ng cthe as isspecion. ente opeinput two
# %W tati by blendinal ardiing ues th reunct on ctionthe ne or
# e roion" for orig reghift vale witer f tatirota of a li
# Thotat ort the tionut snate car_cen e roise hapeextr
# R supperve idera aboordixtra get stablockwhe s an ons.
# No pres consthingd coed e see ore terclon tting tatiugh
# - to nal any-basee neble, a mcoun lot nser e roltho
# itio sayto 0ng, wersi tingise/ds a by i oducd, a
# Addsn'trms undit rev elecockwepenible ] prstea
# - doensfor routpu in se clIt dvers pi/2t in ly to
# trategehe o care utivt. e re i/2, tex ical
# inke t tra onsecr ou mad [-pt the omat
# ma h exat c othen be weenstorible. aut
# wite theachon ca beto divers sted
# Evenantecel tati glesnd te re adju s.
# guar cane ro y ane tell b l be ment
# willn th Onlrang sti wil ele
# ofte gle.that ight idth text
# n anide ion m . W ble erialink
atiooutsrmat/ 13 entss. edita les. he scan l
Rotles nsfo:PI elemcell all tup . T we
# Ang traath: edit ter to eme) textthat
# the = M of harac ched graph ate uch her.
#NGLE ightre c.9em" atta al, rotD, sh ot
A e hesqua= "0 be seri me toue I eac
Linure GHT me to x, aphe uniqs to
# ens_HEI s na (y, d grme aation
#LINE clas "t" t of s anaphe rot
yle SS = a lis nateh grrent
# St_CLA as ordi eaciffe
EDIT nput he cogivess d
ad i ed td to acro
# Lo y neaddeheme
# onl is grap 0
# Wemberame put _y = {|c|
# nuhe sd_in] ursor ster
# t loa = [ = c ine|_clu 8
defdataor_x 0 ne{|lheme x %
cursal =h_li_grap 1 sor_r\n" ]
seri.eaceach= " "x +=" cur= "\ , c]
ARGFine. c =rsor_ "\t 8 - c = rial
l if cu c ==x +=" || x, se
lsifrsor_ "\n0 sor_
e cu c ==x = 1 cur
lsifrsor_y += r_y, t
e cursor_ urso thay
cu [[c= 1 ilityed bext.
lse ta +=_x +1 obabollowal t
e daursor += e pron frigin
cerial ass. s thtatihe o
s of m easee roin t l be hat
end nter incrkwislts wilges thave
m ce nter clocresu heret ed We
} a fro n cee. a sa) o, taighion.
dat nter atio, i.e ver zer strotat
} turn n ce rotible vic frome.g.he r ,
re tatio s asvers (or away er, er t tione.
nd e ro mase retion und cent aftcts: rotaitiv
e mput er ofll brota e rotionld betifa o. ox. ftern pos
# Co centon wiise ow wrotashouse ar zerng box aemai r
# ing tatilockw to hthe hey the d ofunding bon r othey
# Use roterc due ear an tduce nsteaf bounditati s atbilittion
# thcoun ely, ts nd tho re ty iter of bor ro factersiul op
# a unattifacaggegs t fini cenner oafte arti revusef f
# forte arore jthin e ino be cor and get theost er or
# Unsiblut mious itivon to before we losehe m centr fo
# vime o var postation ts be thatlso be t theedito
# coried owardf rotatinate e is we a to ause an and the t
# t nd tter of roordi thes andpears ll catesaddsm in tha
# Rou center ol co of ter,s ap s wienerrts rithd for
# - Set cenat al all cen mas cterly guppoalgo neer).
# - Seth th with ther of charat onso sion reatithe
# - suc ened d ofente. ing script alotat a gol e
# happnsteang cacts emovhis r thahe re iss to
# hat es i Usirtif nd rhy tditoent tther thi
# Wplacure.the a ng ais wan eplemsure for
# featite ertiich ave reimnot need
# desp t ins, whTo h to am any
# thashiftt. need. Ie is
# Note to g texill riptther
# massacin we wvascure
# repltes,ed jaot sa)
# deleerat am n(dat ze
# genl (Ienter ta.si
# tooet_cy = 0t| / da
#ef g = cach{|1] cy
d cxta.e+= t[0] ize,
da cx += t[ ta.s es.
cy / da inat
n cx oorda)
} etur to ccy, .
r ion cx, 2) gain
end rotatta, (a / X a
ply te(da:tan(a) | r in
# AprotaMath::sinp{|tnts. shea
def x = Math:a.maonte then
ry = n dater c cx Y,
retur Cent1] - cy r in me).
r # = t[0] - shead aphe eme.
x = t[ X, round , gr graph
y r in y).round erial ach
Shearx * x).roun x, s nd e
# -= (ry * y). (y, arou
x += (rx * ted ] pan
y -= ( updat[3] ne s
x urn 2], ith o
# Ret, t[ xt wfix)
[y, x L te_pre
HTM, id
} k ofdata0] n
d blocock(ata[ ].min
en rate e_bl = d t[1]].mi
Geneneratin_xt| _x, t[0]
# f ge_y, mch{|[min_y,
de minta.eax = [min >\n"
da min_y = ix}\"
min_ x pref
min_y {id_
} x = min_=\"# r_y)
rsor_y = e id{|t| curso
cursor_"<preach y -
cuxt = ort.t < y * (
teata.sx = or_y"\n"
d y, curs += = yin_x
if textor_y = m
cursor_x
curs [3] &" "
= t== "amp;"
end textext = "&= "<
ner_er_text xt =lt;"" ' +
in inner_tr_te= "&= "> '">
if inninneext xt =gt;" SS +_s +
sif er_tr_te= "& x) +_CLA].to
el inninneext rsor_EDIT t[2
sif er_t - cu"' + ix +
el inn (x ass=_pref
d " *n cl+ id low.
en += "<spa="' t + er be
ext '" id_tex numb
t 'nneran>" ial ns.
i</sp+ 1 ser colum
"= x re>" next. by
r_x n</p the airs them
urso + "\ find er p oup
c ext er, numbta) d gr
} rn t numbrialap(das an
retu ial f sewn_my row
nd serst or_dors b
e eacha liursoumbe
For rns te_cal n ]]
# Retuneraseri} |t| ] [t[2
#ef geort = {ach{t[1]] += ]
d # Sumnsrt.emns[t[1] [t[2]
cola.socolumns[ ] = n.
dat if colu t[1] olum 0]]) .
e mns[ ch c [r[ ight
elscolu or ea 1] + he r by
rs f e - to t sortnext
end umbe .siz mber we the
al n r| [1, r l nu o if us
} seri [] |_, ip(r eria s, s get
Add ls =ach{ r.z xt s inateould )
# erians.es += e ners. oordhat w [0]]
solumrial s d th pai n) c1, t ials
c se rial , finmberta) olum by [ser a
n se mberal nup(daw, cials 1] + extr
}etur l nuseriht_ma (ro ser e - one
r eria of _rig with all .siz get
end ch slistrsortartotate [2]}ials . e we ,'
r eas a e_cues snd r t| t ser airs sinc + '"
# Foturnerattuples a. map{|s[1, ue p) ine, o_s
# Re genput tuplbersort.erial valairsnewl 1].t
def# Input numta.sip(s keyal_ping + t[
# inrial= dals.z s asserirail efix
# seals eria pairix, ut t + pr
serirn s mber(prefitho "'
retu l nu_mapies wate. '":
eriarsorentrtempl|t| _s +
end at st_cumap the .map{].to
Formnverate rom airs+ t[0
# f coenerne fal_pfix
de # Gewliseri pre es.
# nurn "' + valu
ret' " nate
"\n ordi
} * f co) a[0]
d ge odata dat
en ranize(_x =
Getet_s minn_x
#ef gn_y,= min_y min 1
d mix_x = mi|t| , x].max y +
max_y ach{t in_x, x].min min_
mata.ex = = [max_x, y].max y -
da y, n_x = [min_y, y]. max_
mix_x = [max_y 1,
man_y = [m n_x +
mix_y - mi
ma x_x
n ma
}etur
r ut
end _inp
loadty? ) a) GLE)) /td>
a = .emp (data(dat -ANNGLE ")}< >
datdatarn nter_size cy,y, A d> r> , "Ltd> }</td
if retu t_ce get cx,x, c /hea "><tdata)}</"R")
= geht = data,a, c le>< ng="4eft_ "M"ta,
end cy heig ate(e(dat /tit addiock(lata,t_da
cx,th, rototat est< ellpe_block(drigh
wid ta = = r te t 1" cerate_bllock(
t_dadata >Rota ng="{generatte_b l>
lefght_ OT" itle pacip">#{gennera labe
ri <<"Ed><t cells="top">##{ge le)</
int <hea "1" align="toop"> "> togg or
prtml> der=t" valignn="t edit to l> errght,
<hody> bor"left" vvalig id="(ESC"><u izes-hei
<bableign="lefft" ox" dit nonet. minimline
<td align=="le heckble elay: tex hat sing
<td allignble>e="c>Enabdisplace . ne tcreap.
<ttd a</ta typdit"yle=" repor. anel he oy deerla
</tr>nputr="e" sters =cursct p ep tis bo ov
<p><il fohelpractmove sele nd keo thes t
<labeid=" chas = ab = s, also d lin
<div SCII keyft+to. "> aluean ae the ;
<li>Arrow shi und riptng vWe ccaus ght)
<li>Aab /+Z = vascpacio. ill tHei
<li>TCtrliv> xt/jaer-sratich wM");; offse
<<li>></d ="te lettect o muId("HT}" / p.
</ul typerentd aspt tontByHEIG dth
ipt iffesireg thalemeINE_ etWi
<scrry de deasin.getE"#{L 2) offs
// To thecrementht = 0.0 - p.
// tut ddocuHeig x += em";ght}
// bp = line= 0; 2; .0; + "{hei
var yle.t_x or =x < 2 = x / #
p.st bes_err 0; cingdth}
var min x = erSpa#{wi
var(var lett.abs( )
for yle.Mathr > e
{ p.ste = erro ; ;
var min_ r = e"em"
if( erro x + t_x;); }";
{ min__x = bes("L"IGHT
best ng =ByIdE_HE
Spaciment{LINt_x;"); T}";
} tteretEle= "# besd("REIGH
e.lent.gight ng =tByINE_H;
} stylcumeneHeSpaciemen#{LIst_x
p.= doe.littergetEl = "= be
p style.leent.eighting
p.stylocumineHrSpac ta))}
p. = dle.lette e; t_da }
p.style.l tate.fals . (lefa))}ata))
p.sty le sit = tion ns. _map(datht_d
p itabe_ed posi itio down_map(rig
/ Wrnabl rsor ; pos rsor_down_map )}
/ar e t cu "M0" rsor e_cursor_down data)
v rrenor = t cu erate_cursor_ eft_)} ))}
/ Cucurs o nex generate_cu ap(lata)_data
/var ng t "L", generat ht_map(dight
appi = map("M", gen _right_map(r
// Mdown rsor_map("R", ursor_right_m
var t_cursor_map( te_cursor_rig
{ nvert_cursor_ nerate_cursor
#{convert_cu , generate_c
#{conver ("L", genera rs.
#{co ht = _map("M", ge ) pai
}; rig ursor_map("R" text
var rt_cursor_map nal
{ onvert_cursor rigi
#{convert_c x, o n))
#{conve uffi . (dow
#{c (id s []; ions tries
}; of ist = osit t.en )
Listdo_l or p bjec ght)
// r un curs of O s(ri
va erse}; ue] ntrie
Rev = { {}; val ct.e
//r upft =[key, Obje
var lenst key; of
var(co e] = lue]
fo valu , va on.
{ up[ [key ey; siti
onst = k e po ;
}or(c alue] . e sam tyle;
f ft[v okes$/; t th = style;
{ le ystr!-~] rs a tyle = style
ed ke /^[ actele) x).style = s
} cepteys = char sty suffix).style
/ AcditK for (id, (1);" + suffix).s
/ar e tyle tyle bstrd("L" + suffi
v et s setS d.sutById("M" +
// Stion = iementById("R .
func uffixetElementByI tion
{ ar sent.getElemen posi
vocument.getEl n. sor
document.g itio s cur . 0";
docum posd) viou tion ff808
d rsoror(i pre posi nd:# ;
} te cuCurs t at rsor ); grou xt])
Updan set ligh""); w cu f80"back erTe
// ctio highor, t ne :#80f = " .inn
fun lear curs ht a oundstyle ion. fix)
{ // Ctyle( hlig ckgrid). osit suf
setS hig "bayId( me p "M" +t;
pdate id;sor,entB at sa yId(= text;
// Usor =(curElem ers entBext = text;
curStyle.get ractxt) ElemnerText = tex
setument cha, te .get).innerText
doc fort(id 1); umentffix).innerT
texteTex str( doc + suffix).in
} lace plac .subfix,("L" + suffix
Repon re = id[sufById("M" + su
//ncti fix ush(mentById("R"
fu r sufst.ptElementById
{ vado_lit.getElement
uncument.getEle
document.ge it. [1];
documen t ed ) ntry[1];
do ecen = 0 t = entry[1];
st r() th = rText = entry
} do moundo leng innerText = e
/ Untion ist. ); ix).innerTex
/func do_l pop( suffix).inne
{ f( un ist. L" + suffix).
i urn; do_l[0];Id("M" + suff
{ ret = unntryntById("R" +
try = elementById("
}ar enffixgetElementBy x);
var suent.getEleme suffi
vdocument.getEit ) ] +
document.e_ed or[0
documnabl curs ";
if( e sor( line
{ tCur "in
se us. lay =
} statt() it; disp
dit _edi e_ed yle. ;
} ge eggle nabl ).st one"
Chann to = !e) elp" = "n
//nctio dit dit ; Id("h play ;
fu le_ele_e sor)ntBy .dis edit
{ enabenab (curleme tyle able_ )
if( rsorgetE ").s = en S}")
{ etCuent. ; help ked CLAS
socum "")yId(" chec DIT_
d sor,entB t"). ("#{E
} e (curElem ("edi Name
els tyle.get ById lass
{ setSment ment sByC {
docu tEle ment =>
t.ge s. etEle ent)
} umen enernt.g (ev
doc listcume ick",
ent f do ("cl
} d ev t o ener ) => {
// Adonst Listedit nt) ) )
for(c ventble_ id); (eve "Z"
{ addE ena r(t. n", y ==
t. if( urso ydow t.ke
{ setC r("ke even
tene ||
} tLis) e" ) = "z"
); Evendit Escap ey =
} .addle_e == " nt.k ) )
} mentenab key (eve "Z"
docuf( ! ent. (); && y ==
i ( ev edit rlKey t.ke
{ if gle_ t.ct even
{ tog even " ||
if( = "z
}lse ; ey =
e do() nt.k
{ un (eve
n; y && s) )
}etur rlKe tKey
r t.ct (edi );
} even match .key
if( (); key. vent
{ undo ent. or, er]); )
( ev curscurso wUp" e" )
} e if ext(ght[ Arro spac
els aceTr(ri == " Back
{ replurso .key ); n" ) == "
setC vent rsor] wDow key
f( e p[cu Arro vent. )
} se i or(u == " || e " "
el Curs .key r]); ft" ==
{ set vent curso owLe .key
f( e own[ "Arr event
} se i or(d y == ; || M"}
el Curs t.ke or]) ght" ": "L"};
{ set even [curs owRi , "R": "
if( left "Arr "L", "R
} lse sor( y == ); "M": "R"
e tCur t.ke sor] "R", "M":;
{ se even t[cur b" ) L": "M", r(1)
if( righ "Ta ? {"L": subst
}lse sor( ey == Key : {"sor.
e tCur nt.k hift cur {
{ se eve ent.s ]] + ) =>
if( = ev or[0 vent
}else ext [curs " ) , (e
{ ar n nextsor); cape ick"
v r = (cur "Es ("cl
ursorsor ey == ener
cetCu nt.k tList
s eve ); Even
} if( dit( (); .add
else le_e fault it")
{ togg ntDe ("ed
reve tById
} nt.p emen
eve etEl();
; nt.gedit
})cumegle_
do tog
; pt> >
})scri html
</ y></
/bod
<OT
E

View File

@ -0,0 +1,3 @@
* Yusuke Endoh
* mame@ruby-lang.org
* cctld: jp

View File

@ -0,0 +1,34 @@
From:pd <pd-@example.com> (`)
Date:Wed,01 Jan 2025 00:00:00 +0000
Subject:[PATCH] +an(/.{40}/));exit].gsub(/X.*X|\n(\h+\s)?\+?/,E=""))#TRICK2025]}
--- /dev/null
+++ pd.rb
@@ -0,0 +1,27 @@
+%;`);;BEGIN{eval$s=%q[eval(%q[F=File;puts((dup)?(q="%;`);;BEGIN
+{eval$s=%q[#$s]}";U,*,V=R=(0..33.0).map{|t|q.gsub(/./){i=$`.siz
+e;c=(i/64*2i-26i+i%64-31)*1i**(t/16.5);x,y=c.rect;r=c.abs;r<13?
+4<=r&&r<6&&x>-4||-5<x&&x<=-3&&-6<y&&y<11??.:?X:$&}};B,A="---|%s
+\n+++|%s\n@@|-%s,%s|+%s,%s|@@\nFrom:pd|<pd-@example.com>|(`)\nD
+ate:%a,%d|%b|%Y|%T|%z\nSubject:[PATCH]|".tr(?|,z="\s")[/@.*\n/]
+,$`;(i=R.index(q))?(S,T=i<33?R[i,(f=->i{(Time.gm(2025)+86400*i)
+.strftime$'};o=f[i+1]+(fXXXXXXXXXXXXXXX[0]+q[/.*\z/]+?\n*2+A%["
+/dev/null",v="pd.rb"]+XXXXXXXXXXXXXXXXXXXB%[0,0,1,27]+U.gsub(/^
+/,?+)).lines[-i-2],EXXXXXXXXXXXXXXXXXXXXXXX,a=A%[v,v];V<<"\n(`\
+n#{a+B%[0,0,1,1]}+dXXXXXXXXXXXXXXXXXXXXXXXXXup=(`)";2)]:($*.siz
+e!=2&&abort(["usagXXXXXXXXX.........XXXXXXXXXe:",$0,F,F]*z);$*.
+map{o=A%$*;F.read(XXXXXXXXX..XXXXXX..XXXXXXXX_1)});a=[i=0]*v=(s
+=[s]+S.lines).sizeXXXXXXXXX..XXXXXX..XXXXXXXX;c=b=s.map{c=_1&&[
+c,?-+_1,i+=1]||0};XXXXXXXXX..XXXXXX..XXXXXXXXT.lines{|t|s.map{|
+s|a<<((s)?[x=a[-1]XXXXXXXXX.........XXXXXXXXX,y=a[-v]].max+((f=
+s==t)?1:0):0);c,d=(XXXXXXXX..XXXXXXXXXXXXXXXf)?[v+1,z+t]:s&&(x>
+y)?[1,?-+s]:[v,?++t]XXXXXXX..XXXXXXXXXXXXXX;b<<[b[-c],d,i+=1]}}
+;c=b[-1].flatten;b=c[(XXXXX..XXXXXXXXXXXX1..)%2];(b.map{_1[0]}*
+E).scan(/\s{,3}([-+]\s{,XXXXXXXXXXXXXXX6})*[-+]\s{,3}/){n=c[2*i
+=$`.size];o=o,B%[n%v+1-1/v,(m=c[2.*i+j=$&.size]-n)%v,T>""?n/v+1
+:0,m/v],b[i,j]}):(o=[];a,b=[A,B].map{_1.sub(?+){'\+'}%(['(\S+)'
+]*4)};$<.read=~//;F.write$2,(s=F.readlines$1;o<<[:patching,F,$2
+]*z;(*,n,i,m=[*$~].map{_1.to_i};n+=m;($'=~/\A((-)|\+)?(.*\n)/;$
+2?s[i-=1,1]=[]:$1?s[i-1,0]=$3:n-=1;i+=1;n-=1)while+n>0)while/\A
+#{b}/=~$';s*E)while$'=~/^#{a}/);o):([*[?l]*799,1].shuffle*E).sc
+an(/.{40}/));exit].gsub(/X.*X|\n(\h+\s)?\+?/,E=""))#TRICK2025]}

View File

@ -0,0 +1,141 @@
# A Lesser "Patch" Program
This program is a minimalistic version of the traditional "patch" command, which looks like a patch.
## Usage as a "Patch" Command
The program reads a unified diff file from standard input and applies the changes to the specified files.
To apply `test.patch` to `sample.rb`, use the following commands:
```
$ cp sample.orig.rb sample.rb
$ ruby entry.rb < test.patch
```
After running these commands, verify that `sample.rb` has been modified.
## Usage as a Patch File
Interestingly, this program is not just a patch-like tools -- it *is* a patch.
This duality allows it to be applied like a regular patch file.
The following will create a file named pd.rb.
```
$ patch < entry.rb
```
Alternatively, you can achieve the same result using `entry.rb`:
```
$ ruby entry.rb < entry.rb
```
The generated `pd.rb` produces a new patch.
```
$ ruby pd.rb
```
The produced patch is self-referential, targeting `pd.rb` itself.
To apply it:
```
$ ruby pd.rb | ruby entry.rb
```
You'll notice the `p` logo rotates slightly counterclockwise.
The modified `pd.rb` outputs the patch for itself again, apply the patch repeatedly--a total of 33 times!
## From `p` to `d`
The center `p` logo symbolizes a "patch."
When rotated 180 degrees, it resembles a `d`, signifying a transformation in functionality.
`pd.rb` now operates as a simplified "diff" command:
```
$ ruby pd.rb
usage: pd.rb File File
$ ruby pd.rb sample.orig.rb sample.rb
--- sample.orig.rb
+++ sample.rb
...
```
## Integration with Git
The patches are compatible with Git's `git am` command, which imports patches in mbox format.
Start fresh by removing `pd.rb` and initializing a Git repository:
```
$ rm -f pd.rb
$ git init
Initialized empty Git repository in /home/...
```
And import `entry.rb` as a patch to the repository:
```
$ git am --committer-date-is-author-date entry.rb
Applying: +(/.{40}/));exit].gsub(/X.*X|\n(\h+\s)?\+?/,E=""))#_TRICK2025_]}
applying to an empty history
```
Verify the commit history:
```
$ git log
commit 1e32693f11c1df77bd797c7b3e9f108a3e139824 (HEAD -> main)
Author: pd (`) <pd-@example.com>
Date: Wed Jan 1 00:00:00 2025 +0000
+an(/.{40}/));exit].gsub(/X.*X|\n(\h+\s)?\+?/,E=""))#TRICK2025]}
```
Notice that the Author and Date are properly set.
To apply subsequent patches:
```
$ for i in `seq 0 32`; do ruby pd.rb | git am --committer-date-is-author-date; done
```
*(A fun details: you will see the `b` logo!)*
Now, view a commit history by the following command:
```
$ git log --oneline
```
You will rediscover the original `entry.rb` unexpectedly.
If you set `--committer-date-is-author-date` appropriately, you should be able to run the output of `git log --oneline` as is.
Try this unusual command:
```
$ git log --oneline | ruby - test.patch
```
## A Little Something Extra
Interestingly, `pd.rb` -- functioning as a diff command -- is a patch to itself.
Reveal hidden details with:
```
$ ruby entry.rb pd.rb
$ ruby pd.rb
```
Can you spot the difference?
## Limitations
* I tested it with ruby 3.3.6, git 2.45.2, and GNU patch 2.7.6.
* No error check at all. The lesser patch do not care if there is a discrepancy between what is written in the patch and the input file, and will write over the existing file without prompt.
* It is assumed that the text files have a new line at the end.

View File

@ -0,0 +1,8 @@
def add(a, b)
a + b
end
if __FILE__ == $0
result = add(3, 5)
puts "Three plus five is #{ result }"
end

View File

@ -0,0 +1,16 @@
--- sample.rb
+++ sample.rb
@@ -2,7 +2,13 @@
a + b
end
+def sub(a, b)
+ a - b
+end
+
if __FILE__ == $0
result = add(3, 5)
puts "Three plus five is #{ result }"
+ result = sub(5, 3)
+ puts "five minus three is #{ result }"
end

View File

@ -0,0 +1,3 @@
* Tomoya Ishida (tompng)
* tomoyapenguin@gmail.com
* cctld: jp

View File

@ -0,0 +1,74 @@
eval->{%w[u=*? a..?i;l=*?j..? r;o=*?s..?z,?_
;m='#-*&|^`!@$ '.chars;s=[[3] ,[0,1,3,4,6],[
1,5],[1,4],[0, 4,6],[2,4],[2] ,[1,3,4,6],[],
[4], ];a= (0.. 7).m ap{[
?;*_ 1+'a 4',: a1,? x*(_
1+2) ]*"T /#{? x.*6 7-_1
}/x; "};v =([c =[?x *150
]*4, a.reverse,[[6, 3,0].map{"a#{_
1}T/ #{?x*15}/x"}*( ?;*42)+';xx']*
30,a .map{_1.tr'14' ,'25'},c,]*n=$
/).g sub( /(^| ;)(;
*);/ ){$1 +?x* $2.s
ize+ ?;}; p,e= [0,1
].ma p{|t |g=( ["(m
fT/' /;#{a=(0..9).m ap{"f#{_1}T/l#
{_1} =1./"}*?;};C"' ;#{a.tr'l',?u}
;?C" ",(0..9).map{| i|a="l#{i}T/'/
;C"' ;";b ="#{o[i-1]+?=i fTi>0}%+";(1..
9).m ap{a <<l[_1-1]+"T/% #{c=m[_1]}/;";
b<<c +";# {(d=_1+i)>10?' ca='+o[d-11]:d
>9?' ca': o[d- 1]}=
%"+c };a+ b+[m [1..
],?+ ,?"] *';? '},"
caT/ '/;C "';" +(1.
.8).map{u[8-_1 ]+"T/#{u[9-_1] }=1./;"}*''+u[
0]+h='=1;?"',( 1..9).map{|i|" u#{i}T/'/;C"';
"+(0..8-i).map {u[8-i-_1]+"T/ #{u[8-_1]}=1./
;"}* ''+u [i-1 ]+h}
]*?; ).sp lit( /([^
;]+; )/); ((0. .43)
.map {|y| c='' ;q=-
>{a= (y-22).abs;b=( c.size+_1-78).
abs; [a<7&&b<59||b< 15,(b-30).abs<
14][ t]};110.times{ c+=q[8]?g.shif
t||? ;:q[-t]??;:'T' };c.gsub(';T',
'TT' ).rstrip}*n).g sub(/(;|T)(;;+
)(;| $)/){$1+'/'+?x *($2.size-2)+'
/'+$ 3}}; F=Fi
le;1 0.ti mes{
|i|a ="(n fT/m
f=l# {i}= '/;n
f=f# {i}=?';def/("+ s[i].map!{"a#{
_1}" }*','+')=(';F. write"#{i}",a+
?x*( 150-a.size)+n+ v[..-5]+'))&&'
+n}; a,*b ="/)
&&de f((C nCn<
<A"; c=") )./(
";d= 'T}' ,?A,
'__= <<B';u.map{|v| b<<v+"TT%(T<<#
{v}T )TT";d=d,v,"AC n#{v}=<<B"};o.
zip( l,m){a+=?;+_1+ "T/%#{_3}/";c+
=(_3[?#]||?#+_
3)+"))./("+_2+
?,};F.write'+'
,n*2 6+[p [..-
10]+ (a+c ).tr ('!@',%("')).g
sub( /%([ '"`] )/,){$1},'#{TT
T'+b *';T T'+d *n,?B,')=']*n+
n;a, b=[u ,o].map{|v|(0.
.8). map{ t=s[9-_1];t[0]
&&t+ =[1] ;v[8-_1]+"T/#{
t*?= }#/" }*?; +';a3='+?x*25}
;F.w rite '=', [n*26]*2*e+a+n
+v+n +(b+ n+v) .tr(?a,?b)[..-
9]+' )if~ exit
'+n].join.tr('
TRICK',_1)}[+"
\x2025"<<-?\\]

View File

@ -0,0 +1,146 @@
### Remarks
Run it with no argument. It will generate 12 files: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + and =.
```sh
ruby entry.rb
```
Concat and syntax highlight them.
```sh
cat 2 0 + 2 5 = | ruby -run -e colorize
cat 4 + 1 5 + 4 + 1 8 = | ruby -run -e colorize
```
I confirmed the following implementations/platforms:
* ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +YJIT +MN +PRISM [arm64-darwin22]
* ruby 3.3.0 (2023-12-25 revision 5124f9ac75) +YJIT +MN [arm64-darwin22]
### Description
Did you know that Ruby syntax can perform additive operations on two-digit numbers without Ruby runtime? This entry demonstrates a syntax level computation of Ruby grammar.
`ruby entry.rb` will generate 12 files: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, + and =.
These files constitute a calculator system that runs on Ruby parser.
To calculate `6 + 7`, concat `6`, `+`, `7` and `=`.
```sh
cat 6 + 7 =
```
The concatenated output is a Ruby script that does nothing. It is also an ASCII art of `█ + █ = ██` rotated 90 degrees.
Now, let's try syntax highlighting that code.
```sh
cat 6 + 7 = | ruby -run -e colorize
```
Wow! You can see the calculation result `6 + 7 = 13` as a colorized ASCII art!
This system can also add more than two numbers. All numbers should be one or two digits, and the answer should be less than 100.
```sh
cat 3 1 + 4 + 1 5 + 9 = | ruby -run -e colorize
cat 1 + 2 + 4 + 8 + 1 6 + 3 2 = | ruby -run -e colorize
cat 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 1 0 = | ruby -run -e colorize
```
If the syntax highlighting is hard to see, use this command to change the terminal color.
```sh
printf "\e]11;#000000\a\e]10;#333333\a\e]4;1;#ffaaaa\a"
```
### Internals
To perform calculation, you need a storage and a control flow statement.
Local variable existence can be used as a storage.
Ruby syntax provides conditional local variable definition and local variable reset with state carry over which can be used as a control flow statement.
#### Conditional Local Variable Definition
Ruby syntax can define new local variables conditionally.
```ruby
# Defines x and y if a is defined
a /x = y = 1./
# Defines x and y if a is not defined
a /1#/; x = y = 1
# Defines x or y depend on the existence of local variable a
a /(x=1);'/;(y=1);?'
```
#### Local Variables Reset
Local variables can be cleared by creating a new `def` scope.
```ruby
x = y = z = 1
def f
# x, y, z are cleared
```
#### State Carry Over
Some state should be carried over to the next `def` scope. There are two tricks to do it.
```ruby
a /%+/i; b /%-/i; def f(x)# +; def f(y) # -; def f(z)
```
```ruby
a %(<<A); b %(<<B); def f
x=<<C
A
y=<<C
B
z=<<C
C
```
In both examples above, local variable defined in the new scope will be:
```ruby
x # if both a and b are not defined
y # if a is defined
z # if b is defined
```
Combining these two tricks, Ruby syntax can carry over two states to the next `def` scope. In this system, two states represents upper digit and lower digit.
### File Structure
```ruby
# File 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
(code) &&
```
```ruby
# File +
(code) && def f(arg)=
```
```ruby
# File =
(code) if exit
```
```ruby
# cat 1 2 + 3 + 4 5 =
(one) &&
(two) &&
(plus) && def f(arg)=
(three) &&
(plus) && def f(arg)=
(four) &&
(five) &&
(equal) if exit
```
### Limitation
Number to be added must be one or two digits.
Answer of the addition must be less than 100.

View File

@ -0,0 +1,3 @@
* Tomoya Ishida (tompng)
* tomoyapenguin@gmail.com
* cctld: jp

View File

@ -0,0 +1,36 @@
$c=%q@E="
\e[4%d;37m%s\e[m"
;n=32.chr;pu ts"\e
[H\e[J#{$c=n*54+' $c=%
q'+[64.chr]*2*$c+';e val$
c.'+n*10+"\n"+n*57+"spl it*'
'"+n*15}";n=l=0;R=->y=0 {n+=1
;l=$c.lines. map{|m|m=(0..79).chunk{380-n+
36*Math.sin(0.04.*it-n )<9*y}.map{a=_2.map{m[it]}*''
;_1&&E%[6,a]||a}*'';m!=l[~-y +=1]&&$><<"\e[#{y}H#{m}\e[37H
";m}};N=(Integer$* [-1]resc ue+30)*H=44100;alias:r:rand
;F=->e,w=1{a=b=c=0;d=( 1-e)**0 .5*20;->v=r-0.5{a=a*w*e+v
;b=b*w*e*e+v;d.*a-2*b+c=c*w *e**3+ v}};A=->u,n,t{(0..n).
map{|i|u=u.shuffle.map{|w|R[]; a=u.s ample;b,c,d=[[0.5
,(0.2+r)*H/3*1.1**i,[[1+r/10,1+r/ 10]][ i]||[1.2+
r/10,1.3+r/5]],[0.3,r*H/2,[1,1+r/5 ]]][t
];e,f=d.shuffle;g=b+r;h=b+r;(0..[w. size/e, a.size/f
+c].max).map{g*(w[it*e]||0)+h*(a[[it-c,0].ma x*f]||0)}}}};j=A[A
[(0..9).map{a=F[0.998,1i**0.02];(0..28097).m ap{a[].real.*0.1**(8.0*i
t/H)-8e-6}},14,0].transpose.map{|d|a=[0]*3e3 ;15.times{|i|R [];b=r
(3e3);d[i].each_with_index{a[c=_2+b]=(a[c] ||0)+_1*0.63**i}} ;a},9,
1][4..].flatten(1).shuffle;y=(0..3).map{F[ 1-1e-5]};m=[-1,1].map {[F[1
-1e-4],F[1-5e-5],it]};u=v=w=0;k=[],[],[] ;z=F[0.7,1i**0.5];File.o pen($
*.grep(/[^\d]/)[0]||'output.wav','wb') {|f|f<<'RIFF'+[N*4+36,'WA VEfmt
',32,16,1,2,H,H*4,4,16,'data',N*4].p ack('Va7cVvvVVvva4V');N.tim es{|
i|$><<E%[4,?#]if(i+1)*80/N!=i*80 /N;t=[i/1e5,(N-i)/2e5,1].min;a,b,c=k
.map{it.shift||(j[20*r,0]=[g =j.pop];a=1+r/3;it[0..]=(0..g.size).m
ap{g[it*a]||0};0)};u=u *0.96+r-0.5;v=v*0.99+d=r-0.5;w=w*0.8+d
;x=(z[].*1+0 .59i).imag;e=y.map(&:[]);f.<<m.map{|o,
p,q|r=a+(b+c)/2+(b-c)*q/5;s=o[r.abs]
;r=t*t*(3-2*t)*(r+s*w/1e4+p[s]*x/1
e7+[[u,0],[v,1]].sum{_1*1.5**(e[
_2]+q*e[_2+2]/9)}/32)/9;r/(1
+r*r)**0.5*32768}.pack'v
*'}};puts@;eval$c.
split*''

View File

@ -0,0 +1,43 @@
# Seashore - Nature Sound
Listen to the relaxing sound of ocean waves generated by Ruby.
## Usage
```sh
ruby entry.rb
ruby entry.rb seashore.wav 60
```
The default filename is `output.wav` and the default duration is 30 seconds.
Tested with ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +YJIT +MN +PRISM [arm64-darwin22]
## Noise
Noise sound is created by applying low-pass/band-pass filter to a white noise signal.
Volume of the noise should change over time. This is also calculated by using low-pass filter.
## Wave
Sound of a single ocean wave is composed of hundreds of water splash sounds.
Each water splash sound is composed of thousands of water drops and bubbles.
This program creates this complicated sound by repeating sound mixing.
```ruby
sound2 = mix(sound1.change_pitch(rand), sound1.change_pitch(rand).delay(rand))
sound4 = mix(sound2.change_pitch(rand), sound2.change_pitch(rand).delay(rand))
...
sound32768 = mix(sound16384.change_pitch(rand), sound16384.change_pitch(rand).delay(rand))
splash1 = mix(sound1.delay(rand), sound2.delay(rand), sound4.delay(rand), ..., sound16384.delay(rand))
splash2 = mix(splash1.change_pitch(rand), splash1.change_pitch(rand).delay(rand))
splash4 = mix(splash2.change_pitch(rand), splash2.change_pitch(rand).delay(rand))
...
splash1024 = mix(splash512.change_pitch(rand), splash512.change_pitch(rand).delay(rand))
wave_sound = [splash32, splash64, ..., splash1024].sample
```
This kind of repetition is often used in fractal rendering. In other words, this operation is rendering a fractal shape to the spectrogram canvas.
It's an efficient way to create complex structure with low computational cost.

View File

@ -0,0 +1,3 @@
* Tomoya Ishida (tompng)
* tomoyapenguin@gmail.com
* cctld: jp

View File

@ -0,0 +1,118 @@
module ReadableFizzBuzz
module Chain
end
end
include ReadableFizzBuzz
Chain::Itself = Chain
module Chain::Itself
module Void
A = B = C = D = E = F = G = H = I = J = K = L = M = Void
N = O = P = Q = R = S = T = U = V = W = X = Y = Z = Void
module Set
end
module Put
end
module WriteBack
end
module Not
include Void
end
end
module Off
include Void
end
module Nil
A = B = C = D = E = F = G = H = I = J = K = L = M = Off
N = O = P = Q = R = S = T = U = V = W = X = Y = Z = Off
end
module Next
include Nil
end
module Current
include Nil
Not = Off
Set = Put = Next
WriteBack = Current
end
True = If = Current
On = Next
module On
INT = 1
FIZZ = 'Fizz'
BUZZ = 'Buzz'
PREFIX = '0b'
FORMAT = "%d%s%s\n"
NEXT = __FILE__
end
module Off
INT = 0
FIZZ = BUZZ = nil
PREFIX = '0b1'
FORMAT = "%2$s%3$s\n"
NEXT = '/dev/null'
Not = True
end
module Initial
C = D = True
end
module ReadableFizzBuzz::Chain::Current
include Initial
end
If::C::Set::E = If::E::Set::F = If::F::Set::C = On
If::D::Set::G = If::G::Set::H = If::H::Set::I = If::I::Set::J = If::J::Set::D = On
If::F::Not::J::Not::Set::B = On
If::K::Not::Set::K = On
If::K::WriteBack::L = True
If::L::Not::M::Set::M = On
If::L::M::Not::Put::M = On
If::L::M::WriteBack::N = True
If::N::Not::O::Set::O = On
If::N::O::Not::Put::O = On
If::N::O::WriteBack::P = True
If::P::Not::Q::Set::Q = On
If::P::Q::Not::Put::Q = On
If::P::Q::WriteBack::R = True
If::R::Not::S::Set::S = On
If::R::S::Not::Put::S = On
If::R::S::WriteBack::T = True
If::T::Not::U::Set::U = On
If::T::U::Not::Put::U = On
If::T::U::WriteBack::V = True
If::V::Not::W::Set::W = On
If::V::W::Not::Put::W = On
If::V::W::WriteBack::X = True
If::X::Not::Y::Set::Y = On
If::X::Y::Not::Put::Y = On
If::X::Y::WriteBack::Z = True
If::Z::Not::Set::A = On
end
module Chain::Chain
Current = Chain::Next
end
include Chain
module Chain::Current
NUMBER = A::PREFIX, Y::INT, W::INT, U::INT, S::INT, Q::INT, O::INT, M::INT, K::INT
printf B::FORMAT, NUMBER.join, C::FIZZ, D::BUZZ
load A::NEXT
end

View File

@ -0,0 +1,106 @@
### Remarks
Just run it with no argument:
```sh
ruby entry.rb
```
I confirmed the following implementations/platforms:
- ruby 3.4.1 (2024-12-25 revision 48d4efcb85) +YJIT +MN +PRISM [arm64-darwin22]
- ruby 3.0.0p0 (2020-12-25 revision 95aff21468) [aarch64-linux-musl]
### Description
Readability is important even for a simple fizz buzz program.
These are the major ingredients of a spaghetti that makes program tasty and valuable but unreadable.
- Many class definitions
- Many method definitions
- Many method calls
- Many variables
- Conditional branches
These are what is acceptable for a readable program.
- Many modules: Using only a single module in a program is not good.
- Many constants: Better than magic numbers.
- Module#include: Mixins are what module is for.
- Many file loads: Usually better than loading a large file only once.
- Minimal method calls: Needed for printing output.
This program is doing something slightly difficult in the last few lines: print output and load ruby program.
In contrast, the rest part of this program is extremely simple and easy. Module definition, constant definition and module inclusion. That's all.
### Internals
Called methods
- `Module#include`
- `Array#join`
- `Kernel#printf`
- `Kernel#load`
Deeply nested module chain to avoid constant reassignment
```ruby
10.times do
module Root
module Chain
module X; end
module Y; end
module Z; end
end
end
include Root
module Chain::Chain
# Not a constant reassignment because Chain::Chain is always a new module
X = Chain::Y
Y = Chain::Z
Z = Chain::X
end
include Chain
p x: X, chain: Chain
end
```
Constant allocation
| Constant | Purpose |
| ---------------------- | ----------------------- |
| A | Loop condition |
| B | Format (!Fizz && !Buzz) |
| C, E, F | Fizz rotation |
| D, G, H, I, J | Buzz rotation |
| K, M, O, Q, S, U, W, Y | Iteration bits |
| L, N, P, R, T, V, X, Z | Temporary carry bits |
Instruction sequence with constant lookup magic
```ruby
# B = 1 if A
If::A::Set::B = On
# B = 1 if !A
If::A::Not::Set::B = On
# C = 1 if !A && B
If::A::Not::B::Set::C = On
# C = 1 if !A && !B
If::A::Not::B::Not::Set::C = On
```
Loop with `load __FILE__`
```ruby
# A::NEXT is __FILE__ or '/dev/null'
load A::NEXT
```
### Limitation
Needs `/dev/null`

View File

@ -0,0 +1,16 @@
This directory contains the top-five entries of
the 5th Transcendental Ruby Imbroglio Contest for rubyKaigi (TRICK 2025).
THESE ARE BAD EXAMPLES! You must NOT use them as a sample code.
* 1st: "Most Revolutionary" - Don Yang
* 2nd: "Most Useful" - Yusuke Endoh
* 3rd: "Most Arithmetic" - Tomoya Ishida
* 4th: "Best ASMR" - Tomoya Ishida
* 5th: "Most Maintainable" - Tomoya Ishida
These files are licensed under MIT license.
For the contest outline and other winning entries, see:
https://github.com/tric/trick2025