# بخش اول: انیمیشنها و ابزارهای تعاملی. این سلول را فقط یک بار اجرا کنید؛ همان پخشکنندهی بخش پنجم است که چند نوع صحنهی تازه دارد.
# ============================================================
# پخشکنندهی تعاملی الگوریتمها (Algorithm Player)
# ============================================================
import json, re, hashlib, html as _html, uuid
from IPython.display import HTML
_AP_CSS = r''':host{all:initial;display:block;max-width:900px;margin:8px auto 18px}
*{box-sizing:border-box}
.card{--card:#fff;--panel:#f6f8fb;--bd:#e2e7ef;--tx:#182230;--mut:#6a7688;--acc:#4f46e5;--acc-soft:rgba(79,70,229,.10);
--stage:#fbfcfe;--dot:#dfe4ee;--code-bg:#fafbfd;--hl:rgba(79,70,229,.12);--ln:#a3adbd;--sh:0 1px 2px rgba(16,24,40,.06),0 14px 30px -18px rgba(16,24,40,.28);
--sb:rgba(100,116,139,.45);--sb-h:rgba(79,70,229,.65);color-scheme:light;--i-bg:#eef2ff;--i-bd:#98a6cf;--i-tx:#182230;--out-bg:#f6f8fa;--out-fg:#116329;--out-bd:#d0d7de;
--cur-bg:#fde68a;--cur-bd:#d9a20a;--cur-tx:#4a3200;--cur-gl:rgba(250,204,21,.38);
--cmp-bg:#fbcfe8;--cmp-bd:#e07bb0;--cmp-tx:#4a1230;--cmp-gl:rgba(236,72,153,.28);
--ok-bg:#bbf7d0;--ok-bd:#2fa863;--ok-tx:#0a3d1f;--ok-gl:rgba(34,197,94,.30);
--sorted-bg:#bfdbfe;--sorted-bd:#4f8ad9;--sorted-tx:#0f2a52;
--min-bg:#fecaca;--min-bd:#e05a5a;--min-tx:#501414;--min-gl:rgba(239,68,68,.28);
--key-bg:#ddd6fe;--key-bd:#7c5be0;--key-tx:#26155a;--key-gl:rgba(139,92,246,.30);
--dim-bg:#f0f2f6;--dim-bd:#d3d9e3;--dim-tx:#9aa4b3;
--vis-bg:#e0f2fe;--vis-bd:#7db9de;--vis-tx:#123a55;
--row-bg:#dbeafe;--row-bd:#8fb4ea;--col-bg:#fef3c7;--col-bd:#e6c66a;--rc-bg:#fdba74;--rc-bd:#e08a2c;
--k-kw:#cf222e;--k-ty:#0550ae;--k-num:#0550ae;--k-str:#0a3069;--k-cm:#6e7781;--k-fn:#8250df;--k-pp:#953800;--k-tx:#1f2328;
position:relative;font:14px/1.5 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:var(--tx);background:var(--card);
border:1px solid var(--bd);border-radius:16px;box-shadow:var(--sh);overflow:hidden;direction:ltr;text-align:left;outline:none;transition:background .3s,border-color .3s,color .3s}
.card[data-theme=dark]{--card:#0f1522;--panel:#141b2b;--bd:#242e45;--tx:#e5eaf4;--mut:#8b97ae;--acc:#8b93ff;--acc-soft:rgba(139,147,255,.14);
--stage:#0c111d;--dot:#1a2236;--code-bg:#0c111c;--hl:rgba(139,147,255,.16);--ln:#4a5670;--sh:0 1px 2px rgba(0,0,0,.4),0 18px 36px -18px rgba(0,0,0,.7);
--sb:rgba(148,163,184,.32);--sb-h:rgba(139,147,255,.7);color-scheme:dark;--i-bg:#1a2238;--i-bd:#3c4b74;--i-tx:#e5eaf4;--out-bg:#0a0f1a;--out-fg:#7ee787;--out-bd:#1d2740;
--cur-bg:#6b4c06;--cur-bd:#f0b429;--cur-tx:#ffe9a8;--cur-gl:rgba(240,180,41,.30);
--cmp-bg:#5a1d42;--cmp-bd:#e879b9;--cmp-tx:#ffd6ec;--cmp-gl:rgba(232,121,185,.28);
--ok-bg:#14532d;--ok-bd:#4ade80;--ok-tx:#d9fbe4;--ok-gl:rgba(74,222,128,.26);
--sorted-bg:#1e3a6e;--sorted-bd:#60a5fa;--sorted-tx:#dbeafe;
--min-bg:#6b1d1d;--min-bd:#f87171;--min-tx:#fee2e2;--min-gl:rgba(248,113,113,.28);
--key-bg:#43307a;--key-bd:#a78bfa;--key-tx:#ede9fe;--key-gl:rgba(167,139,250,.30);
--dim-bg:#121826;--dim-bd:#252f45;--dim-tx:#566178;
--vis-bg:#10324a;--vis-bd:#38a9d8;--vis-tx:#d3f0ff;
--row-bg:#16305a;--row-bd:#3d68a8;--col-bg:#4a3a0c;--col-bd:#a9852a;--rc-bg:#6b430f;--rc-bd:#d18a2e;
--k-kw:#ff7b72;--k-ty:#79c0ff;--k-num:#79c0ff;--k-str:#a5d6ff;--k-cm:#8b949e;--k-fn:#d2a8ff;--k-pp:#ffa657;--k-tx:#e6edf3}
.card:focus-visible{box-shadow:0 0 0 3px var(--acc-soft),var(--sh);border-color:var(--acc)}
.hr{display:flex;align-items:center;gap:10px;flex:none}
.btn.fsb{width:30px;height:30px;border-radius:9px}
.btn.fsb svg{width:15px;height:15px}
:host(.ap-full){max-width:none;margin:0;width:100%;height:100%;background:var(--fs-bg,#fff)}
:host(.ap-pseudo){position:fixed;inset:0;z-index:2147483000;width:100vw;height:100vh}
.card.full{height:100%;border-radius:0;border:0;display:flex;flex-direction:column}
.card.full .stage{flex:none;display:flex;align-items:center;justify-content:center}
.card.full .split{flex:1;min-height:0}
.card.full .codep{display:flex;flex-direction:column;min-height:0}
.card.full .cwrap{flex:1;min-height:0}
.card.full .cbody{max-height:none;height:100%}
.card.full .info{overflow:auto;min-height:0}
.hd{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 16px;border-bottom:1px solid var(--bd);
background:linear-gradient(180deg,var(--panel),var(--card))}
.ttl{display:flex;align-items:center;gap:10px;min-width:0}
.dot{flex:none;width:10px;height:10px;border-radius:50%;background:var(--acc);box-shadow:0 0 0 4px var(--acc-soft)}
.tt{font-weight:700;font-size:15px;letter-spacing:.01em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.bdg{flex:none;font:600 10.5px/1 'JetBrains Mono',ui-monospace,Consolas,monospace;letter-spacing:.08em;color:var(--acc);
background:var(--acc-soft);padding:6px 10px;border-radius:999px;text-transform:uppercase}
.stage{position:relative;overflow:hidden;background-color:var(--stage);background-image:radial-gradient(var(--dot) 1px,transparent 1.3px);background-size:18px 18px;border-bottom:1px solid var(--bd)}
.it{position:absolute;left:0;top:0;display:flex;align-items:center;justify-content:center;border:2px solid var(--i-bd);background:var(--i-bg);color:var(--i-tx);
border-radius:12px;font-family:'JetBrains Mono',ui-monospace,Consolas,monospace;font-weight:700;line-height:1;z-index:2;
box-shadow:0 1px 0 rgba(0,0,0,.05),0 8px 14px -10px rgba(15,23,42,.45);transition:background-color .28s,border-color .28s,color .28s,box-shadow .28s;will-change:transform}
.it[data-c=cur]{background:var(--cur-bg);border-color:var(--cur-bd);color:var(--cur-tx);box-shadow:0 0 0 5px var(--cur-gl);z-index:4}
.it[data-c=cmp]{background:var(--cmp-bg);border-color:var(--cmp-bd);color:var(--cmp-tx);box-shadow:0 0 0 5px var(--cmp-gl);z-index:4}
.it[data-c=ok]{background:var(--ok-bg);border-color:var(--ok-bd);color:var(--ok-tx);box-shadow:0 0 0 5px var(--ok-gl);z-index:4}
.it[data-c=min]{background:var(--min-bg);border-color:var(--min-bd);color:var(--min-tx);box-shadow:0 0 0 5px var(--min-gl);z-index:3}
.it[data-c=key]{background:var(--key-bg);border-color:var(--key-bd);color:var(--key-tx);box-shadow:0 0 0 5px var(--key-gl),0 14px 18px -10px rgba(76,29,149,.5);z-index:5}
.it[data-c=sorted]{background:var(--sorted-bg);border-color:var(--sorted-bd);color:var(--sorted-tx)}
.it[data-c=vis]{background:var(--vis-bg);border-color:var(--vis-bd);color:var(--vis-tx)}
.it[data-c=dim]{background:var(--dim-bg);border-color:var(--dim-bd);color:var(--dim-tx);box-shadow:none}
.it[data-c=row]{background:var(--row-bg);border-color:var(--row-bd)}
.it[data-c=col]{background:var(--col-bg);border-color:var(--col-bd);color:var(--cur-tx)}
.card[data-theme=dark] .it[data-c=col]{color:#ffeaa7}
.it[data-c=rc]{background:var(--rc-bg);border-color:var(--rc-bd);color:#3a1d00}
.card[data-theme=dark] .it[data-c=rc]{color:#ffe1bd}
.it.nul{border-style:dashed}
.ix{position:absolute;left:0;top:0;text-align:center;font:500 12px/16px 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--mut);z-index:1}
.hdr{position:absolute;left:0;top:0;display:flex;align-items:center;justify-content:center;font:600 11.5px/1 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--mut);
border-radius:8px;transition:background-color .28s,color .28s;z-index:1}
.hdr.on{background:var(--acc-soft);color:var(--acc)}
.win{position:absolute;left:0;top:0;border:2px dashed var(--acc);border-radius:16px;background:var(--acc-soft);opacity:0;z-index:1;
transition:transform .5s cubic-bezier(.4,0,.2,1),width .5s cubic-bezier(.4,0,.2,1),opacity .3s}
.pt{position:absolute;left:0;top:0;width:0;height:0;z-index:6;pointer-events:none;transition:transform .5s cubic-bezier(.4,0,.2,1),opacity .28s;--pc:#6366f1}
.pt.off{opacity:0}
.pin{position:absolute;left:0;top:0;transform:translateX(-50%);display:flex;flex-direction:column;align-items:center}
.ar{width:0;height:0;border-left:6px solid transparent;border-right:6px solid transparent;border-bottom:8px solid var(--pc)}
.lb{margin-top:1px;padding:0 9px;border-radius:999px;background:var(--pc);color:#fff;font:700 12px/20px 'JetBrains Mono',ui-monospace,Consolas,monospace;white-space:nowrap;box-shadow:0 4px 10px -4px var(--pc)}
.pt[data-t=i],.pt[data-t=count]{--pc:#6366f1}.pt[data-t=j]{--pc:#0ea5a4}.pt[data-t=low]{--pc:#16a34a}.pt[data-t=mid]{--pc:#d98a06}
.pt[data-t=high],.pt[data-t=min]{--pc:#e5484d}.pt[data-t=key]{--pc:#8b5cf6}
.card[data-theme=dark] .pt[data-t=i],.card[data-theme=dark] .pt[data-t=count]{--pc:#7c83ff}.card[data-theme=dark] .pt[data-t=j]{--pc:#2dd4bf}
.card[data-theme=dark] .pt[data-t=low]{--pc:#22c55e}.card[data-theme=dark] .pt[data-t=mid]{--pc:#f59e0b}
.card[data-theme=dark] .pt[data-t=high],.card[data-theme=dark] .pt[data-t=min]{--pc:#f87171}.card[data-theme=dark] .pt[data-t=key]{--pc:#a78bfa}
.lg{display:flex;flex-wrap:wrap;gap:6px 16px;padding:9px 16px;border-bottom:1px solid var(--bd);background:var(--card);direction:rtl;font:500 12.5px/1.2 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:var(--mut)}
.lg span{display:inline-flex;align-items:center;gap:6px}
.lg i{width:12px;height:12px;border-radius:4px;border:1.5px solid var(--i-bd);background:var(--i-bg)}
.split{display:grid;grid-template-columns:minmax(0,1.3fr) minmax(0,1fr)}
.card.narrow .split{grid-template-columns:minmax(0,1fr)}
.codep{min-width:0;background:var(--code-bg);border-right:1px solid var(--bd)}
.card.narrow .codep{border-right:0;border-bottom:1px solid var(--bd)}
.card.narrow .cbody{font-size:10.5px}
.chd{display:flex;align-items:center;gap:8px;padding:9px 14px;border-bottom:1px solid var(--bd);font:700 10.5px/1 'JetBrains Mono',ui-monospace,Consolas,monospace;letter-spacing:.1em;color:var(--mut)}
.chd s{width:8px;height:8px;border-radius:50%;background:#ff5f57;text-decoration:none;box-shadow:14px 0 0 #febc2e,28px 0 0 #28c840;margin-right:32px}
.cwrap{position:relative}
.sbt{position:absolute;top:0;right:3px;width:5px;height:100%;pointer-events:none;display:none}
.sbt i{display:block;width:5px;border-radius:99px;background:var(--sb);opacity:.9}
.cbody{position:relative;padding:8px 0 10px;overflow:auto;max-height:300px;overscroll-behavior:contain;font:500 13px/22px 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--k-tx)}
.lines{position:relative;min-width:max-content}
.hl{position:absolute;left:0;right:0;top:0;height:22px;background:var(--hl);border-left:3px solid var(--acc);transition:transform .38s cubic-bezier(.4,0,.2,1),height .38s cubic-bezier(.4,0,.2,1);z-index:0}
.ln{position:relative;display:flex;height:22px;white-space:pre;z-index:1}
.no{flex:none;width:40px;padding-right:12px;text-align:right;color:var(--ln);user-select:none;transition:color .2s}
.tx{flex:1;padding-right:16px}
.ln.on .no{color:var(--acc);font-weight:700}
.k{color:var(--k-kw)}.t{color:var(--k-ty)}.n{color:var(--k-num)}.s{color:var(--k-str)}.c{color:var(--k-cm);font-style:italic}.f{color:var(--k-fn)}.p{color:var(--k-pp)}
.info{min-width:0;display:flex;flex-direction:column;gap:14px;padding:14px 16px;background:var(--card);direction:rtl;text-align:right}
.bt{margin-bottom:8px;font:700 12px/1 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:var(--mut)}
.vars{display:flex;flex-wrap:wrap;gap:8px;direction:rtl;min-height:32px}
.chip{direction:ltr;display:flex;align-items:baseline;gap:7px;padding:5px 11px;border-radius:10px;background:var(--panel);border:1px solid var(--bd);font:600 13px/1.25 'JetBrains Mono',ui-monospace,Consolas,monospace}
.chip b{color:var(--mut);font-weight:600}.chip span{color:var(--tx);font-weight:700;min-width:1ch}
.chip.na{opacity:.45}.chip.chg{animation:pop .7s ease-out}
@keyframes pop{0%{background:var(--acc-soft);border-color:var(--acc);transform:scale(1.07)}100%{transform:scale(1)}}
.note{direction:rtl;text-align:right;min-height:72px;padding:11px 13px;border-radius:12px;background:var(--panel);border:1px solid var(--bd);font:500 13.5px/1.65 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif}
.note.in{animation:rise .35s ease-out}
@keyframes rise{from{opacity:0;transform:translateY(5px)}to{opacity:1;transform:none}}
.note code{font:600 12.5px 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--acc);background:var(--acc-soft);padding:1px 6px;border-radius:6px}
.out{direction:ltr;text-align:left}.out .bt{direction:rtl;text-align:right}.out pre{margin:0;min-height:58px;max-height:150px;overflow:hidden;white-space:pre-wrap;padding:10px 12px;border-radius:12px;background:var(--out-bg);color:var(--out-fg);border:1px solid var(--out-bd);font:500 12.5px/1.6 'JetBrains Mono',ui-monospace,Consolas,monospace;white-space:pre-wrap}
.out pre::after{content:"\2588";margin-left:2px;color:var(--out-fg);animation:blink 1s steps(1) infinite}
@keyframes blink{50%{opacity:0}}
.ctl{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:11px 14px;border-top:1px solid var(--bd);background:var(--panel)}
.bts{display:flex;align-items:center;gap:6px}
.btn{display:grid;place-items:center;width:34px;height:34px;padding:0;border-radius:10px;border:1px solid var(--bd);background:var(--card);color:var(--tx);cursor:pointer;transition:background .15s,border-color .15s,color .15s,transform .1s}
.btn:hover{background:var(--acc-soft);border-color:var(--acc);color:var(--acc)}
.btn:active{transform:scale(.94)}.btn:disabled{opacity:.35;cursor:default}
.btn:focus-visible{outline:2px solid var(--acc);outline-offset:2px}
.btn svg{width:16px;height:16px;fill:currentColor}
.btn.play{width:42px;height:42px;border-radius:50%;background:var(--acc);border-color:var(--acc);color:#fff;box-shadow:0 8px 16px -8px var(--acc)}
.btn.play:hover{filter:brightness(1.08);color:#fff}
.btn.play svg{width:18px;height:18px}
.btn.on{background:var(--acc-soft);border-color:var(--acc);color:var(--acc)}
.sl{flex:1;min-width:120px;height:22px;margin:0;background:transparent;-webkit-appearance:none;appearance:none;cursor:pointer;--p:0%}
.sl::-webkit-slider-runnable-track{height:6px;border-radius:99px;background:linear-gradient(to right,var(--acc) var(--p),var(--bd) var(--p))}
.sl::-moz-range-track{height:6px;border-radius:99px;background:var(--bd)}
.sl::-moz-range-progress{height:6px;border-radius:99px;background:var(--acc)}
.sl::-webkit-slider-thumb{-webkit-appearance:none;width:16px;height:16px;margin-top:-5px;border-radius:50%;background:#fff;border:3px solid var(--acc);box-shadow:0 2px 6px rgba(0,0,0,.25)}
.sl::-moz-range-thumb{width:12px;height:12px;border-radius:50%;background:#fff;border:3px solid var(--acc)}
.sl:focus-visible{outline:2px solid var(--acc);outline-offset:3px;border-radius:6px}
.cnt{flex:none;min-width:58px;text-align:center;font:700 12px/1 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--mut)}
.spd{flex:none;height:34px;padding:0 8px;border-radius:10px;border:1px solid var(--bd);background:var(--card);color:var(--tx);font:600 12px 'JetBrains Mono',ui-monospace,Consolas,monospace;cursor:pointer}
.spd:focus-visible{outline:2px solid var(--acc);outline-offset:2px}
.card.narrow .sl{order:5;flex-basis:100%}
@media (prefers-reduced-motion:reduce){.it,.pt,.win,.hl{transition:none!important}.note.in,.chip.chg{animation:none}}
.world{position:relative}.stage{overflow:hidden}
.nt,.nt *{transition:none!important;animation:none!important}
.lg i[data-c=cur]{background:var(--cur-bg);border-color:var(--cur-bd)}.lg i[data-c=cmp]{background:var(--cmp-bg);border-color:var(--cmp-bd)}
.lg i[data-c=ok]{background:var(--ok-bg);border-color:var(--ok-bd)}.lg i[data-c=min]{background:var(--min-bg);border-color:var(--min-bd)}
.lg i[data-c=key]{background:var(--key-bg);border-color:var(--key-bd)}.lg i[data-c=sorted]{background:var(--sorted-bg);border-color:var(--sorted-bd)}
.lg i[data-c=vis]{background:var(--vis-bg);border-color:var(--vis-bd)}.lg i[data-c=dim]{background:var(--dim-bg);border-color:var(--dim-bd)}
.mc{position:absolute;left:0;top:0;display:flex;align-items:center;justify-content:center;border:1.5px solid var(--i-bd);background:var(--i-bg);color:var(--i-tx);border-radius:8px;
font:700 12px 'JetBrains Mono',ui-monospace,Consolas,monospace;transition:background-color .25s,border-color .25s,color .25s,box-shadow .25s}
.mc[data-c=cur]{background:var(--cur-bg);border-color:var(--cur-bd);color:var(--cur-tx);box-shadow:0 0 0 4px var(--cur-gl)}
.mc[data-c=vis]{background:var(--vis-bg);border-color:var(--vis-bd);color:var(--vis-tx)}
.mlab{position:absolute;left:0;top:0;font:600 12px/1 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:var(--mut);direction:rtl;white-space:nowrap}
.mlab code{font:600 11.5px 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--acc)}
.mx{position:absolute;left:0;top:0;text-align:center;font:500 10.5px/14px 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--mut)}
.corner{position:absolute;left:0;top:0;font:600 11px/1 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--mut);opacity:.8}
*{scrollbar-width:none;-ms-overflow-style:none}
*::-webkit-scrollbar{display:none;width:0;height:0}
.sub{position:absolute;left:0;top:0;text-align:center;font:600 11.5px/16px 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--k-fn);z-index:1;white-space:nowrap;transition:color .25s,transform .25s}
.sub.on{color:var(--acc);font-weight:700}
.it[data-c=hid]{opacity:.18;box-shadow:none;border-style:dashed;background:transparent}
.hint{margin-inline-start:auto;font:500 12px 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:var(--mut);direction:rtl}
.cap{padding:13px 18px;border-top:1px solid var(--bd);direction:rtl;text-align:right;font:500 13.5px/1.95 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;background:var(--card)}
.cap code{font:600 12.5px 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--acc);background:var(--acc-soft);padding:1px 6px;border-radius:6px;direction:ltr;unicode-bidi:isolate}
.chartw{background-color:var(--stage);background-image:radial-gradient(var(--dot) 1px,transparent 1.3px);background-size:18px 18px;padding:4px 0 0}
.chartw svg{display:block;max-width:100%;height:auto}
.gl{stroke:var(--bd);stroke-width:1;stroke-dasharray:3 5}
.ax{stroke:var(--mut);stroke-width:1.4}
.tk{fill:var(--mut);font:500 11.5px 'JetBrains Mono',ui-monospace,Consolas,monospace}
.axl{fill:var(--mut);font:600 12px 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif}
.cl-area{fill:url(#gf);opacity:0;transition:opacity 1s ease .9s}
.cl-line{fill:none;stroke:var(--acc);stroke-width:3.2;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:var(--len);stroke-dashoffset:var(--len);transition:stroke-dashoffset 1.5s cubic-bezier(.4,0,.2,1)}
.cl-pt{fill:var(--card);stroke:var(--acc);stroke-width:3;opacity:0;transform-box:fill-box;transform-origin:center;transform:scale(.3)}
.cl-lb{fill:var(--tx);font:700 12px 'JetBrains Mono',ui-monospace,Consolas,monospace;opacity:0}
.run .cl-area{opacity:1}
.run .cl-line{stroke-dashoffset:0}
.run .cl-pt{animation:ptin .42s cubic-bezier(.3,1.4,.5,1) forwards;animation-delay:calc(var(--i)*.13s + .15s)}
.run .cl-lb{animation:lbin .4s ease-out forwards;animation-delay:calc(var(--i)*.13s + .25s)}
@keyframes ptin{from{opacity:0;transform:scale(.3)}to{opacity:1;transform:scale(1)}}
@keyframes lbin{from{opacity:0;transform:translateY(5px)}to{opacity:1;transform:none}}
.sum{display:flex;flex-direction:column;direction:rtl;background:var(--card)}
.srow{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:14px 22px;align-items:center;padding:16px 18px;border-bottom:1px solid var(--bd)}
.sname b{display:block;font:700 15px/1.4 'JetBrains Mono',ui-monospace,Consolas,monospace;direction:ltr;text-align:right}
.sname span{display:block;font:500 11.5px/1.5 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--mut);direction:ltr;text-align:right}
.sarr{display:flex;gap:6px;direction:ltr}
.sbx{flex:1 1 0;min-width:0;max-width:58px;aspect-ratio:1;display:grid;place-items:center;border-radius:11px;border:2px solid var(--sorted-bd);background:var(--sorted-bg);color:var(--sorted-tx);font:700 15px 'JetBrains Mono',ui-monospace,Consolas,monospace;opacity:0;transform:scale(.4)}
.run .sbx{animation:ptin .45s cubic-bezier(.3,1.4,.5,1) forwards;animation-delay:calc(var(--i)*80ms + .1s)}
.smet{display:flex;flex-direction:column;gap:9px}
.m{display:grid;grid-template-columns:4.8rem minmax(24px,1fr) auto auto;gap:8px;align-items:center;font:600 12.5px 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:var(--mut)}
.mt{height:10px;border-radius:99px;background:var(--bd);overflow:hidden;direction:ltr}
.mt i{display:block;height:100%;width:0;border-radius:inherit;transition:width .9s cubic-bezier(.4,0,.2,1) .45s}
.run .mt i{width:var(--w)}
.m[data-k="0"] .mt i{background:var(--cmp-bd)}.m[data-k="1"] .mt i{background:var(--ok-bd)}
.m b{font:700 14px 'JetBrains Mono',ui-monospace,Consolas,monospace;color:var(--tx);min-width:2ch;direction:ltr;text-align:left}
.m em{font-style:normal;font:600 11px 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:var(--mut);background:var(--panel);border:1px solid var(--bd);padding:1px 7px;border-radius:99px;white-space:nowrap;font-size:10.5px}
.nt.run .cl-pt,.nt.run .cl-lb,.nt.run .sbx{opacity:1;transform:none}
.nt.run .cl-line{stroke-dashoffset:0;transition:none}
.nt.run .cl-area{opacity:1}
.nt.run .mt i{width:var(--w)}
.lg i[data-c=hid]{background:transparent;border-style:dashed;opacity:.6}
.vpw{width:100%;padding:12px 10px}
.vpw svg{display:block;margin:0 auto;width:100%;height:auto;max-height:520px;font-family:'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif}
.split.nocode{grid-template-columns:minmax(0,1fr)}
.card.pc .cbody{font:500 13.5px/22px 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;direction:rtl}
.card.pc .lines{min-width:100%}
.card.pc .ln{direction:rtl;white-space:pre}
.card.pc .no{width:38px;padding:0;text-align:center}
.card.pc .tx{direction:rtl;unicode-bidi:embed;padding:0 6px 0 16px}
.card.pc .hl{border-left:none;border-right:3px solid var(--acc)}
.card.pc .codep{border-right:none;border-left:1px solid var(--bd)}
.card.pc .chd{direction:rtl;font-family:'Vazirmatn',system-ui,sans-serif;letter-spacing:0}
.fc-n rect,.fc-n polygon{fill:var(--panel);stroke:var(--i-bd);stroke-width:1.6;transition:fill .3s,stroke .3s}
.fc-n text{fill:var(--tx);font-size:14px;direction:rtl;unicode-bidi:embed;transition:fill .3s}
.fc-n .mono,.mono{font-family:'JetBrains Mono',ui-monospace,Consolas,monospace;direction:ltr;unicode-bidi:normal}
.fc-n.s-cur rect,.fc-n.s-cur polygon{fill:var(--cur-bg);stroke:var(--cur-bd)}
.fc-n.s-cur text{fill:var(--cur-tx)}
.fc-n.s-ok rect,.fc-n.s-ok polygon{fill:var(--ok-bg);stroke:var(--ok-bd)}
.fc-n.s-ok text{fill:var(--ok-tx)}
.fc-n.s-key rect,.fc-n.s-key polygon{fill:var(--key-bg);stroke:var(--key-bd)}
.fc-n.s-key text{fill:var(--key-tx)}
.fc-n.s-vis rect,.fc-n.s-vis polygon{fill:var(--vis-bg);stroke:var(--vis-bd)}
.fc-n.s-vis text{fill:var(--vis-tx)}
.fc-n.s-min rect,.fc-n.s-min polygon{fill:var(--min-bg);stroke:var(--min-bd)}
.fc-n.s-min text{fill:var(--min-tx)}
.fc-n.s-cmp rect,.fc-n.s-cmp polygon{fill:var(--cmp-bg);stroke:var(--cmp-bd)}
.fc-n.s-cmp text{fill:var(--cmp-tx)}
.fc-n.s-dim rect,.fc-n.s-dim polygon{fill:var(--dim-bg);stroke:var(--dim-bd)}
.fc-n.s-dim text{fill:var(--dim-tx)}
.fc-n.col rect{fill:transparent;stroke:transparent}
.fc-n.col.s-cur rect{fill:var(--cur-gl);stroke:var(--cur-bd);stroke-dasharray:5 4}
.fc-n.plain rect{fill:transparent;stroke:var(--bd)}
.fc-e{fill:none;stroke:var(--mut);stroke-width:1.6;marker-end:url(#arr)}
.fc-e.bus{stroke-width:5;stroke-linecap:round;marker-end:none;opacity:.55}
.fc-e.s-on{stroke:var(--acc);stroke-width:2.4;marker-end:url(#arrA)}
.fc-e.s-cur{stroke:var(--cur-bd);stroke-width:3.2;stroke-dasharray:7 5;animation:fcdash .7s linear infinite;marker-end:url(#arrC)}
.fc-e.bus.s-cur{stroke-width:6;opacity:1;marker-end:none}
@keyframes fcdash{to{stroke-dashoffset:-24}}
.mk{fill:var(--mut)}.mkA{fill:var(--acc)}.mkC{fill:var(--cur-bd)}
.fc-lb{fill:var(--mut);font-size:12.5px;font-weight:700;direction:rtl;unicode-bidi:embed}
.fc-tag{fill:var(--mut);font-size:12px;direction:rtl;unicode-bidi:embed}
.fc-n text.fc-tag{fill:var(--mut);font-size:12px}
.fc-n.s-cur text.fc-tag{fill:var(--cur-tx)}
.fc-big{font-size:20px;font-weight:700}
.fc-t text.s-cur,.fc-t.s-cur{fill:var(--cur-tx)}
text.fc-v{font-family:'JetBrains Mono',ui-monospace,Consolas,monospace;direction:ltr;unicode-bidi:normal;fill:var(--tx);font-size:18px;font-weight:700;transition:fill .3s}
text.fc-v.s-cur{fill:var(--cur-bd)}
text.fc-v.s-ok{fill:var(--ok-bd)}
text.fc-v.s-key{fill:var(--key-bd)}
.lg i[data-c=min]{background:var(--min-bg);border-color:var(--min-bd)}
.lg i[data-c=cmp]{background:var(--cmp-bg);border-color:var(--cmp-bd)}
.lg i[data-c=sorted]{background:var(--sorted-bg);border-color:var(--sorted-bd)}
.lg i[data-c=dim]{background:var(--dim-bg);border-color:var(--dim-bd)}
.lg i[data-c=i]{background:var(--i-bg);border-color:var(--i-bd)}
/* ---------- interactive widgets ---------- */
.iw .bd{padding:14px 16px 16px;display:flex;flex-direction:column;gap:14px;direction:rtl;text-align:right;font:500 13.5px/1.6 'Vazirmatn',system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;color:var(--tx)}
.iw .row{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
.iw .lab{color:var(--mut);font-weight:700;font-size:12.5px}
.iw .pill{border:1px solid var(--bd);background:var(--panel);color:var(--tx);border-radius:999px;padding:7px 14px;font:600 13px/1 'Vazirmatn',system-ui,sans-serif;cursor:pointer;transition:border-color .2s,background .2s,color .2s}
.iw .pill:hover{border-color:var(--acc)}
.iw .pill.on{background:var(--acc-soft);border-color:var(--acc);color:var(--acc)}
.iw .pill.act{background:var(--acc);border-color:var(--acc);color:#fff}
.iw .pill:focus-visible,.iw button:focus-visible,.iw input:focus-visible{outline:2px solid var(--acc);outline-offset:2px}
.iw .rd{border:1px solid var(--bd);background:var(--panel);border-radius:12px;padding:10px 12px;min-width:0}
.iw .rd b{display:block;font:700 11.5px/1.3 'Vazirmatn',system-ui,sans-serif;color:var(--mut);margin-bottom:6px}
.iw .rd span.fa{direction:rtl;text-align:right;font-family:'Vazirmatn',system-ui,sans-serif;font-size:15px}
.iw .rd span{display:block;direction:ltr;text-align:left;font:700 17px/1.3 'JetBrains Mono',ui-monospace,Consolas,monospace;overflow-wrap:anywhere}
.iw .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:10px}
.iw .msg{min-height:48px;padding:10px 13px;border-radius:12px;background:var(--panel);border:1px solid var(--bd)}
.iw .msg code,.iw .lab code{direction:ltr;unicode-bidi:isolate;font:600 12.5px 'JetBrains Mono',ui-monospace,monospace;background:var(--acc-soft);padding:1px 6px;border-radius:6px}
.iw .rng{flex:1;min-width:140px;accent-color:var(--acc);direction:ltr}
.iw .sec{font:700 16px 'JetBrains Mono',ui-monospace,monospace;min-width:70px;direction:ltr}
.iw input.txt{flex:1;min-width:160px;border:1px solid var(--bd);background:var(--card);color:var(--tx);border-radius:10px;padding:8px 12px;font:600 15px 'JetBrains Mono','Vazirmatn',ui-monospace,monospace}
.gbar{position:relative;height:50px;border-radius:12px;background:var(--dim-bg);border:1px solid var(--dim-bd);overflow:hidden;direction:ltr}
.grng{position:absolute;top:0;bottom:0;background:var(--vis-bg);border-left:2px solid var(--vis-bd);border-right:2px solid var(--vis-bd);transition:left .45s cubic-bezier(.4,0,.2,1),width .45s cubic-bezier(.4,0,.2,1)}
.gmk{position:absolute;top:0;bottom:0;width:4px;margin-left:-2px;background:var(--cur-bd);box-shadow:0 0 0 4px var(--cur-gl);transition:left .45s cubic-bezier(.4,0,.2,1);opacity:0}
.gsec{position:absolute;top:6px;width:14px;height:14px;margin-left:-7px;border-radius:50%;background:var(--key-bd);border:2px solid var(--card)}
.gscale{direction:ltr;display:flex;justify-content:space-between;font:600 11.5px 'JetBrains Mono',ui-monospace,monospace;color:var(--mut);margin-top:-8px}
.bits{display:flex;direction:ltr;justify-content:center;gap:6px}
.bit{display:flex;flex-direction:column;align-items:center;gap:6px;min-width:0}
.bit .w{font:700 11.5px/1 'JetBrains Mono',ui-monospace,monospace;color:var(--mut);min-height:14px}
.bit .w.neg{color:var(--min-bd)}
.bit button{width:46px;height:56px;max-width:100%;border-radius:12px;border:2px solid var(--i-bd);background:var(--i-bg);color:var(--i-tx);font:700 22px/1 'JetBrains Mono',ui-monospace,monospace;cursor:pointer;transition:background .2s,border-color .2s,box-shadow .2s,transform .12s}
.bit button:active{transform:scale(.94)}
.bit button.on{background:var(--ok-bg);border-color:var(--ok-bd);color:var(--ok-tx);box-shadow:0 0 0 4px var(--ok-gl)}
.bit button.neg.on{background:var(--min-bg);border-color:var(--min-bd);color:var(--min-tx);box-shadow:0 0 0 4px var(--min-gl)}
.bit .ix{font:600 10.5px/1 'JetBrains Mono',ui-monospace,monospace;color:var(--ln)}
.bits .gap{width:12px;flex:none}
.nib{display:flex;direction:ltr;justify-content:center;gap:6px;margin-top:-6px}
.nib div{width:calc(4*46px + 3*6px);max-width:50%;text-align:center;border-top:3px solid var(--acc);padding-top:5px;font:700 13px 'JetBrains Mono',ui-monospace,monospace;color:var(--acc)}
.fbits{display:flex;direction:ltr;flex-wrap:wrap;gap:3px;justify-content:center}
.fg{display:flex;flex-direction:column;align-items:center;gap:5px;padding:7px 8px 8px;border-radius:12px;border:1.5px solid}
.fg.s{background:var(--min-bg);border-color:var(--min-bd)}
.fg.e{background:var(--cur-bg);border-color:var(--cur-bd)}
.fg.m{background:var(--vis-bg);border-color:var(--vis-bd)}
.fg i{font:700 10.5px/1 'Vazirmatn',system-ui,sans-serif;font-style:normal;color:var(--tx)}
.fg .bs{display:flex;gap:3px;flex-wrap:wrap;justify-content:center;max-width:370px}
.fg button{width:22px;height:30px;border-radius:6px;border:1.5px solid var(--i-bd);background:var(--card);color:var(--tx);font:700 13px/1 'JetBrains Mono',ui-monospace,monospace;cursor:pointer;padding:0}
.fg button.on{background:var(--acc);border-color:var(--acc);color:#fff}
.bq{display:flex;flex-wrap:wrap;gap:12px;direction:ltr}
.bc{border:1.5px solid var(--bd);background:var(--panel);border-radius:12px;padding:8px 10px;display:flex;flex-direction:column;gap:6px;align-items:center}
.bc .ch{font:700 22px/1.1 'Vazirmatn','JetBrains Mono',sans-serif;direction:ltr}
.bc .cp{font:600 10.5px/1 'JetBrains Mono',ui-monospace,monospace;color:var(--mut)}
.bc .by{display:flex;gap:6px}
.bc .b{border-radius:8px;padding:5px 8px;text-align:center;font:700 12px/1.35 'JetBrains Mono',ui-monospace,monospace;border:1.5px solid}
.bc .b small{display:block;font-weight:600;font-size:10.5px;opacity:.8}
.bc .b u{text-decoration:none;opacity:.45}
.bc.l1{border-color:var(--vis-bd)}.bc.l1 .b{background:var(--vis-bg);border-color:var(--vis-bd);color:var(--vis-tx)}
.bc.l2{border-color:var(--key-bd)}.bc.l2 .b{background:var(--key-bg);border-color:var(--key-bd);color:var(--key-tx)}
.bc.l3{border-color:var(--cur-bd)}.bc.l3 .b{background:var(--cur-bg);border-color:var(--cur-bd);color:var(--cur-tx)}
.bc.l4{border-color:var(--cmp-bd)}.bc.l4 .b{background:var(--cmp-bg);border-color:var(--cmp-bd);color:var(--cmp-tx)}
@media (max-width:520px){.bit button{width:34px;height:46px;font-size:18px}.nib div{width:calc(4*34px + 3*6px)}.bits{gap:4px}}
'''
_AP_JS = r'''(function(){
if(window.__VPL&&window.__VPL.v==="__VER__")return;
var CSS=__CSS__;
var IC={first:'M18.41 16.59 13.82 12l4.59-4.59L17 6l-6 6 6 6zM6 6h2v12H6z',prev:'M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z',next:'M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z',last:'M5.59 7.41 10.18 12l-4.59 4.59L7 18l6-6-6-6zM16 6h2v12h-2z',play:'M8 5v14l11-7z',pause:'M6 19h4V5H6v14zm8-14v14h4V5h-4z',replay:'M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z',fs:'M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z',fsx:'M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z',loop:'M7 7h10v3l4-4-4-4v3H5v6h2V7zm10 10H7v-3l-4 4 4 4v-3h12v-6h-2v4z'};
function svg(p){return '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="'+p+'"/></svg>'}
function esc(s){return String(s).replace(/[&<>"]/g,function(c){return {'&':'&','<':'<','>':'>','"':'"'}[c]})}
function isDark(){
var d=document.documentElement,b=document.body||d;
if(d.classList.contains('dark'))return true;
if(d.classList.contains('light'))return false;
var th=(d.getAttribute('data-theme')||'')+' '+(b.getAttribute&&b.getAttribute('data-vscode-theme-kind')||'');
if(/dark/i.test(th))return true; if(/light/i.test(th))return false;
var bc=b.className||'';
if(/vscode-high-contrast-light|vscode-light/.test(bc))return false;
if(/vscode-dark|vscode-high-contrast/.test(bc))return true;
if(/\bjp-mod-dark\b|theme-dark/.test(bc))return true;
return !!(window.matchMedia&&matchMedia('(prefers-color-scheme: dark)').matches);
}
var PRI=['i','j','low','mid','high','min','key','count'];
function mount(host,S){
if(host.__ap)return; host.__ap=1;
var root=host.attachShadow?host.attachShadow({mode:'open'}):host;
var F=S.frames,N=F.length,isGrid=!!S.grid,n=S.n,LH=22;
var codeH='';for(var q=0;q<S.code.length;q++)codeH+='<div class="ln"><span class="no">'+(q+1)+'</span><span class="tx">'+S.code[q]+'</span></div>';
var lg='';S.legend.forEach(function(l){lg+='<span><i data-c="'+l[0]+'"></i>'+l[1]+'</span>'});
var btn=function(id,ic,label,cls){return '<button class="btn '+(cls||'')+'" data-a="'+id+'" aria-label="'+label+'" title="'+label+'">'+svg(ic)+'</button>'};
root.innerHTML='<style>'+CSS+'</style><div class="card nt" tabindex="0" role="group" aria-label="'+esc(S.title)+'">'+
'<div class="hd"><div class="ttl"><i class="dot"></i><span class="tt">'+esc(S.title)+'</span></div><div class="hr"><span class="bdg">'+esc(S.badge||'Interactive')+'</span>'+btn('fs',IC.fs,'تمامصفحه','fsb')+'</div></div>'+
'<div class="stage"><div class="world"></div></div>'+
'<div class="lg">'+lg+'</div>'+
'<div class="split"><div class="codep"><div class="chd"><s></s>'+esc(S.codeTitle)+'</div><div class="cwrap"><div class="cbody"><div class="lines"><div class="hl"></div>'+codeH+'</div></div><div class="sbt"><i></i></div></div></div>'+
'<div class="info"><div><div class="bt">متغیرها</div><div class="vars"></div></div>'+
'<div><div class="bt">این مرحله چه میکند؟</div><div class="note" aria-live="polite"></div></div>'+
(S.showOut?'<div class="out"><div class="bt">خروجی برنامه</div><pre></pre></div>':'')+'</div></div>'+
'<div class="ctl"><div class="bts">'+btn('first',IC.first,'اول')+btn('prev',IC.prev,'قبلی')+btn('play',IC.play,'پخش','play')+btn('next',IC.next,'بعدی')+btn('last',IC.last,'آخر')+'</div>'+
'<input class="sl" type="range" min="0" max="'+(N-1)+'" value="0" aria-label="مرحله">'+
'<span class="cnt"></span>'+
'<select class="spd" aria-label="سرعت"><option value="0.5">0.5×</option><option value="1" selected>1×</option><option value="1.5">1.5×</option><option value="2">2×</option><option value="3">3×</option></select>'+
btn('loop',IC.loop,'تکرار خودکار')+'</div></div>';
var $=function(s){return root.querySelector(s)};
var card=$('.card'),stage=$('.stage'),world=$('.world'),hl=$('.hl'),cbody=$('.cbody'),sbt=$('.sbt'),sbi=$('.sbt i'),lines=root.querySelectorAll('.ln'),
varsEl=$('.vars'),noteEl=$('.note'),outPre=$('.out pre'),sl=$('.sl'),cnt=$('.cnt'),bPlay=$('[data-a=play]'),bLoop=$('[data-a=loop]'),spd=$('.spd');
function sb(){if(!sbt||!cbody)return;var h=cbody.clientHeight,t=cbody.scrollHeight;if(t<=h+1){sbt.style.display='none';return}sbt.style.display='block';var th=Math.max(26,h*h/t);sbi.style.height=th+'px';sbi.style.transform='translateY('+(4+(cbody.scrollTop/(t-h))*(h-th-8))+'px)'}
if(cbody)cbody.addEventListener('scroll',sb);if(cbody&&window.ResizeObserver){try{new ResizeObserver(sb).observe(cbody)}catch(e){}}setTimeout(sb,60);setTimeout(sb,400);
var its=[],ixs=[],subs=[],pts={},win=null,rowH=[],colH=[],mcs=[],mlab=null,mx=[],corner=null,G={};
var st={k:0,vars:{},playing:false,timer:null,loop:false,speed:1,lastK:-1};
var d,i,id;
for(id=0;id<n;id++){d=document.createElement('div');d.className='it'+((S.nul&&S.nul.indexOf(id)>=0)?' nul':'');d.textContent=S.vals[id];world.appendChild(d);its.push(d)}
if(S.win){win=document.createElement('div');win.className='win';world.appendChild(win)}
if(!isGrid){for(i=0;i<n;i++){d=document.createElement('div');d.className='ix';d.textContent=i;world.appendChild(d);ixs.push(d);
if(S.sub){var sd=document.createElement('div');sd.className='sub';sd.textContent=S.sub[i];world.appendChild(sd);subs.push(sd)}}}
else{
for(i=0;i<S.grid.r;i++){d=document.createElement('div');d.className='hdr';d.textContent=(S.grid.rl?S.grid.rl[i]:'i='+i);world.appendChild(d);rowH.push(d)}
for(i=0;i<S.grid.c;i++){d=document.createElement('div');d.className='hdr';d.textContent=(S.grid.cl?S.grid.cl[i]:'j='+i);world.appendChild(d);colH.push(d)}
if(S.mem){
mlab=document.createElement('div');mlab.className='mlab';mlab.innerHTML='چیدمان واقعی در حافظه (Row-Major): خانهی <code dir="ltr">scores[i][j]</code> در جایگاه <code dir="ltr">i × COLS + j</code>';world.appendChild(mlab);
for(i=0;i<n;i++){d=document.createElement('div');d.className='mc';d.textContent=S.vals[i];world.appendChild(d);mcs.push(d);
var e=document.createElement('div');e.className='mx';e.textContent=i;world.appendChild(e);mx.push(e)}
}
}
function ensurePt(nm){
if(pts[nm])return pts[nm];
var p=document.createElement('div');p.className='pt off';p.setAttribute('data-t',nm);
p.innerHTML='<div class="pin"><div class="ar"></div><div class="lb">'+esc(nm)+'</div></div>';world.appendChild(p);pts[nm]=p;return p;
}
function layout(){
var W=stage.clientWidth;if(!W)return false;
var padX=W<500?14:26,size,gap,tw,ww;
if(!isGrid){
size=Math.max(26,Math.min(card.classList.contains('full')?120:80,Math.floor((W-2*padX)/n/1.16)));gap=Math.round(size*.16);
tw=n*size+(n-1)*gap;ww=Math.max(W,tw+2*padX);
G={W:ww,size:size,gap:gap,padL:(ww-tw)/2,padT:40};
G.ixY=G.padT+size+8;G.subY=G.ixY+19;G.ptrY=G.padT+size+(S.sub?54:32);G.H=G.ptrY+(S.lanes||1)*30+12;
}else{
var R=S.grid.r,C=S.grid.c,rh=52;
size=Math.max(30,Math.min(card.classList.contains('full')?84:58,Math.floor((W-2*padX-rh)/C/1.16)));gap=Math.round(size*.16);
tw=rh+C*size+(C-1)*gap;ww=Math.max(W,tw+2*padX);
G={W:ww,size:size,gap:gap,padL:(ww-tw)/2+rh,padT:36,rh:rh};
var gh=R*size+(R-1)*gap;
if(S.mem){
var tot=R*C,m=Math.max(22,Math.min(38,Math.floor((ww-2*padX-(R-1)*10)/tot)-5));
G.m=m;G.mg=5;var mw=tot*m+(tot-1)*5+(R-1)*10;G.mx=(ww-mw)/2;G.ml=G.padT+gh+22;G.my=G.ml+24;G.H=G.my+m+34;
}else G.H=G.padT+gh+18;
}
world.style.width=G.W+'px';world.style.height=G.H+'px';
var fs=Math.max(11,Math.round(size*(isGrid?.36:.37)))+'px',br=Math.round(size*.2)+'px';
its.forEach(function(el){el.style.width=el.style.height=size+'px';el.style.fontSize=fs;el.style.borderRadius=br});
if(!isGrid){ixs.forEach(function(el,p){el.style.width=size+'px';el.style.transform='translate('+(G.padL+p*(size+gap))+'px,'+G.ixY+'px)'});
subs.forEach(function(el,p){el.style.width=(size+gap)+'px';el.style.marginLeft=(-gap/2)+'px';el.style.transform='translate('+(G.padL+p*(size+gap))+'px,'+G.subY+'px)'})}
else{
rowH.forEach(function(el,r){el.style.width=(G.rh-12)+'px';el.style.height=size+'px';el.style.transform='translate('+(G.padL-G.rh+4)+'px,'+(G.padT+r*(size+gap))+'px)'});
colH.forEach(function(el,c){el.style.width=size+'px';el.style.height='24px';el.style.transform='translate('+(G.padL+c*(size+gap))+'px,'+(G.padT-32)+'px)'});
if(S.mem){
mlab.style.transform='translate('+G.mx+'px,'+G.ml+'px)';
mcs.forEach(function(el,k){var rr=Math.floor(k/S.grid.c);var x=G.mx+k*(G.m+G.mg)+rr*(10-0)-0;el.style.width=el.style.height=G.m+'px';el.style.transform='translate('+x+'px,'+G.my+'px)';
mx[k].style.width=G.m+'px';mx[k].style.transform='translate('+x+'px,'+(G.my+G.m+4)+'px)'});
}
}
return true;
}
function itemXY(id,f){
if(isGrid){var r=Math.floor(id/S.grid.c),c=id%S.grid.c;return [G.padL+c*(G.size+G.gap),G.padT+r*(G.size+G.gap)]}
var lift=f.lift&&f.lift.indexOf(id)>=0;
return [G.padL+f.pos[id]*(G.size+G.gap),G.padT+(lift?-18:0)];
}
function setPtr(p,x,y,instant){
if(instant||p.classList.contains('off')){p.style.transition='none';p.style.transform='translate('+x+'px,'+y+'px)';void p.offsetWidth;p.style.transition=''}
else p.style.transform='translate('+x+'px,'+y+'px)';
}
function render(k){
var f=F[k],pr=f.ptr||{};
for(id=0;id<n;id++){var el=its[id];el.setAttribute('data-c',f.cls[id]);if(f.vals&&f.vals[id]!==undefined)el.textContent=f.vals[id];var xy=itemXY(id,f);el.style.transform='translate('+xy[0]+'px,'+xy[1]+'px)'}
if(!isGrid){
subs.forEach(function(el,p){el.classList.toggle('on',f.subOn===p)});
var groups={};
Object.keys(pr).forEach(function(nm){var v=pr[nm];if(v!=null&&v>=0&&v<n){(groups[v]=groups[v]||[]).push(nm)}});
Object.keys(pts).forEach(function(nm){var v=pr[nm];if(!(v!=null&&v>=0&&v<n))pts[nm].classList.add('off')});
Object.keys(groups).forEach(function(ix){
groups[ix].sort(function(a,b){return PRI.indexOf(a)-PRI.indexOf(b)}).forEach(function(nm,r){
var p=ensurePt(nm),x=G.padL+(+ix)*(G.size+G.gap)+G.size/2,y=G.ptrY+r*30;
setPtr(p,x,y);p.classList.remove('off');
});
});
if(win){
if(f.win){var lo=f.win[0],hi=f.win[1];win.style.opacity=1;win.style.width=((hi-lo+1)*G.size+(hi-lo)*G.gap+18)+'px';win.style.height=(G.size+22)+'px';
win.style.transform='translate('+(G.padL+lo*(G.size+G.gap)-9)+'px,'+(G.padT-11)+'px)'}
else win.style.opacity=0;
}
}else{
rowH.forEach(function(el,r){el.classList.toggle('on',f.row===r)});
colH.forEach(function(el,c){el.classList.toggle('on',f.col===c)});
if(S.mem){mcs.forEach(function(el,q){el.setAttribute('data-c',q===f.mem?'cur':(q<(f.memv||0)?'vis':'i'))})}
}
var a=f.ln[0],b=f.ln[1];
hl.style.transform='translateY('+((a-1)*LH)+'px)';hl.style.height=((b-a+1)*LH)+'px';
for(i=0;i<lines.length;i++)lines[i].classList.toggle('on',i+1>=a&&i+1<=b);
var topY=(a-1)*LH,botY=b*LH+16;
if(topY<cbody.scrollTop+8||botY>cbody.scrollTop+cbody.clientHeight-8){cbody.scrollTo({top:Math.max(0,topY-cbody.clientHeight/2+LH*1.5),behavior:card.classList.contains('nt')?'auto':'smooth'})}
var h='',prev=st.vars,nv={};
(f.vars||[]).forEach(function(v){nv[v[0]]=v[1];var ch=prev[v[0]]!==undefined&&prev[v[0]]!==v[1];h+='<div class="chip'+(v[1]==='—'?' na':'')+(ch?' chg':'')+'"><b>'+esc(v[0])+'</b><span>'+esc(v[1])+'</span></div>'});
varsEl.innerHTML=h;st.vars=nv;
if(st.lastK!==k){noteEl.innerHTML=f.note;noteEl.classList.remove('in');void noteEl.offsetWidth;noteEl.classList.add('in')}
if(outPre){outPre.textContent=f.out||'';outPre.scrollTop=outPre.scrollHeight}
sl.value=k;sl.style.setProperty('--p',(N>1?k/(N-1)*100:0)+'%');cnt.textContent=(k+1)+' / '+N;
root.querySelector('[data-a=first]').disabled=root.querySelector('[data-a=prev]').disabled=(k===0);
root.querySelector('[data-a=next]').disabled=root.querySelector('[data-a=last]').disabled=(k===N-1);
bPlay.innerHTML=svg(st.playing?IC.pause:(k===N-1?IC.replay:IC.play));
var pl=st.playing?'توقف':(k===N-1?'پخش دوباره':'پخش');bPlay.setAttribute('aria-label',pl);bPlay.title=pl;
st.lastK=k;
}
function go(k){st.k=Math.max(0,Math.min(N-1,k));render(st.k)}
function stop(){st.playing=false;clearTimeout(st.timer);render(st.k)}
function tick(){
if(!st.playing)return;
if(st.k<N-1)go(st.k+1);else if(st.loop)go(0);else{stop();return}
if(st.k===N-1&&!st.loop){stop();return}
st.timer=setTimeout(tick,(S.interval||1200)/st.speed);
}
function play(){
if(st.k===N-1)go(0);
st.playing=true;render(st.k);clearTimeout(st.timer);st.timer=setTimeout(tick,(S.interval||1200)/st.speed);
}
root.querySelector('.ctl').addEventListener('click',function(e){
var t=e.target.closest&&e.target.closest('[data-a]');if(!t)return;
var a=t.getAttribute('data-a');
if(a==='play'){st.playing?stop():play()}
else if(a==='loop'){st.loop=!st.loop;bLoop.classList.toggle('on',st.loop)}
else{if(st.playing)stop();go(a==='first'?0:a==='last'?N-1:a==='prev'?st.k-1:st.k+1)}
});
sl.addEventListener('input',function(){if(st.playing)stop();go(+sl.value)});
spd.addEventListener('change',function(){st.speed=+spd.value;if(st.playing){clearTimeout(st.timer);st.timer=setTimeout(tick,(S.interval||1200)/st.speed)}});
card.addEventListener('keydown',function(e){
var k=e.key;if(e.target&&e.target.tagName==='INPUT'&&(k==='ArrowLeft'||k==='ArrowRight'))return;
if(k===' '||k==='Spacebar'){if(e.target&&e.target.tagName==='BUTTON')return;e.preventDefault();st.playing?stop():play()}
else if(k==='ArrowRight'){e.preventDefault();if(st.playing)stop();go(st.k+1)}
else if(k==='ArrowLeft'){e.preventDefault();if(st.playing)stop();go(st.k-1)}
else if(k==='Home'){e.preventDefault();go(0)}else if(k==='End'){e.preventDefault();go(N-1)}
});
function theme(){card.setAttribute('data-theme',isDark()?'dark':'light')}
function quiet(fn){card.classList.add('nt');fn();requestAnimationFrame(function(){requestAnimationFrame(function(){card.classList.remove('nt')})})}
function relayout(){
card.classList.toggle('narrow',card.clientWidth<640);
quiet(function(){if(layout()){Object.keys(pts).forEach(function(nm){pts[nm].classList.add('off')});st.lastK=-1;render(st.k)}});
}
var bFs=$('[data-a=fs]'),pseudo=false;
function fsOn(){return document.fullscreenElement===host||pseudo}
function syncFs(){var on=fsOn();card.classList.toggle('full',on);host.classList.toggle('ap-full',on);host.classList.toggle('ap-pseudo',pseudo);
if(bFs){bFs.innerHTML=svg(on?IC.fsx:IC.fs);bFs.title=bFs.ariaLabel=on?'خروج از تمامصفحه':'تمامصفحه'}
setTimeout(function(){if(host.isConnected)relayout()},60);setTimeout(function(){if(host.isConnected)relayout()},300)}
function toggleFs(){
if(fsOn()){if(pseudo){pseudo=false;syncFs()}else if(document.exitFullscreen)document.exitFullscreen();return}
var go2=function(){pseudo=true;syncFs()};
try{if(host.requestFullscreen){var pr=host.requestFullscreen();if(pr&&pr.catch)pr.catch(go2)}else go2()}catch(_){go2()}
}
if(bFs)bFs.addEventListener('click',toggleFs);
document.addEventListener('fullscreenchange',function(){if(host.isConnected)syncFs()});
document.addEventListener('keydown',function(e){if(e.key==='Escape'&&pseudo){pseudo=false;syncFs()}});
card.addEventListener('keydown',function(e){if((e.key==='f'||e.key==='F')&&!(e.target&&e.target.tagName==='INPUT')){toggleFs()}});
theme();
try{
new MutationObserver(function(){if(!host.isConnected)return;theme()}).observe(document.documentElement,{attributes:true,attributeFilter:['class','data-theme']});
if(document.body)new MutationObserver(function(){theme()}).observe(document.body,{attributes:true,attributeFilter:['class','data-vscode-theme-kind']});
if(window.matchMedia)matchMedia('(prefers-color-scheme: dark)').addEventListener('change',theme);
}catch(_){}
if(window.ResizeObserver){new ResizeObserver(function(){if(host.isConnected)relayout()}).observe(card)}
else window.addEventListener('resize',relayout);
relayout();
}
function watchTheme(host,card){
function theme(){card.setAttribute('data-theme',isDark()?'dark':'light')}
theme();
try{
new MutationObserver(function(){if(host.isConnected)theme()}).observe(document.documentElement,{attributes:true,attributeFilter:['class','data-theme']});
if(document.body)new MutationObserver(function(){theme()}).observe(document.body,{attributes:true,attributeFilter:['class','data-vscode-theme-kind']});
if(window.matchMedia)matchMedia('(prefers-color-scheme: dark)').addEventListener('change',theme);
}catch(_){}
}
function shell(host,S,inner,withReplay){
var root=host.attachShadow?host.attachShadow({mode:'open'}):host;
root.innerHTML='<style>'+CSS+'</style><div class="card nt" tabindex="0" role="group" aria-label="'+esc(S.title)+'">'+
'<div class="hd"><div class="ttl"><i class="dot"></i><span class="tt">'+esc(S.title)+'</span></div><span class="bdg">'+esc(S.badge||'Interactive')+'</span></div>'+inner+
'<div class="ctl"><div class="bts"><button class="btn" data-a="replay" aria-label="پخش دوباره" title="پخش دوباره">'+svg(IC.replay)+'</button></div><span class="hint">برای دیدن دوبارهی انیمیشن، دکمهی پخش دوباره را بزنید</span></div></div>';
return root;
}
function runAnim(card){card.classList.remove('run');void card.offsetWidth;card.classList.add('run')}
function startAnim(card){card.classList.remove('run');requestAnimationFrame(function(){requestAnimationFrame(function(){card.classList.remove('nt');runAnim(card)})})}
function mountChart(host,S){
if(host.__ap)return; host.__ap=1;
var root=shell(host,S,'<div class="chartw"></div><div class="cap">'+S.caption+'</div>');
var card=root.querySelector('.card'),wrap=root.querySelector('.chartw'),W0=0;
function draw(){
var W=wrap.clientWidth;if(!W)return false;
var H=Math.round(Math.max(230,Math.min(340,W*.46))),m={l:58,r:22,t:34,b:52},iw=W-m.l-m.r,ih=H-m.t-m.b;
var P=S.points,xmax=P[P.length-1][0],ymax=S.ymax;
function X(x){return m.l+x/xmax*iw} function Y(y){return m.t+ih-y/ymax*ih}
var h='<svg viewBox="0 0 '+W+' '+H+'" width="'+W+'" height="'+H+'" role="img" aria-label="'+esc(S.title)+'">'+
'<defs><linearGradient id="gf" x1="0" y1="0" x2="0" y2="1"><stop offset="0" style="stop-color:var(--acc);stop-opacity:.28"/><stop offset="1" style="stop-color:var(--acc);stop-opacity:0"/></linearGradient></defs>';
S.yticks.forEach(function(t){h+='<line class="gl" x1="'+m.l+'" x2="'+(W-m.r)+'" y1="'+Y(t)+'" y2="'+Y(t)+'"/><text class="tk" x="'+(m.l-10)+'" y="'+(Y(t)+4)+'" text-anchor="end">'+t+'</text>'});
P.forEach(function(p){h+='<text class="tk" x="'+X(p[0])+'" y="'+(H-m.b+20)+'" text-anchor="middle">'+p[0]+'</text>'});
h+='<line class="ax" x1="'+m.l+'" x2="'+(W-m.r)+'" y1="'+Y(0)+'" y2="'+Y(0)+'"/>';
var d='',len=0,px=null,py=null;
P.forEach(function(p,k){var x=X(p[0]),y=Y(p[1]);d+=(k?'L':'M')+x.toFixed(1)+' '+y.toFixed(1);if(k)len+=Math.hypot(x-px,y-py);px=x;py=y});
h+='<path class="cl-area" d="'+d+' L'+X(xmax).toFixed(1)+' '+Y(0)+' L'+X(0).toFixed(1)+' '+Y(0)+'Z"/>';
h+='<path class="cl-line" d="'+d+'" style="--len:'+Math.ceil(len)+'"/>';
P.forEach(function(p,k){var x=X(p[0]),y=Y(p[1]);
h+='<text class="cl-lb" style="--i:'+k+'" x="'+x+'" y="'+(y-12)+'" text-anchor="middle">'+p[1]+'</text>'+
'<circle class="cl-pt" style="--i:'+k+'" cx="'+x+'" cy="'+y+'" r="5.5"><title>'+esc((S.tip||'گام')+' '+p[0]+': '+p[1])+'</title></circle>'});
h+='<text class="axl" x="'+(m.l+iw/2)+'" y="'+(H-8)+'" text-anchor="middle">'+esc(S.xlabel)+'</text>';
h+='<text class="axl" transform="translate(14 '+(m.t+ih/2)+') rotate(-90)" text-anchor="middle">'+esc(S.ylabel)+'</text></svg>';
wrap.innerHTML=h;return true;
}
watchTheme(host,card);
function full(){if(draw())startAnim(card)}
root.querySelector('[data-a=replay]').addEventListener('click',function(){if(draw()){card.classList.add('nt');startAnim(card)}});
if(window.ResizeObserver){new ResizeObserver(function(){if(!host.isConnected)return;var w=wrap.clientWidth;if(w&&w!==W0){var first=!W0;W0=w;if(first)full();else{card.classList.add('nt');if(draw()){card.classList.add('run')}}}}).observe(wrap)}
else full();
}
function mountSummary(host,S){
if(host.__ap)return; host.__ap=1;
var h='<div class="sum">';
S.rows.forEach(function(r){
h+='<div class="srow"><div class="sname"><b>'+esc(r.name)+'</b><span>'+esc(r.sub||'')+'</span></div><div class="sarr">';
r.final.forEach(function(v,k){h+='<div class="sbx" style="--i:'+k+'">'+esc(v)+'</div>'});
h+='</div><div class="smet">';
r.metrics.forEach(function(m,k){
h+='<div class="m" data-k="'+k+'"><span class="ml">'+esc(m.label)+'</span><div class="mt"><i style="--w:'+(m.max?Math.max(m.val/m.max*100,m.val?4:0):0)+'%"></i></div><b>'+m.val+'</b>'+(m.tag?'<em>'+esc(m.tag)+'</em>':'')+'</div>'});
h+='</div></div>';
});
h+='</div><div class="lg">'+S.legend.map(function(l){return '<span><i data-c="'+l[0]+'"></i>'+l[1]+'</span>'}).join('')+'</div><div class="cap">'+S.caption+'</div>';
var root=shell(host,S,h);
var card=root.querySelector('.card');
watchTheme(host,card);
root.querySelector('[data-a=replay]').addEventListener('click',function(){card.classList.add('nt');startAnim(card)});
startAnim(card);
}
function vpPaint(items,f){
Object.keys(items).forEach(function(id){items[id].forEach(function(e){e.setAttribute('class',e.getAttribute('data-b')||'');if(e.hasAttribute('data-t'))e.textContent=e.getAttribute('data-t')})});
var on=f.on||{};Object.keys(on).forEach(function(id){(items[id]||[]).forEach(function(e){e.setAttribute('class',((e.getAttribute('class')||'')+' s-'+on[id]).trim())})});
var set=f.set||{};Object.keys(set).forEach(function(id){(items[id]||[]).forEach(function(e){e.textContent=set[id]})});
}
function mountVP(host,S){
if(host.__ap)return; host.__ap=1;
var root=host.attachShadow?host.attachShadow({mode:'open'}):host;
var F=S.frames,N=F.length,LH=22,hasCode=!!(S.code&&S.code.length);
function codeHtml(arr){var h='';for(var q=0;q<arr.length;q++)h+='<div class="ln"><span class="no">'+(q+1)+'</span><span class="tx">'+arr[q]+'</span></div>';return h}
var lg='';(S.legend||[]).forEach(function(l){lg+='<span><i data-c="'+l[0]+'"></i>'+l[1]+'</span>'});
var btn=function(id,ic,label,cls){return '<button class="btn '+(cls||'')+'" data-a="'+id+'" aria-label="'+label+'" title="'+label+'">'+svg(ic)+'</button>'};
root.innerHTML='<style>'+CSS+'</style><div class="card nt'+(S.pc?' pc':'')+'" tabindex="0" role="group" aria-label="'+esc(S.title)+'">'+
'<div class="hd"><div class="ttl"><i class="dot"></i><span class="tt">'+esc(S.title)+'</span></div><div class="hr"><span class="bdg">'+esc(S.badge||'Interactive')+'</span>'+btn('fs',IC.fs,'تمامصفحه','fsb')+'</div></div>'+
(S.svg?'<div class="stage"><div class="vpw">'+S.svg+'</div></div>':'')+
(lg?'<div class="lg">'+lg+'</div>':'')+
'<div class="split'+(hasCode?'':' nocode')+'">'+(hasCode?'<div class="codep"><div class="chd"><s></s>'+esc(S.codeTitle||'')+'</div><div class="cwrap"><div class="cbody"><div class="lines"><div class="hl"></div>'+codeHtml(S.code)+'</div></div><div class="sbt"><i></i></div></div></div>':'')+
'<div class="info"><div><div class="bt">متغیرها</div><div class="vars"></div></div>'+
'<div><div class="bt">این مرحله چه میکند؟</div><div class="note" aria-live="polite"></div></div>'+
(S.showOut?'<div class="out"><div class="bt">خروجی برنامه</div><pre></pre></div>':'')+'</div></div>'+
'<div class="ctl"><div class="bts">'+btn('first',IC.first,'اول')+btn('prev',IC.prev,'قبلی')+btn('play',IC.play,'پخش','play')+btn('next',IC.next,'بعدی')+btn('last',IC.last,'آخر')+'</div>'+
'<input class="sl" type="range" min="0" max="'+(N-1)+'" value="0" aria-label="مرحله">'+
'<span class="cnt"></span>'+
'<select class="spd" aria-label="سرعت"><option value="0.5">0.5×</option><option value="1" selected>1×</option><option value="1.5">1.5×</option><option value="2">2×</option><option value="3">3×</option></select>'+
btn('loop',IC.loop,'تکرار خودکار')+'</div></div>';
var $=function(s){return root.querySelector(s)};
var card=$('.card'),hl=$('.hl'),cbody=$('.cbody'),sbt=$('.sbt'),sbi=$('.sbt i'),linesBox=$('.lines'),chd=$('.chd'),
varsEl=$('.vars'),noteEl=$('.note'),outPre=$('.out pre'),sl=$('.sl'),cnt=$('.cnt'),bPlay=$('[data-a=play]'),bLoop=$('[data-a=loop]'),spd=$('.spd');
var lines=root.querySelectorAll('.ln'),i;
function sb(){if(!sbt||!cbody)return;var h=cbody.clientHeight,t=cbody.scrollHeight;if(t<=h+1){sbt.style.display='none';return}sbt.style.display='block';var th=Math.max(26,h*h/t);sbi.style.height=th+'px';sbi.style.transform='translateY('+(4+(cbody.scrollTop/(t-h))*(h-th-8))+'px)'}
if(cbody)cbody.addEventListener('scroll',sb);if(cbody&&window.ResizeObserver){try{new ResizeObserver(sb).observe(cbody)}catch(e){}}setTimeout(sb,60);setTimeout(sb,400);
var items={},svgEl=root.querySelector('.vpw svg');
if(svgEl)svgEl.querySelectorAll('[data-id]').forEach(function(e){var id=e.getAttribute('data-id');(items[id]=items[id]||[]).push(e);e.setAttribute('data-b',e.getAttribute('class')||'');if(e.tagName==='text')e.setAttribute('data-t',e.textContent)});
var st={k:0,vars:{},playing:false,timer:null,loop:false,speed:1,lastK:-1};
function render(k){
var f=F[k];
vpPaint(items,f);
if(hasCode){
if(f.code){linesBox.querySelectorAll('.ln').forEach(function(n){n.parentNode.removeChild(n)});linesBox.insertAdjacentHTML('beforeend',codeHtml(f.code));lines=root.querySelectorAll('.ln');if(chd)chd.lastChild.nodeValue=f.codeTitle||S.codeTitle||'';setTimeout(sb,30)}
if(f.ln){var a=f.ln[0],b=f.ln[1];hl.style.height=((b-a+1)*LH)+'px';hl.style.transform='translateY('+((a-1)*LH)+'px)';
for(i=0;i<lines.length;i++)lines[i].classList.toggle('on',i+1>=a&&i+1<=b);
var topY=(a-1)*LH,botY=b*LH+16;
if(topY<cbody.scrollTop+8||botY>cbody.scrollTop+cbody.clientHeight-8){cbody.scrollTo({top:Math.max(0,topY-cbody.clientHeight/2+LH*1.5),behavior:card.classList.contains('nt')?'auto':'smooth'})}
}else{hl.style.height='0px';for(i=0;i<lines.length;i++)lines[i].classList.remove('on')}
}
var h='',prev=st.vars,nv={};
(f.vars||[]).forEach(function(v){nv[v[0]]=v[1];var ch=prev[v[0]]!==undefined&&prev[v[0]]!==v[1];h+='<div class="chip'+(v[1]==='—'?' na':'')+(ch?' chg':'')+'"><b>'+esc(v[0])+'</b><span>'+esc(v[1])+'</span></div>'});
varsEl.innerHTML=h;varsEl.parentNode.style.display=h?'':'none';st.vars=nv;
if(st.lastK!==k){noteEl.innerHTML=f.note;noteEl.classList.remove('in');void noteEl.offsetWidth;noteEl.classList.add('in')}
if(outPre){outPre.textContent=f.out||'';outPre.scrollTop=outPre.scrollHeight}
sl.value=k;sl.style.setProperty('--p',(N>1?k/(N-1)*100:0)+'%');cnt.textContent=(k+1)+' / '+N;
root.querySelector('[data-a=first]').disabled=root.querySelector('[data-a=prev]').disabled=(k===0);
root.querySelector('[data-a=next]').disabled=root.querySelector('[data-a=last]').disabled=(k===N-1);
bPlay.innerHTML=svg(st.playing?IC.pause:(k===N-1?IC.replay:IC.play));
var pl=st.playing?'توقف':(k===N-1?'پخش دوباره':'پخش');bPlay.setAttribute('aria-label',pl);bPlay.title=pl;
st.lastK=k;
}
function go(k){st.k=Math.max(0,Math.min(N-1,k));render(st.k)}
function stop(){st.playing=false;clearTimeout(st.timer);render(st.k)}
function tick(){
if(!st.playing)return;
if(st.k<N-1)go(st.k+1);else if(st.loop)go(0);else{stop();return}
if(st.k===N-1&&!st.loop){stop();return}
st.timer=setTimeout(tick,(S.interval||1200)/st.speed);
}
function play(){if(st.k===N-1)go(0);st.playing=true;render(st.k);clearTimeout(st.timer);st.timer=setTimeout(tick,(S.interval||1200)/st.speed)}
root.querySelector('.ctl').addEventListener('click',function(e){
var t=e.target.closest&&e.target.closest('[data-a]');if(!t)return;
var a=t.getAttribute('data-a');
if(a==='play'){st.playing?stop():play()}
else if(a==='loop'){st.loop=!st.loop;bLoop.classList.toggle('on',st.loop)}
else{if(st.playing)stop();go(a==='first'?0:a==='last'?N-1:a==='prev'?st.k-1:st.k+1)}
});
sl.addEventListener('input',function(){if(st.playing)stop();go(+sl.value)});
spd.addEventListener('change',function(){st.speed=+spd.value;if(st.playing){clearTimeout(st.timer);st.timer=setTimeout(tick,(S.interval||1200)/st.speed)}});
card.addEventListener('keydown',function(e){
var k=e.key;if(e.target&&e.target.tagName==='INPUT'&&(k==='ArrowLeft'||k==='ArrowRight'))return;
if(k===' '||k==='Spacebar'){if(e.target&&e.target.tagName==='BUTTON')return;e.preventDefault();st.playing?stop():play()}
else if(k==='ArrowRight'){e.preventDefault();if(st.playing)stop();go(st.k+1)}
else if(k==='ArrowLeft'){e.preventDefault();if(st.playing)stop();go(st.k-1)}
else if(k==='Home'){e.preventDefault();go(0)}else if(k==='End'){e.preventDefault();go(N-1)}
});
function theme(){card.setAttribute('data-theme',isDark()?'dark':'light')}
function relayout(){card.classList.toggle('narrow',card.clientWidth<640)}
var bFs=$('[data-a=fs]'),pseudo=false;
function fsOn(){return document.fullscreenElement===host||pseudo}
function syncFs(){var on=fsOn();card.classList.toggle('full',on);host.classList.toggle('ap-full',on);host.classList.toggle('ap-pseudo',pseudo);
if(bFs){bFs.innerHTML=svg(on?IC.fsx:IC.fs);bFs.title=bFs.ariaLabel=on?'خروج از تمامصفحه':'تمامصفحه'}
setTimeout(function(){if(host.isConnected){relayout();sb()}},60)}
function toggleFs(){
if(fsOn()){if(pseudo){pseudo=false;syncFs()}else if(document.exitFullscreen)document.exitFullscreen();return}
var go2=function(){pseudo=true;syncFs()};
try{if(host.requestFullscreen){var pr=host.requestFullscreen();if(pr&&pr.catch)pr.catch(go2)}else go2()}catch(_){go2()}
}
if(bFs)bFs.addEventListener('click',toggleFs);
document.addEventListener('fullscreenchange',function(){if(host.isConnected)syncFs()});
document.addEventListener('keydown',function(e){if(e.key==='Escape'&&pseudo){pseudo=false;syncFs()}});
theme();
try{
new MutationObserver(function(){if(!host.isConnected)return;theme()}).observe(document.documentElement,{attributes:true,attributeFilter:['class','data-theme']});
if(document.body)new MutationObserver(function(){theme()}).observe(document.body,{attributes:true,attributeFilter:['class','data-vscode-theme-kind']});
if(window.matchMedia)matchMedia('(prefers-color-scheme: dark)').addEventListener('change',theme);
}catch(_){}
if(window.ResizeObserver){new ResizeObserver(function(){if(host.isConnected)relayout()}).observe(card)}else window.addEventListener('resize',relayout);
relayout();render(0);
requestAnimationFrame(function(){requestAnimationFrame(function(){card.classList.remove('nt')})});
}
function ishell(host,S,inner){
var root=host.attachShadow?host.attachShadow({mode:'open'}):host;
root.innerHTML='<style>'+CSS+'</style><div class="card nt iw" tabindex="0" role="group" aria-label="'+esc(S.title)+'"><div class="hd"><div class="ttl"><i class="dot"></i><span class="tt">'+esc(S.title)+'</span></div><span class="bdg">'+esc(S.badge||'Interactive')+'</span></div><div class="bd">'+inner+'</div></div>';
var card=root.querySelector('.card');watchTheme(host,card);
requestAnimationFrame(function(){requestAnimationFrame(function(){card.classList.remove('nt')})});
return root;
}
function fmt(n){return Number(n).toLocaleString('en-US')}
function mountGuess(host,S){
if(host.__ap)return;host.__ap=1;
var root=ishell(host,S,
'<div class="row"><span class="lab">بازهی عدد:</span><button class="pill" data-n="100">۱ تا ۱۰۰</button><button class="pill" data-n="1000">۱ تا ۱٬۰۰۰</button><button class="pill" data-n="1000000">۱ تا ۱٬۰۰۰٬۰۰۰</button></div>'+
'<div class="row"><span class="lab">عدد پنهانِ من:</span><input class="rng" type="range" min="1" max="100" value="73" aria-label="عدد پنهان"><b class="sec">73</b></div>'+
'<div><div class="gbar"><div class="grng"></div><div class="gmk"></div><div class="gsec"></div></div><div class="gscale"><span>1</span><span class="gmax"></span></div></div>'+
'<div class="row"><button class="pill act" data-a="step">حدس بعدی</button><button class="pill" data-a="auto">پخش خودکار</button><button class="pill" data-a="reset">از اول</button></div>'+
'<div class="msg" aria-live="polite"></div>'+
'<div class="grid"><div class="rd"><b>حدسهای روش نیمکردن</b><span class="c1">0</span></div><div class="rd"><b>حداکثرِ لازم برای این بازه</b><span class="c2"></span></div><div class="rd"><b>حدسزدن یکییکی (از ۱)</b><span class="c3"></span></div></div>');
var $=function(s){return root.querySelector(s)};
var N=S.n||100,secret=Math.round(N*0.73),steps=[],idx=0,timer=null;
var rng=$('.rng'),secEl=$('.sec'),rangeEl=$('.grng'),mk=$('.gmk'),sc=$('.gsec'),msg=$('.msg'),c1=$('.c1'),c2=$('.c2'),c3=$('.c3'),gmax=$('.gmax'),bAuto=$('[data-a=auto]');
function plan(){var lo=1,hi=N,o=[];for(var t=0;t<64;t++){var g=Math.floor((lo+hi)/2);if(g===secret){o.push({g:g,lo:lo,hi:hi,r:0});break}if(g<secret){o.push({g:g,lo:lo,hi:hi,r:-1});lo=g+1}else{o.push({g:g,lo:lo,hi:hi,r:1});hi=g-1}}return o}
function pct(x){return (x/N*100)}
function draw(){
var lo=1,hi=N,k=idx,m='';
gmax.textContent=fmt(N);secEl.textContent=fmt(secret);
sc.style.left=pct(secret-0.5)+'%';
if(k>0){var s=steps[k-1];if(s.r<0){lo=s.g+1;hi=s.hi}else if(s.r>0){lo=s.lo;hi=s.g-1}else{lo=s.g;hi=s.g}
mk.style.opacity=1;mk.style.left=pct(s.g-0.5)+'%';
if(s.r<0)m='حدس <b>'+k+'</b>: <code>'+fmt(s.g)+'</code> از عدد من <b>کوچکتر</b> است، پس نیمهی پایینی کنار میرود. بازهی باقیمانده: <code>'+fmt(lo)+'</code> تا <code>'+fmt(hi)+'</code> ('+fmt(hi-lo+1)+' عدد).';
else if(s.r>0)m='حدس <b>'+k+'</b>: <code>'+fmt(s.g)+'</code> از عدد من <b>بزرگتر</b> است، پس نیمهی بالایی کنار میرود. بازهی باقیمانده: <code>'+fmt(lo)+'</code> تا <code>'+fmt(hi)+'</code> ('+fmt(hi-lo+1)+' عدد).';
else m='حدس <b>'+k+'</b>: <code>'+fmt(s.g)+'</code> درست بود! عدد با '+k+' حدس پیدا شد.'}
else{mk.style.opacity=0;m='عدد پنهان را با لغزنده تعیین کنید و «حدس بعدی» را بزنید. هر حدس، وسط بازهی باقیمانده است.'}
rangeEl.style.left=pct(lo-1)+'%';rangeEl.style.width='max('+((hi-lo+1)/N*100)+'%,5px)';
msg.innerHTML=m;c1.textContent=k;c2.textContent=Math.ceil(Math.log2(N+1));c3.textContent=fmt(secret);
}
function reset(){stop();steps=plan();idx=0;draw()}
function step(){if(idx<steps.length){idx++;draw()}else{stop()}}
function stop(){if(timer){clearInterval(timer);timer=null}bAuto.textContent='پخش خودکار'}
function auto(){if(timer){stop();return}if(idx>=steps.length){idx=0;draw()}bAuto.textContent='توقف';timer=setInterval(function(){if(idx>=steps.length){stop();return}step()},850)}
function setN(n){N=n;rng.max=n;secret=Math.round(n*0.73);rng.value=secret;root.querySelectorAll('[data-n]').forEach(function(b){b.classList.toggle('on',+b.getAttribute('data-n')===n)});reset()}
root.addEventListener('click',function(e){var t=e.target.closest&&e.target.closest('button');if(!t)return;
if(t.hasAttribute('data-n'))setN(+t.getAttribute('data-n'));
else{var a=t.getAttribute('data-a');if(a==='step'){stop();step()}else if(a==='auto')auto();else if(a==='reset')reset()}});
rng.addEventListener('input',function(){secret=+rng.value;reset()});
setN(N);
}
function mountBits(host,S){
if(host.__ap)return;host.__ap=1;
var root=ishell(host,S,
'<div class="row"><span class="lab">نمایش:</span><button class="pill" data-m="u">بدون علامت (۰ تا ۲۵۵)</button><button class="pill" data-m="s">با علامت، مکمل ۲ (−۱۲۸ تا ۱۲۷)</button></div>'+
'<div class="bits"></div><div class="nib"></div>'+
'<div class="row"><span class="lab">امتحان کنید:</span><button class="pill" data-v="0">0</button><button class="pill" data-v="5">5</button><button class="pill" data-v="65">65</button><button class="pill" data-v="127">127</button><button class="pill" data-v="128">128</button><button class="pill" data-v="255">255</button><button class="pill act" data-a="inc">+۱</button><button class="pill act" data-a="dec">−۱</button><button class="pill" data-a="not">معکوسکردن بیتها</button><button class="pill" data-a="neg">قرینه (مکمل ۲)</button></div>'+
'<div class="msg" aria-live="polite"></div>'+
'<div class="grid"><div class="rd"><b>مقدار (دهدهی)</b><span class="r-dec"></span></div><div class="rd"><b>دودویی</b><span class="r-bin"></span></div><div class="rd"><b>هگزادسیمال</b><span class="r-hex"></span></div><div class="rd"><b>اکتال</b><span class="r-oct"></span></div><div class="rd"><b>نویسهی ASCII</b><span class="r-asc"></span></div></div>');
var $=function(s){return root.querySelector(s)};
var v=S.v||0,signed=S.mode==='s';
var bitsEl=$('.bits'),nibEl=$('.nib'),msg=$('.msg'),btns=[];
for(var i=7;i>=0;i--){
if(i===3){var g=document.createElement('div');g.className='gap';bitsEl.appendChild(g)}
var c=document.createElement('div');c.className='bit';
c.innerHTML='<div class="w"></div><button aria-label="بیت '+i+'">0</button><div class="ix">'+i+'</div>';
bitsEl.appendChild(c);btns[i]={w:c.querySelector('.w'),b:c.querySelector('button')};
(function(ii){btns[ii].b.addEventListener('click',function(){v^=(1<<ii);note('');draw()})})(i);
}
nibEl.innerHTML='<div class="n1"></div><div class="n0"></div>';
function sv(x){return x>=128?x-256:x}
function note(t){msg.innerHTML=t}
function draw(){
var parts=[],i;
for(i=7;i>=0;i--){var on=(v>>i)&1;btns[i].b.textContent=on;btns[i].b.classList.toggle('on',!!on);btns[i].b.classList.toggle('neg',signed&&i===7);
btns[i].w.textContent=(signed&&i===7)?'−128':String(1<<i);btns[i].w.classList.toggle('neg',signed&&i===7);
if(on)parts.push((signed&&i===7)?'−128':String(1<<i))}
var val=signed?sv(v):v;
var sum=parts.length?parts.join(' + ').replace(/\+ −/g,'− ').replace(/^\+ /,''):'0';
$('.r-dec').textContent=val;
$('.r-bin').textContent=(v>>4).toString(2).padStart(4,'0')+' '+(v&15).toString(2).padStart(4,'0');
$('.r-hex').textContent='0x'+v.toString(16).toUpperCase().padStart(2,'0');
$('.r-oct').textContent=v?('0'+v.toString(8)):'0';
$('.r-asc').textContent=(!signed&&v>=32&&v<=126)?("'"+String.fromCharCode(v)+"'"):'—';
$('.n1').textContent=((v>>4)&15).toString(16).toUpperCase();$('.n0').textContent=(v&15).toString(16).toUpperCase();
root.querySelectorAll('[data-m]').forEach(function(b){b.classList.toggle('on',(b.getAttribute('data-m')==='s')===signed)});
if(!msg.innerHTML)msg.innerHTML='جمع وزن بیتهای روشن: <code>'+sum+' = '+val+'</code>. هر چهار بیت (یک «نیبل») دقیقاً یک رقم هگزادسیمال است.';
}
root.addEventListener('click',function(e){var t=e.target.closest&&e.target.closest('button');if(!t)return;
if(t.hasAttribute('data-m')){signed=t.getAttribute('data-m')==='s';note('');draw();return}
if(t.hasAttribute('data-v')){v=+t.getAttribute('data-v');note('');draw();return}
var a=t.getAttribute('data-a');if(!a)return;
var before=signed?sv(v):v;
if(a==='inc'){v=(v+1)&255;var after=signed?sv(v):v;note(after<before?'<b>سرریز!</b> فقط ۸ بیت داریم، پس بعد از بزرگترین مقدار، شمارش از کمترین مقدار ادامه مییابد: <code>'+before+' + 1 = '+after+'</code>':'<code>'+before+' + 1 = '+after+'</code>')}
else if(a==='dec'){v=(v-1)&255;var after2=signed?sv(v):v;note(after2>before?'<b>سرریز!</b> از کمترین مقدار یک واحد کم کردیم و به بیشترین مقدار رسیدیم: <code>'+before+' − 1 = '+after2+'</code>':'<code>'+before+' − 1 = '+after2+'</code>')}
else if(a==='not'){v=(~v)&255;note('همهی بیتها برعکس شدند (۰ به ۱ و ۱ به ۰). این گام اول ساختن قرینهی یک عدد است.')}
else if(a==='neg'){var o=v;v=((~v)&255)+1&255;note('قرینه: اول بیتها را معکوس میکنیم، بعد ۱ جمع میکنیم. <code>'+(signed?sv(o):o)+'</code> تبدیل شد به <code>'+(signed?sv(v):v)+'</code>. (در حالت «با علامت» این همان ضرب در ۱− است.)')}
draw()});
draw();
}
function mountFloat(host,S){
if(host.__ap)return;host.__ap=1;
var root=ishell(host,S,
'<div class="row"><span class="lab">یک عدد بنویسید:</span><input class="txt" dir="ltr" value="0.1" aria-label="عدد"><button class="pill act" data-a="set">نمایش بیتها</button></div>'+
'<div class="row"><span class="lab">نمونهها:</span><button class="pill" data-p="1">1</button><button class="pill" data-p="0.1">0.1</button><button class="pill" data-p="-2.5">-2.5</button><button class="pill" data-p="0.15625">0.15625</button><button class="pill" data-p="16777217">16777217</button></div>'+
'<div class="fbits"><div class="fg s"><i>علامت</i><div class="bs" data-g="s"></div></div><div class="fg e"><i>توان (۸ بیت)</i><div class="bs" data-g="e"></div></div><div class="fg m"><i>مانتیس (۲۳ بیت)</i><div class="bs" data-g="m"></div></div></div>'+
'<div class="msg" aria-live="polite"></div>'+
'<div class="grid"><div class="rd"><b>علامت</b><span class="r-s fa"></span></div><div class="rd"><b>توان بعد از کمکردن ۱۲۷</b><span class="r-e"></span></div><div class="rd"><b>مانتیس (۱.xxx)</b><span class="r-m"></span></div><div class="rd"><b>مقدار ذخیرهشده</b><span class="r-v"></span></div></div>');
var $=function(s){return root.querySelector(s)};
var bits=0,bt=[],inp=$('.txt'),msg=$('.msg');
function toBits(x){var d=new DataView(new ArrayBuffer(4));d.setFloat32(0,x);return d.getUint32(0)}
function toVal(b){var d=new DataView(new ArrayBuffer(4));d.setUint32(0,b>>>0);return d.getFloat32(0)}
function build(g,hi,lo){var box=$('[data-g='+g+']');for(var i=hi;i>=lo;i--){var b=document.createElement('button');b.textContent='0';b.setAttribute('aria-label','بیت '+i);box.appendChild(b);bt[i]=b;(function(ii){b.addEventListener('click',function(){bits=(bits^(1<<ii))>>>0;msg.innerHTML='';draw()})})(i)}}
build('s',31,31);build('e',30,23);build('m',22,0);
function draw(){
var i;for(i=31;i>=0;i--){var on=(bits>>>i)&1;bt[i].textContent=on;bt[i].classList.toggle('on',!!on)}
var s=bits>>>31,e=(bits>>>23)&255,m=bits&0x7fffff,val=toVal(bits),kind;
$('.r-s').textContent=s?'منفی (−)':'مثبت (+)';
if(e===255)kind=m?'NaN (عدد نامعتبر)':(s?'−∞':'+∞');else if(e===0)kind=m?'عدد بسیار کوچک (زیرنرمال)':'صفر';else kind='';
$('.r-e').textContent=(e===0||e===255)?('خاص: '+e):(e-127);
$('.r-m').textContent=(e===0)?('0.'+m.toString(2).padStart(23,'0').slice(0,8)+'…'):('1.'+(m/8388608).toFixed(7).slice(2));
$('.r-v').textContent=Number.isFinite(val)?String(val):(kind||'');
if(!msg.innerHTML){var f=(e>0&&e<255)?'<code>(−1)<sup>'+s+'</sup> × '+(1+m/8388608).toFixed(6)+' × 2<sup>'+(e-127)+'</sup></code>':'';msg.innerHTML=(kind?kind+'. ':'')+f}
}
function apply(t){var x=parseFloat(t);if(isNaN(x)){msg.textContent='یک عدد معتبر بنویسید.';return}
bits=toBits(x);inp.value=t;var st=toVal(bits);
msg.innerHTML=(String(st)===String(x))?('عدد <code>'+t+'</code> دقیقاً قابل ذخیره است.'):('عدد <code>'+t+'</code> <b>دقیقاً</b> قابل ذخیره نیست. نزدیکترین عدد قابل ذخیره در ۳۲ بیت: <code>'+String(st)+'</code>');
draw();
var f=msg.innerHTML;var s2=bits>>>31,e2=(bits>>>23)&255,m2=bits&0x7fffff;if(e2>0&&e2<255)msg.innerHTML=f+'<br>ساختار: <code>(−1)<sup>'+s2+'</sup> × '+(1+m2/8388608).toFixed(6)+' × 2<sup>'+(e2-127)+'</sup></code>'}
root.addEventListener('click',function(e){var t=e.target.closest&&e.target.closest('button');if(!t)return;
if(t.hasAttribute('data-p'))apply(t.getAttribute('data-p'));else if(t.getAttribute('data-a')==='set')apply(inp.value)});
inp.addEventListener('keydown',function(e){if(e.key==='Enter')apply(inp.value)});
apply(S.start||'0.1');
}
function mountBytes(host,S){
if(host.__ap)return;host.__ap=1;
var root=ishell(host,S,
'<div class="row"><span class="lab">یک متن بنویسید:</span><input class="txt" value="Hi سلام" aria-label="متن"></div>'+
'<div class="row"><span class="lab">نمونهها:</span><button class="pill" data-t="A">A</button><button class="pill" data-t="Hello">Hello</button><button class="pill" data-t="سلام">سلام</button><button class="pill" data-t="چ">چ</button><button class="pill" data-t="€">€</button></div>'+
'<div class="bq"></div><div class="msg" aria-live="polite"></div>');
var $=function(s){return root.querySelector(s)};
var inp=$('.txt'),box=$('.bq'),msg=$('.msg');
function esc2(t){return String(t).replace(/[&<>]/g,function(c){return {'&':'&','<':'<','>':'>'}[c]})}
function draw(){
var chars=Array.from(inp.value).slice(0,16),total=0,h='';
chars.forEach(function(ch){
var enc=new TextEncoder().encode(ch),n=enc.length;total+=n;
var cp=ch.codePointAt(0).toString(16).toUpperCase().padStart(4,'0');
var by='';
Array.prototype.forEach.call(enc,function(b,ix){
var bin=b.toString(2).padStart(8,'0'),pre=0;
if(n>1){pre=(ix===0)?(n+1):2}
by+='<div class="b"><u>'+bin.slice(0,pre)+'</u>'+bin.slice(pre)+'<small>0x'+b.toString(16).toUpperCase().padStart(2,'0')+' = '+b+'</small></div>'});
h+='<div class="bc l'+n+'"><div class="ch">'+(ch===' '?'␣':esc2(ch))+'</div><div class="cp">U+'+cp+'</div><div class="by">'+by+'</div></div>'});
box.innerHTML=h;
var all=Array.from(inp.value).length;
msg.innerHTML=all?('<b>'+all+'</b> نویسه، که در حافظه <b>'+new TextEncoder().encode(inp.value).length+'</b> بایت جا میگیرد'+(all>16?' (فقط ۱۶ نویسهی اول نمایش داده شد)':'')+'. نویسههای لاتین یک بایتاند؛ حرفهای فارسی معمولاً دو بایت. بخش کمرنگِ هر بایت، بیتهای ثابتِ قالب UTF-8 است و بقیه، خودِ داده.'):'متنی بنویسید.';
}
root.addEventListener('click',function(e){var t=e.target.closest&&e.target.closest('[data-t]');if(t){inp.value=t.getAttribute('data-t');draw()}});
inp.addEventListener('input',draw);
draw();
}
function mountAny(host,S){
if(S.kind==='vp')return mountVP(host,S);
if(S.kind==='guess')return mountGuess(host,S);
if(S.kind==='bits')return mountBits(host,S);
if(S.kind==='float')return mountFloat(host,S);
if(S.kind==='bytes')return mountBytes(host,S);
if(S.kind==='chart')return mountChart(host,S);
if(S.kind==='summary')return mountSummary(host,S);
return mount(host,S);
}
window.__VPL={mount:mountAny,v:"__VER__"};
})();
'''
_KW = {"if","else","for","while","do","return","break","continue","switch","case","default","sizeof","struct","typedef","const","static"}
_TY = {"int","char","void","float","double","long","short","unsigned","signed","size_t"}
_TOK = re.compile(r'(//.*$)|("(?:\\.|[^"\\])*")|(\'(?:\\.|[^\'\\])*\')|(#\s*\w+)|(\b\d+(?:\.\d+)?\b)|(\b[A-Za-z_]\w*\b)')
def _c_hl(line):
out, pos = [], 0
for m in _TOK.finditer(line):
out.append(_html.escape(line[pos:m.start()]))
t = m.group(0)
if m.group(1): cls = "c"
elif m.group(2) or m.group(3): cls = "s"
elif m.group(4): cls = "p"
elif m.group(5): cls = "n"
else:
w = t
after = line[m.end():].lstrip()[:1]
if w in _KW: cls = "k"
elif w in _TY: cls = "t"
elif after == "(" : cls = "f"
elif len(w) > 1 and w.upper() == w and w.isalpha() or "_" in w and w.upper() == w: cls = "p"
else: cls = None
e = _html.escape(t)
out.append(f'<span class="{cls}">{e}</span>' if cls else e)
pos = m.end()
out.append(_html.escape(line[pos:]))
s = "".join(out)
if line.lstrip().startswith("#include"):
s = re.sub(r'(<[^&]*>)', r'<span class="s">\1</span>', s)
return s
def _c(x):
return f'<code dir="ltr">{_html.escape(str(x))}</code>'
def _widget(scene):
sid = "ap" + uuid.uuid4().hex[:8]
_ver = hashlib.md5((_AP_CSS + _AP_JS).encode("utf8")).hexdigest()[:10]
js_lib = _AP_JS.replace("__CSS__", json.dumps(_AP_CSS)).replace("__VER__", _ver)
data = json.dumps(scene, ensure_ascii=False, separators=(",", ":")).replace("</", "<\\/")
return HTML(
f'<div class="ap-root" data-ap="1" id="{sid}" style="display:block"></div>'
f'<script>{js_lib}\n(function(){{var S={data};var id="{sid}";var tries=0;'
f'var host=(document.currentScript&&document.currentScript.previousElementSibling)||document.getElementById(id);'
f'(function go(){{host=document.getElementById(id)||host;if(host&&host.isConnected){{window.__VPL.mount(host,S)}}'
f'else if(tries++<200){{setTimeout(go,50)}}}})();}})();</script>'
)
def _scene(title, code, code_title, vals, frames, legend, **kw):
s = dict(title=title, code=[_c_hl(l) for l in code], codeTitle=code_title, vals=[str(v) for v in vals],
n=len(vals), frames=frames, legend=legend, badge="Step by step")
s.update(kw)
return s
ART = {
"c": [
"#include <stdio.h>",
"",
"int main(void)",
"{",
" printf(\"Hello, world\\n\");",
" return 0;",
"}"
],
"i": [
"/* ... about 820 lines from stdio.h and the headers it includes ... */",
"extern int printf (const char *__restrict __format, ...);",
"/* ... */",
"",
"int main(void)",
"{",
" printf(\"Hello, world\\n\");",
" return 0;",
"}"
],
"s": [
".LC0:",
" .string \"Hello, world\"",
" .text",
" .globl main",
" .type main, @function",
"main:",
" pushq %rbp",
" movq %rsp, %rbp",
" leaq .LC0(%rip), %rax",
" movq %rax, %rdi",
" call puts@PLT",
" movl $0, %eax",
" popq %rbp",
" ret"
],
"o": [
" 0: 55 push %rbp",
" 1: 48 89 e5 mov %rsp,%rbp",
" 4: 48 8d 05 00 00 00 00lea 0x0(%rip),%rax # b <main+0xb>",
" b: 48 89 c7 mov %rax,%rdi",
" e: e8 00 00 00 00 call 13 <main+0x13>",
" 13: b8 00 00 00 00 mov $0x0,%eax",
" 18: 5d pop %rbp",
" 19: c3 ret"
],
"x": [
"$ gcc hello.o -o hello",
"$ file hello",
"hello: ELF 64-bit LSB pie executable, x86-64, dynamically linked, ...",
"$ wc -c < hello",
"15960"
],
"r": [
"$ ./hello",
"Hello, world"
],
"n_i": 820
}
# ============================================================
# صحنههای بخش اول: الگوریتم، معماری کامپیوتر و آشنایی با C
# ============================================================
import html as _h
_LRM = "\u200e"
_FA = str.maketrans("0123456789", "۰۱۲۳۴۵۶۷۸۹")
def fa(x):
return str(x).translate(_FA)
def lx(s):
"""an LTR expression inside Persian pseudocode (bdi isolates it from the surrounding RTL text)"""
return '<bdi dir="ltr">' + _h.escape(s, quote=False) + '</bdi>'
def lt(s):
"""an LTR expression inside SVG text (LRM marks isolate it)"""
return _LRM + s + _LRM
def _t(x, y, s, cls="", anchor="middle", extra=""):
c = f' class="{cls}"' if cls else ""
return f'<text{c} x="{x}" y="{y}" text-anchor="{anchor}" dominant-baseline="central"{extra}>{_h.escape(s, quote=False)}</text>'
_DEFS = ('<defs>'
'<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path class="mk" d="M0,0 L10,5 L0,10 z"/></marker>'
'<marker id="arrA" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path class="mkA" d="M0,0 L10,5 L0,10 z"/></marker>'
'<marker id="arrC" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path class="mkC" d="M0,0 L10,5 L0,10 z"/></marker>'
'</defs>')
def _node(n):
t, x, y, w, h, nid = n["t"], n["x"], n["y"], n["w"], n["h"], n["id"]
if t in ("start", "end"):
shape = f'<rect x="{x - w / 2}" y="{y - h / 2}" width="{w}" height="{h}" rx="{h / 2}"/>'
elif t == "proc":
shape = f'<rect x="{x - w / 2}" y="{y - h / 2}" width="{w}" height="{h}" rx="6"/>'
elif t == "dec":
shape = f'<polygon points="{x},{y - h / 2} {x + w / 2},{y} {x},{y + h / 2} {x - w / 2},{y}"/>'
else: # io
k = 14
shape = (f'<polygon points="{x - w / 2 + k},{y - h / 2} {x + w / 2 + k},{y - h / 2} '
f'{x + w / 2 - k},{y + h / 2} {x - w / 2 - k},{y + h / 2}"/>')
lines = n["lines"]
texts = ""
for i, ln_ in enumerate(lines):
ty = y + (i - (len(lines) - 1) / 2) * 17
texts += _t(x, ty, ln_)
return f'<g class="fc-n" data-id="{nid}">{shape}{texts}</g>'
def flow_svg(vw, vh, nodes, edges):
out = f'<svg viewBox="0 0 {vw} {vh}" xmlns="http://www.w3.org/2000/svg" role="img">{_DEFS}'
for e in edges:
pts = e["pts"]
d = "M" + " L".join(f"{px},{py}" for px, py in pts)
out += f'<path class="fc-e" data-id="{e["id"]}" d="{d}"/>'
if e.get("label"):
lx_, ly_ = e["lpos"]
out += _t(lx_, ly_, e["label"], "fc-lb", e.get("anchor", "middle"))
for n in nodes:
out += _node(n)
return out + "</svg>"
class Trace:
"""Builds frames for a flowchart run: current node/edge highlighted, visited ones tinted."""
def __init__(self):
self.frames, self.vis, self.eon = [], set(), set()
def reset(self):
self.vis, self.eon = set(), set()
def step(self, node, edges, ln, vars_, note, out="", set_=None, extra=None):
on = {n: "vis" for n in self.vis}
on.update({e: "on" for e in self.eon})
for e in edges:
on[e] = "cur"
on[node] = "cur"
if extra:
on.update(extra)
self.frames.append(dict(ln=[ln, ln] if isinstance(ln, int) else ln, on=on, vars=vars_, note=note,
out=out, set=set_ or {}))
self.vis.add(node)
self.eon.update(edges)
_LG_FLOW = [["cur", "گام فعلی"], ["vis", "گامهای اجراشده"]]
def _vp(title, svg, code, frames, legend, code_title="شبهکد", pc=True, show_out=False, interval=1300, badge="Step by step"):
return dict(kind="vp", title=title, svg=svg, code=code, codeTitle=code_title, frames=frames, legend=legend,
pc=pc, showOut=show_out, interval=interval, badge=badge)
# ------------------------------------------------------------------ فلوچارت: قبولی یا مردودی
def scene_flow_pass(title="Flowchart: pass or fail"):
nodes = [
dict(id="n_start", t="start", x=300, y=28, w=120, h=34, lines=["شروع"]),
dict(id="n_read", t="io", x=300, y=100, w=200, h=40, lines=["خواندن نمره (" + lt("score") + ")"]),
dict(id="n_dec", t="dec", x=300, y=200, w=230, h=88, lines=["آیا", lt("score ≥ 10") + " ؟"]),
dict(id="n_yes", t="proc", x=480, y=300, w=150, h=40, lines=["چاپ «قبول»"]),
dict(id="n_no", t="proc", x=120, y=300, w=150, h=40, lines=["چاپ «مردود»"]),
dict(id="n_end", t="end", x=300, y=372, w=120, h=34, lines=["پایان"]),
]
edges = [
dict(id="e1", pts=[(300, 45), (300, 80)]),
dict(id="e2", pts=[(300, 120), (300, 156)]),
dict(id="e3", pts=[(415, 200), (480, 200), (480, 280)], label="بله", lpos=(447, 189)),
dict(id="e4", pts=[(185, 200), (120, 200), (120, 280)], label="خیر", lpos=(153, 189)),
dict(id="e5", pts=[(480, 320), (480, 372), (360, 372)]),
dict(id="e6", pts=[(120, 320), (120, 372), (240, 372)]),
]
code = ["شروع",
"نمره را بخوان و در " + lx("score") + " بگذار",
"اگر " + lx("score ≥ 10") + " باشد:",
" «قبول» را چاپ کن",
"در غیر این صورت:",
" «مردود» را چاپ کن",
"پایان"]
T = Trace()
T.step("n_start", [], 1, [("score", "—")], "الگوریتم از «شروع» آغاز میشود. اول با نمرهی ۱۴ اجرا میکنیم.")
T.step("n_read", ["e1"], 2, [("score", 14)], f"نمره را از ورودی میخوانیم و در {_c('score')} میگذاریم: {_c(14)}.")
T.step("n_dec", ["e2"], 3, [("score", 14)], f"لوزی یک <b>تصمیم</b> است. شرط {_c('14 ≥ 10')} <b>درست</b> است، پس مسیرِ «بله» را میرویم.")
T.step("n_yes", ["e3"], 4, [("score", 14)], "مسیر «بله»: عبارت «قبول» چاپ میشود.", out="قبول\n")
T.step("n_end", ["e5"], 7, [("score", 14)], "هر دو مسیر در یک نقطه به «پایان» میرسند. اجرای اول تمام شد.", out="قبول\n")
T.reset()
T.step("n_start", [], 1, [("score", "—")], "حالا همان الگوریتم را با نمرهی دیگری اجرا میکنیم. فلوچارت تغییر نمیکند؛ فقط ورودی فرق دارد.", out="قبول\n")
T.step("n_read", ["e1"], 2, [("score", 7)], f"این بار {_c('score')} برابر {_c(7)} است.", out="قبول\n")
T.step("n_dec", ["e2"], 3, [("score", 7)], f"شرط {_c('7 ≥ 10')} <b>نادرست</b> است، پس مسیرِ «خیر» را میرویم.", out="قبول\n")
T.step("n_no", ["e4"], 6, [("score", 7)], "مسیر «خیر»: عبارت «مردود» چاپ میشود.", out="قبول\nمردود\n")
T.step("n_end", ["e6"], 7, [("score", 7)], "یک فلوچارت برای همهی ورودیها کار میکند؛ هر ورودی فقط یکی از دو مسیر را میرود.", out="قبول\nمردود\n")
return _vp(title, flow_svg(600, 396, nodes, edges), code, T.frames, _LG_FLOW, show_out=True, interval=1500)
# ------------------------------------------------------------------ فلوچارت: بزرگترین عدد
def scene_flow_max(title="Flowchart: the largest of five numbers"):
nodes = [
dict(id="n_start", t="start", x=300, y=24, w=120, h=32, lines=["شروع"]),
dict(id="n_init", t="proc", x=300, y=84, w=250, h=44, lines=["عدد اول را بخوان", "و در " + lt("max") + " بگذار"]),
dict(id="n_more", t="dec", x=300, y=166, w=200, h=64, lines=["عدد دیگری", "مانده است؟"]),
dict(id="n_read", t="io", x=300, y=246, w=190, h=38, lines=["خواندن عدد بعدی (" + lt("x") + ")"]),
dict(id="n_cmp", t="dec", x=300, y=326, w=170, h=62, lines=[lt("x > max") + " ؟"]),
dict(id="n_set", t="proc", x=500, y=326, w=130, h=38, lines=[lt("max ← x")]),
dict(id="n_out", t="io", x=300, y=432, w=190, h=38, lines=["چاپ " + lt("max")]),
dict(id="n_end", t="end", x=300, y=490, w=120, h=32, lines=["پایان"]),
]
edges = [
dict(id="e1", pts=[(300, 40), (300, 62)]),
dict(id="e2", pts=[(300, 106), (300, 134)]),
dict(id="e3", pts=[(300, 198), (300, 227)], label="بله", lpos=(322, 213), anchor="start"),
dict(id="e4", pts=[(300, 265), (300, 295)]),
dict(id="e5", pts=[(385, 326), (435, 326)], label="بله", lpos=(410, 314)),
dict(id="e6", pts=[(300, 357), (300, 392)], label="خیر", lpos=(324, 368), anchor="start"),
dict(id="e7", pts=[(500, 345), (500, 392), (300, 392)]),
dict(id="e8", pts=[(300, 392), (82, 392), (82, 166), (200, 166)]),
dict(id="e9", pts=[(400, 166), (590, 166), (590, 432), (412, 432)], label="خیر", lpos=(496, 154)),
dict(id="e10", pts=[(300, 451), (300, 474)]),
]
code = ["شروع",
"عدد اول را بخوان و در " + lx("max") + " بگذار",
"تا وقتی عدد دیگری مانده است، تکرار کن:",
" عدد بعدی را بخوان و در " + lx("x") + " بگذار",
" اگر " + lx("x > max") + " باشد:",
" " + lx("max ← x"),
"مقدار " + lx("max") + " را چاپ کن",
"پایان"]
nums = [12, 7, 25, 9, 18]
T = Trace()
T.step("n_start", [], 1, [("x", "—"), ("max", "—")], f"ورودی ما پنج عدد است: {_c('12, 7, 25, 9, 18')}. فرض کنید یکییکی از ورودی میرسند.")
mx = nums[0]
T.step("n_init", ["e1"], 2, [("x", "—"), ("max", mx)], f"اولین عدد ({_c(12)}) را میخوانیم و فعلاً آن را بزرگترینِ دیدهشده میگیریم: {_c('max = 12')}.")
inc = ["e2"]
for k, x in enumerate(nums[1:], start=1):
T.step("n_more", inc, 3, [("x", nums[k - 1] if k > 1 else "—"), ("max", mx)],
f"آیا هنوز عددی مانده است؟ بله ({fa(5 - k)} عدد مانده)، پس به مرحلهی خواندن میرویم.")
T.step("n_read", ["e3"], 4, [("x", x), ("max", mx)], f"عدد بعدی را میخوانیم: {_c('x = ' + str(x))}.")
if x > mx:
T.step("n_cmp", ["e4"], 5, [("x", x), ("max", mx)], f"{_c(f'{x} > {mx}')} <b>درست</b> است؛ عدد تازه از بزرگترینِ قبلی بیشتر است.")
mx = x
T.step("n_set", ["e5"], 6, [("x", x), ("max", mx)], f"بزرگترینِ دیدهشده عوض میشود: {_c('max = ' + str(mx))}.")
inc = ["e7", "e8"]
else:
T.step("n_cmp", ["e4"], 5, [("x", x), ("max", mx)], f"{_c(f'{x} > {mx}')} <b>نادرست</b> است؛ {_c('max')} بدون تغییر میماند.")
inc = ["e6", "e8"]
T.step("n_more", inc, 3, [("x", nums[-1]), ("max", mx)], "دیگر عددی نمانده است. مسیرِ «خیر» به چاپ نتیجه میرود.")
T.step("n_out", ["e9"], 7, [("x", nums[-1]), ("max", mx)], f"نتیجه را چاپ میکنیم: {_c(mx)}.", out=f"{mx}\n")
T.step("n_end", ["e10"], 8, [("x", nums[-1]), ("max", mx)], "پایان. حلقهی برگشتی در فلوچارت همان «تکرار» در شبهکد است.", out=f"{mx}\n")
return _vp(title, flow_svg(640, 512, nodes, edges), code, T.frames, _LG_FLOW, show_out=True, interval=1100)
# ------------------------------------------------------------------ فلوچارت: بازی حدس عدد
def scene_flow_guess(title="Flowchart: guess the number (halving)"):
nodes = [
dict(id="n_start", t="start", x=300, y=22, w=120, h=30, lines=["شروع"]),
dict(id="n_init", t="proc", x=300, y=74, w=270, h=38, lines=[lt("low ← 1") + " و " + lt("high ← 100")]),
dict(id="n_guess", t="proc", x=300, y=134, w=270, h=38, lines=[lt("guess") + " ← وسط " + lt("low") + " و " + lt("high")]),
dict(id="n_d1", t="dec", x=300, y=208, w=220, h=68, lines=["آیا", lt("guess < secret") + " ؟"]),
dict(id="n_low", t="proc", x=84, y=208, w=140, h=38, lines=[lt("low ← guess + 1")]),
dict(id="n_d2", t="dec", x=300, y=296, w=220, h=68, lines=["آیا", lt("guess > secret") + " ؟"]),
dict(id="n_high", t="proc", x=514, y=296, w=140, h=38, lines=[lt("high ← guess − 1")]),
dict(id="n_out", t="io", x=300, y=372, w=190, h=36, lines=["چاپ " + lt("guess") + " (پیدا شد)"]),
dict(id="n_end", t="end", x=300, y=424, w=120, h=30, lines=["پایان"]),
]
edges = [
dict(id="e1", pts=[(300, 37), (300, 55)]),
dict(id="e2", pts=[(300, 93), (300, 115)]),
dict(id="e3", pts=[(300, 153), (300, 174)]),
dict(id="e4", pts=[(190, 208), (154, 208)], label="بله", lpos=(172, 197)),
dict(id="e5", pts=[(84, 189), (84, 134), (165, 134)]),
dict(id="e6", pts=[(300, 242), (300, 262)], label="خیر", lpos=(322, 252), anchor="start"),
dict(id="e7", pts=[(410, 296), (444, 296)], label="بله", lpos=(427, 285)),
dict(id="e8", pts=[(514, 277), (514, 134), (435, 134)]),
dict(id="e9", pts=[(300, 330), (300, 354)], label="خیر", lpos=(322, 342), anchor="start"),
dict(id="e10", pts=[(300, 390), (300, 409)]),
]
code = [lx("low ← 1") + " و " + lx("high ← 100") + " را قرار بده",
"تکرار کن:",
" " + lx("guess") + " را برابر وسط " + lx("low") + " و " + lx("high") + " بگیر",
" اگر " + lx("guess < secret") + ": " + lx("low ← guess + 1"),
" در غیر این صورت اگر " + lx("guess > secret") + ": " + lx("high ← guess − 1"),
" در غیر این صورت: " + lx("guess") + " را چاپ کن و تمام کن"]
secret, lo, hi = 73, 1, 100
T = Trace()
T.step("n_start", [], 1, [("low", "—"), ("high", "—"), ("guess", "—"), ("secret", secret)],
f"من عددی بین ۱ تا ۱۰۰ در ذهنم گرفتهام: {_c('secret = 73')}. الگوریتم آن را نمیداند و فقط میتواند «کوچکتر» یا «بزرگتر» بپرسد.")
T.step("n_init", ["e1"], 1, [("low", lo), ("high", hi), ("guess", "—"), ("secret", secret)],
f"بازهی ممکن در ابتدا همهی عددها است: از {_c('low = 1')} تا {_c('high = 100')}.")
inc = ["e2"]
cnt = 0
while True:
g = (lo + hi) // 2
cnt += 1
V = lambda: [("low", lo), ("high", hi), ("guess", g), ("secret", secret)]
T.step("n_guess", inc, 3, V(), f"حدس شمارهی {fa(cnt)}: وسطِ بازه، یعنی {_c(f'({lo} + {hi}) ÷ 2 = {g}')} (گرد به پایین).")
if g < secret:
T.step("n_d1", ["e3"], 4, V(), f"{_c(f'{g} < {secret}')} <b>درست</b> است: حدس ما کوچک است، پس عدد در نیمهی بالایی است.")
lo = g + 1
T.step("n_low", ["e4"], 4, V(), f"نیمهی پایینی را دور میریزیم: {_c('low = ' + str(lo))}. بازه نصف شد.")
inc = ["e5"]
else:
T.step("n_d1", ["e3"], 4, V(), f"{_c(f'{g} < {secret}')} <b>نادرست</b> است؛ پس یا حدس بزرگ است یا درست است.")
if g > secret:
T.step("n_d2", ["e6"], 5, V(), f"{_c(f'{g} > {secret}')} <b>درست</b> است: حدس بزرگ است، پس عدد در نیمهی پایینی است.")
hi = g - 1
T.step("n_high", ["e7"], 5, V(), f"نیمهی بالایی را دور میریزیم: {_c('high = ' + str(hi))}. بازه دوباره نصف شد.")
inc = ["e8"]
else:
T.step("n_d2", ["e6"], 6, V(), f"{_c(f'{g} > {secret}')} هم <b>نادرست</b> است، یعنی {_c('guess = secret')}.")
T.step("n_out", ["e9"], 6, V(), f"پیدا شد: {_c(g)}، با {fa(cnt)} حدس از بین ۱۰۰ عدد.", out=f"{g}\n")
T.step("n_end", ["e10"], 6, V(), f"فقط {fa(cnt)} حدس لازم شد. بدترین حالت برای ۱ تا ۱۰۰ هفت حدس است، چون بعد از هر حدس بازه نصف میشود.", out=f"{g}\n")
break
return _vp(title, flow_svg(600, 446, nodes, edges), code, T.frames, _LG_FLOW, show_out=True, interval=1100)
# ------------------------------------------------------------------ چرخهی fetch-decode-execute
def scene_cpu(title="CPU: fetch, decode, execute"):
rows = [("LOAD 4", ""), ("ADD 5", ""), ("STORE 6", ""), ("HALT", ""), ("5", "a"), ("3", "b"), ("?", "x")]
s = f'<svg viewBox="0 0 770 340" xmlns="http://www.w3.org/2000/svg" role="img">{_DEFS}'
s += _t(145, 14, "حافظه (RAM)", "fc-lb", extra=' font-size="14"')
s += '<path class="fc-e bus" data-id="bus" d="M274,150 L338,150"/>'
for i, (c, lab) in enumerate(rows):
y = 28 + 40 * i
s += (f'<g class="fc-n" data-id="row{i}"><rect x="20" y="{y}" width="250" height="34" rx="7"/>'
+ _t(39, y + 17, str(i), "mono", extra=' font-size="12"')
+ f'<line x1="58" y1="{y}" x2="58" y2="{y + 34}" stroke="currentColor" opacity=".25"/>'
+ _t(72, y + 17, c, "mono", "start", ' data-id="m%d" font-size="14"' % i)
+ (_t(258, y + 17, lab, "fc-tag mono", "end") if lab else "") + '</g>')
s += _t(306, 64, "برنامه", "fc-tag") + _t(306, 232, "داده", "fc-tag")
s += '<g class="fc-n plain"><rect x="340" y="12" width="416" height="316" rx="14"/></g>'
s += _t(548, 34, "پردازنده (CPU)", "fc-lb", extra=' font-size="14"')
s += '<g class="fc-n" data-id="cu"><rect x="362" y="50" width="372" height="52" rx="10"/>' + _t(548, 76, "واحد کنترل: دستور را رمزگشایی میکند") + '</g>'
s += ('<g class="fc-n" data-id="pc"><rect x="362" y="126" width="132" height="64" rx="10"/>' + _t(428, 144, "PC (شمارنده)", "fc-tag")
+ _t(428, 172, "0", "fc-v", extra=' data-id="v_pc"') + '</g>')
s += ('<g class="fc-n" data-id="ir"><rect x="514" y="126" width="220" height="64" rx="10"/>' + _t(624, 144, "IR (دستور فعلی)", "fc-tag")
+ _t(624, 172, "—", "fc-v", extra=' data-id="v_ir"') + '</g>')
s += ('<g class="fc-n" data-id="a"><rect x="362" y="222" width="132" height="64" rx="10"/>' + _t(428, 240, "A (انباره)", "fc-tag")
+ _t(428, 268, "—", "fc-v", extra=' data-id="v_a"') + '</g>')
s += '<g class="fc-n" data-id="alu"><rect x="514" y="222" width="220" height="64" rx="10"/>' + _t(624, 254, "ALU: واحد محاسبه") + '</g>'
s += "</svg>"
code = ["تکرار کن، تا رسیدن به " + lx("HALT") + ":",
" واکشی: دستورِ خانهی " + lx("PC") + " را به " + lx("IR") + " بیاور",
" رمزگشایی: ببین " + lx("IR") + " چه کاری میخواهد",
" اجرا: همان کار را انجام بده"]
pcv, a, m6 = 0, "—", "?"
F = []
def fr(ln, on, note, pc, ir, a_, m6_, set_extra=None):
st = {"v_pc": str(pc), "v_ir": ir, "v_a": a_, "m6": m6_}
if set_extra:
st.update(set_extra)
F.append(dict(ln=[ln, ln] if ln else None, on=on, set=st,
vars=[("PC", pc), ("IR", ir), ("A", a_), ("خانهی ۶ (x)", m6_)], note=note))
fr(None, {}, f"برنامهی ما سه دستور دارد و معادل {_c('x = a + b')} است. مقدار {_c('a = 5')} در خانهی ۴ و {_c('b = 3')} در خانهی ۵ است و جواب باید در خانهی ۶ برود. حافظه و پردازنده با «گذرگاه» (خط ضخیم) به هم وصلاند.", 0, "—", "—", "?")
prog = ["LOAD 4", "ADD 5", "STORE 6"]
descr = ["بارگذاری: مقدارِ خانهی ۴ را در انباره بگذار",
"جمع: مقدارِ خانهی ۵ را با انباره جمع کن",
"ذخیره: مقدار انباره را در خانهی ۶ بنویس"]
cur_a = "—"
for i, ins in enumerate(prog):
fr(2, {"pc": "cur", f"row{i}": "cur", "bus": "cur", "ir": "key"},
f"<b>واکشی (Fetch)</b>: {_c('PC')} میگوید دستور بعدی در خانهی {fa(i)} است. پردازنده آن را از حافظه میخواند و در {_c('IR')} میگذارد، و {_c('PC')} را یکی زیاد میکند.",
i + 1, ins, cur_a, m6)
fr(3, {"ir": "cur", "cu": "cur"}, f"<b>رمزگشایی (Decode)</b>: واحد کنترل دستور {_c(ins)} را میخواند: «{descr[i]}».", i + 1, ins, cur_a, m6)
if i == 0:
cur_a = "5"
fr(4, {"row4": "cur", "bus": "cur", "a": "ok"}, f"<b>اجرا (Execute)</b>: عدد ۵ از خانهی ۴ به انباره میرود. {_c('A = 5')}.", i + 1, ins, cur_a, m6)
elif i == 1:
cur_a = "8"
fr(4, {"row5": "cur", "bus": "cur", "alu": "cur", "a": "ok"}, f"<b>اجرا (Execute)</b>: عدد ۳ از خانهی ۵ میآید، واحد محاسبه (ALU) آن را با انباره جمع میکند: {_c('5 + 3 = 8')}.", i + 1, ins, cur_a, m6)
else:
m6 = "8"
fr(4, {"a": "cur", "bus": "cur", "row6": "ok"}, f"<b>اجرا (Execute)</b>: محتوای انباره در خانهی ۶ نوشته میشود. حالا {_c('x = 8')}.", i + 1, ins, cur_a, m6)
fr(2, {"pc": "cur", "row3": "cur", "bus": "cur", "ir": "key"}, f"واکشیِ دستور آخر: {_c('HALT')}.", 4, "HALT", cur_a, m6)
fr(4, {"cu": "cur", "ir": "cur", "row6": "ok"}, f"{_c('HALT')} یعنی «بایست». کل برنامهی ما یعنی {_c('x = a + b')} با سه بار چرخهی واکشی، رمزگشایی و اجرا انجام شد. کامپیوتر همین چرخه را میلیاردها بار در ثانیه تکرار میکند.", 4, "HALT", cur_a, m6)
lg = [["cur", "بخش فعال"], ["key", "دستورِ آمده در IR"], ["ok", "مقدار تازه نوشته شد"]]
return _vp(title, s, code, F, lg, code_title="چرخهی پردازنده", interval=1500)
# ------------------------------------------------------------------ جمع دودویی
def scene_binadd(title="Adding in binary: 13 + 7"):
xs = [500, 420, 340, 260, 180]
A = [1, 0, 1, 1, 0]
B = [1, 1, 1, 0, 0]
s = f'<svg viewBox="0 0 560 236" xmlns="http://www.w3.org/2000/svg" role="img">{_DEFS}'
for i, x in enumerate(xs):
s += f'<g class="fc-n col" data-id="col{i}"><rect x="{x - 36}" y="10" width="72" height="212" rx="12"/></g>'
s += _t(x, 28, "carry" if False else str(i), "fc-tag mono", extra=' font-size="11"')
labels = [(44, "رقم نقلی"), (92, "A = 13"), (134, "B = 7"), (196, "حاصل")]
for y, tx in labels:
s += _t(66, y, tx, "fc-tag", "middle", ' font-size="13"')
for i, x in enumerate(xs):
s += _t(x, 56, "·", "fc-v", extra=' data-id="c%d"' % i)
s += _t(x, 96, str(A[i]), "fc-v")
s += _t(x, 136, str(B[i]), "fc-v")
s += _t(x, 196, "?", "fc-v", extra=' data-id="s%d"' % i)
s += '<line x1="120" y1="158" x2="540" y2="158" stroke="currentColor" opacity=".45" stroke-width="2"/>'
s += _t(120, 150, "+", "fc-v", "start") + "</svg>"
code = ["برای هر ستون، از راست به چپ:",
" " + "مجموع = بیتِ A + بیتِ B + رقم نقلی",
" بیتِ حاصل = باقیماندهی مجموع بر ۲",
" رقم نقلیِ ستون بعد = خارجقسمتِ مجموع بر ۲"]
F = []
state = {f"c{i}": "·" for i in range(5)}
state.update({f"s{i}": "?" for i in range(5)})
state["c0"] = "0"
F.append(dict(ln=None, on={}, set=dict(state), vars=[("A", "01101"), ("B", "00111")],
note=f"دو عدد پنجبیتی داریم: {_c('01101')} (برابر ۱۳) و {_c('00111')} (برابر ۷). مثل جمع کاغذیِ دهدهی، از <b>راستترین</b> ستون شروع میکنیم و رقم نقلی را به ستون بعد میبریم. در دودویی فقط ۰ و ۱ داریم، پس هر مجموع ۲ یا بیشتر رقم نقلی میسازد."))
carry = 0
res = ""
for i in range(5):
tot = A[i] + B[i] + carry
bit, co = tot % 2, tot // 2
state[f"c{i}"] = str(carry)
state[f"s{i}"] = str(bit)
if i < 4:
state[f"c{i + 1}"] = str(co)
res = str(bit) + res
parts = f"{A[i]} + {B[i]} + {carry} = {tot}"
why = {0: "صفر", 1: "یک", 2: "دو", 3: "سه"}[tot]
if co:
note = f"ستون {fa(i + 1)}: {_c(parts)}. مجموع {why} است و در دودویی برابر {_c(format(tot, 'b'))}. بیتِ حاصل {_c(bit)} را مینویسیم و رقم نقلی {_c(1)} را به ستون بعد میبریم."
else:
note = f"ستون {fa(i + 1)}: {_c(parts)}. مجموع {why} است و در یک بیت جا میشود. بیتِ حاصل {_c(bit)} است و رقم نقلی صفر میماند."
F.append(dict(ln=[2, 4] if i else [1, 1], on={f"col{i}": "cur", f"s{i}": "ok"}, set=dict(state),
vars=[("ستون", i + 1), ("مجموع", tot), ("حاصل تا اینجا", res)], note=note))
carry = co
F.append(dict(ln=None, on={f"s{i}": "ok" for i in range(5)}, set=dict(state),
vars=[("حاصل", "10100"), ("دهدهی", 20)],
note=f"حاصل {_c('10100')} است. برای اطمینان به دهدهی برمیگردیم: {_c('16 + 4 = 20')}، و {_c('13 + 7 = 20')}. جمع دودویی فقط همین قاعدهی ساده است و پردازندهی کامپیوتر آن را با مدارهای کوچکی انجام میدهد."))
lg = [["cur", "ستونی که حساب میشود"], ["ok", "بیتِ حاصل"]]
return _vp(title, s + "", code, F, lg, code_title="قاعدهی جمع", interval=1700)
# ------------------------------------------------------------------ مراحل کامپایل
def scene_pipeline(title="From hello.c to a running program"):
names = ["hello.c", "hello.i", "hello.s", "hello.o", "hello"]
caps = ["کد C", "کد گسترشیافته", "زبان اسمبلی", "کد ماشین", "برنامهی اجرایی"]
tools = ["پیشپردازنده", "کامپایلر", "اسمبلر", "پیوندزن"]
xs = [60, 240, 420, 600, 780]
s = f'<svg viewBox="0 0 840 190" xmlns="http://www.w3.org/2000/svg" role="img">{_DEFS}'
for i in range(4):
x0, x1 = xs[i] + 50, xs[i + 1] - 50
s += f'<path class="fc-e" data-id="t{i}" d="M{x0},96 L{x1},96"/>'
s += _t((x0 + x1) / 2, 74, tools[i], "fc-lb", extra=' font-size="13"')
for i, x in enumerate(xs):
s += (f'<g class="fc-n" data-id="f{i}"><rect x="{x - 50}" y="66" width="100" height="60" rx="10"/>'
+ _t(x, 92, names[i], "mono", extra=' font-size="15"') + _t(x, 112, caps[i], "fc-tag") + '</g>')
s += '<g class="fc-n" data-id="lib"><rect x="640" y="146" width="120" height="30" rx="8"/>' + _t(700, 161, "کتابخانهی استاندارد", "fc-tag") + '</g>'
s += '<path class="fc-e" d="M700,146 L700,106" stroke-dasharray="4 4"/></svg>'
A = ART
F = []
def fr(on, note, code, ctitle, out="", vars_=None):
F.append(dict(ln=None, on=on, note=note, code=[_h.escape(l) for l in code], codeTitle=ctitle, out=out, vars=vars_ or []))
VV = [[("فایل", "hello.c")], [("دستور", "gcc -E"), ("خروجی", "hello.i")], [("دستور", "gcc -S"), ("خروجی", "hello.s")],
[("دستور", "gcc -c"), ("خروجی", "hello.o")], [("دستور", "gcc"), ("خروجی", "hello")], [("دستور", "./hello")]]
fr({"f0": "cur"}, f"ما فقط چند خط C نوشتهایم. پردازنده C را نمیفهمد و فقط دستورهای عددی خودش را اجرا میکند، پس برنامه باید ترجمه شود. این ترجمه چهار مرحله دارد. دستور {_c('gcc hello.c -o hello')} هر چهار مرحله را پشتسرهم انجام میدهد.", A["c"], "hello.c (کد منبع)", vars_=VV[0])
fr({"f0": "ok", "t0": "cur", "f1": "cur"}, f"<b>پیشپردازنده</b>: خطِ {_c('#include <stdio.h>')} با محتوای کامل آن فایل جایگزین میشود و ماکروها باز میشوند. فایل ما از چند خط به حدود {fa(A['n_i'])} خط میرسد. (فقط پایان فایل را میبینید.)", A["i"], "hello.i (پایان فایل)", vars_=VV[1])
fr({"f1": "ok", "t1": "cur", "f2": "cur"}, f"<b>کامپایلر</b>: کد C را به زبان اسمبلی ترجمه میکند؛ دستورهای سادهی پردازنده با نامهای قابلخواندن. جالب است که کامپایلر دید {_c('printf')} هیچ قالبی ندارد و آن را با تابع سادهترِ {_c('puts')} عوض کرد. (روی پردازندهی شما ممکن است متفاوت باشد.)", A["s"], "hello.s (اسمبلی، روی x86-64)", vars_=VV[2])
fr({"f2": "ok", "t2": "cur", "f3": "cur"}, f"<b>اسمبلر</b>: هر دستورِ اسمبلی را به چند بایت عدد تبدیل میکند. مثلاً {_c('55')} یعنی {_c('push')} و {_c('c3')} یعنی {_c('ret')}. این همان <b>کد ماشین</b> است. آدرس {_c('puts')} هنوز خالی (صفر) است.", A["o"], "hello.o (کد ماشین، در مبنای ۱۶)", vars_=VV[3])
fr({"f3": "ok", "t3": "cur", "lib": "key", "f4": "cur"}, f"<b>پیوندزن</b>: کد ما را با کدِ آمادهی کتابخانهی استاندارد (که {_c('puts')} در آن است) یکی میکند و آدرسهای خالی را پر میکند. نتیجه یک فایل اجرایی کامل است.", A["x"], "hello (برنامهی اجرایی)", vars_=VV[4])
fr({"f4": "cur"}, f"حالا سیستمعامل برنامه را در حافظه بارگذاری میکند و پردازنده همان چرخهی واکشی، رمزگشایی و اجرا را روی این بایتها تکرار میکند. نتیجه روی صفحه میآید.", A["r"], "ترمینال", out="Hello, world\n", vars_=VV[5])
lg = [["cur", "مرحله / فایل فعلی"], ["ok", "فایل ساختهشده"], ["key", "ورودی کمکی"]]
return _vp(title, s, [_h.escape(l) for l in A["c"]], F, lg, code_title="hello.c (کد منبع)", pc=False, show_out=True, interval=2600)
# ------------------------------------------------------------------ قدمبهقدم hello.c
_HELLO = ['#include <stdio.h>', '', 'int main(void)', '{', ' printf("Hello, world\\n");', ' return 0;', '}']
def scene_hello(title="Walking through hello.c"):
C = _HELLO
code = [_c_hl(l) for l in C]
F = [
dict(ln=[1, 1], vars=[("خط", "1")], note=f"خطِ {_c('#include')} به کامپایلر میگوید فایلِ {_c('stdio.h')} (ورودی و خروجیِ استاندارد) را وارد کند. بدون آن، {_c('printf')} را نمیشناسد. هر خطی که با {_c('#')} شروع شود برای پیشپردازنده است، نه برای پردازنده."),
dict(ln=[3, 3], vars=[("خط", "3")], note=f"{_c('main')} نقطهی شروعِ هر برنامهی C است. اجرای برنامه همیشه از اولین خطِ {_c('main')} آغاز میشود. {_c('int')} یعنی {_c('main')} در پایان یک عدد صحیح به سیستمعامل برمیگرداند، و {_c('void')} یعنی ورودی ندارد."),
dict(ln=[4, 7], vars=[("خط", "4 تا 7")], note=f"آکولادها ({_c('{ }')}) مرزِ بدنهی تابع را مشخص میکنند. دستورهای داخل آن به ترتیب، از بالا به پایین، اجرا میشوند."),
dict(ln=[5, 5], vars=[("خط", "5")], note=f"{_c('printf')} متن داخل گیومه را روی صفحه چاپ میکند. {_c(chr(92) + 'n')} نویسهی «خط جدید» است و مکاننما را به خط بعد میبرد. هر دستور C با {_c(';')} تمام میشود.", out="Hello, world\n"),
dict(ln=[6, 6], vars=[("خط", "6")], note=f"{_c('return 0')} برنامه را تمام میکند و عدد صفر را به سیستمعامل میدهد. صفر یعنی «همهچیز درست بود». هر عدد دیگر معمولاً نشانهی خطاست.", out="Hello, world\n"),
]
return dict(kind="vp", title=title, svg="", code=code, codeTitle="hello.c", frames=F, legend=[], pc=False,
showOut=True, interval=2400, badge="Step by step")
# ------------------------------------------------------------------ ابزارهای تعاملی
def scene_guess(title="Guess a number in 7 questions", n=100):
return dict(kind="guess", title=title, badge="Try it", n=n)
def scene_bits(title="Eight bits, one number", mode="u", v=65):
return dict(kind="bits", title=title, badge="Try it", mode=mode, v=v)
def scene_float(title="A float is three fields", start="0.1"):
return dict(kind="float", title=title, badge="Try it", start=start)
def scene_bytes(title="Your text as bytes"):
return dict(kind="bytes", title=title, badge="Try it")
def show_flow_pass(): return _widget(scene_flow_pass())
def show_flow_max(): return _widget(scene_flow_max())
def show_flow_guess(): return _widget(scene_flow_guess())
def show_cpu(): return _widget(scene_cpu())
def show_binadd(): return _widget(scene_binadd())
def show_pipeline(): return _widget(scene_pipeline())
def show_hello(): return _widget(scene_hello())
def show_guess(): return _widget(scene_guess())
def show_bits_u(): return _widget(scene_bits("Eight bits, one number", "u", 65))
def show_bits_s(): return _widget(scene_bits("Two's complement: signed numbers", "s", 251))
def show_float(): return _widget(scene_float())
def show_bytes(): return _widget(scene_bytes())
def symbols_html():
"""static flowchart symbol legend (uses currentColor, so it works in light and dark pages)"""
items = [("start", "شروع / پایان"), ("io", "ورودی / خروجی"), ("proc", "پردازش"), ("dec", "تصمیم")]
s = ('<div style="direction:rtl;max-width:760px;margin:10px auto"><svg viewBox="0 0 760 130" xmlns="http://www.w3.org/2000/svg" '
'role="img" aria-label="flowchart symbols" style="width:100%;height:auto;color:inherit;font-family:inherit">')
fill = 'fill="rgba(99,102,241,.10)" stroke="currentColor" stroke-width="1.8"'
xs = [95, 285, 475, 665]
for (k, label), x in zip(items, xs):
y = 48
if k == "start":
s += f'<rect x="{x - 62}" y="{y - 22}" width="124" height="44" rx="22" {fill}/>'
elif k == "io":
s += f'<polygon points="{x - 48},{y - 22} {x + 72},{y - 22} {x + 48},{y + 22} {x - 72},{y + 22}" {fill}/>'
elif k == "proc":
s += f'<rect x="{x - 62}" y="{y - 22}" width="124" height="44" rx="6" {fill}/>'
else:
s += f'<polygon points="{x},{y - 30} {x + 66},{y} {x},{y + 30} {x - 66},{y}" {fill}/>'
s += f'<text x="{x}" y="112" text-anchor="middle" font-size="15" fill="currentColor">{label}</text>'
return s + '</svg></div>'
def show_symbols(): return HTML(symbols_html())