Створіть TeX для набору фрактала трикутника Sierpinski


30

Виклик

Напишіть код, який виводить код математичного рівняння TeX (LaTeX) (подано нижче), який буде набирати фрактал трикутника Sierpinski з 5 рівнів. Найкоротший код виграє .

Деталі

TeX (та друзі, як LaTeX тощо) - це складна система набору тексту. Він може надавати довільні вкладені складні вирази для математичних формул. Випадково цей "вкладений комплекс" також описує фрактали. З MathJaX надано наступне

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

наступним простим текстовим кодом математичного рівняння, що складається з вкладених супер- та підкриптів:

{{{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}^{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}_{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}}^{{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}^{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}_{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}}_{{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}^{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}_{{{x^x_x}^{x^x_x}_{x^x_x}}^{{x^x_x}^{x^x_x}_{x^x_x}}_{{x^x_x}^{x^x_x}_{x^x_x}}}}}

Зауважте, це лише 5-рівневе гніздування. Вам не потрібно генерувати $...$або $$...$$іншу розмітку, необхідну для запуску / закінчення математичного рівняння в TeX & Co. Ви можете попередньо переглянути створений TeX у багатьох онлайн-редакторах, наприклад: http://www.hostmath.com, але ви можете знайти багато інші теж. Це питання надихнуло на дискусію з друзями .

Оновлення

Існує подібне питання, але воно набагато більш загальне і дасть різні рішення. Я хотів побачити дійсно колмогоров-складність для дуже фіксованого простого коду, який в одній системі (TeX) є повністю явним, а в іншій стискається. Це також стосується nзамість коментарів на 5 рівнях.


2
Hello; I closed your question as a duplicate because I believe that answers can be too trivially modified from the other question to answer this question. However, I like the idea and I think it looks pretty cool! :)
HyperNeutrino

2
For what it's worth, I reopened this question as I do not see the code as being trivially modifiable to translate from one to the other.
AdmBorkBork

4
That's far too quick to be accepting a solution!
Shaggy


2
When I saw this challenge, this answer came to my mind... codegolf.stackexchange.com/a/6830/67961 and... it was yours
J42161217

Відповіді:




14

plain TeX, 29 bytes

\def~#1x{{#1x_#1x^#1x}}~~~~~x

That outputs what others have output. But if we need the code to be compilable it would be 6 bytes more

\def~#1x{{#1x_#1x^#1x}}$~~~~~x$\bye

Explanation

~ is an active character in TeX, so we can give it a (new) definition.

\def~#1x{{#1x_#1x^#1x}} defines ~ as a macro, so that when TeX sees ~, it does the following:

  • Read everything up to the next x, and call that #1 (pattern-matching).
  • Replace the whole thing with {#1x_#1x^#1x}

For example, ~ABCx would get replaced with {ABCx_ABCx^ABCx}.

When ~~~~~x is used, #1 is ~~~~, so the whole thing gets replaced with {~~~~x_~~~~x^~~~~x}. And so on.

Once we have the long string, we can print it out to terminal with \message (and ending with a \bye so TeX stops), so \message{~~~~~x}\bye. Or typeset the resulting expression (as a mathematical formula), by surrounding it in $s : so $~~~~~x$\bye.


Sorry if there's anything wrong, first answer here.
Manuel

For a big n (rather than 5) it could be more efficient to create a macro that outputs a list of n tildes ~ rather than writing ~~~~~. Plus it would look better if the whole expression is typeset under \scriptscriptstyle.
Manuel

Nice trick… can you add an explanation, or mind if I add one? This illustrates a nice feature of pattern-matching in TeX macros, which is not a feature common to many languages (that I know of).
ShreevatsaR

I will add it, but feel free to edit.
Manuel

Oops, didn't see your comment… added a very similar explanation; feel free to reject. +1 for the nice answer!
ShreevatsaR

4

05AB1E, 17 bytes

'x5F'x¡"{x^x_x}"ý

Try it online!

Explanation

'x                  # push "x"
  5F                # 5 times do
    'x¡             # split on "x"
       "{x^x_x}"ý   # join on "{x^x_x}"

Other programs at the same byte-count include

"{x^x_x}"©4F'x¡®ý
'x5F'x"{x^x_x}".:

I feel like "{x^x_x}" can be reduced ._.
Magic Octopus Urn

4

PowerShell,  44  35 bytes

"'x'"+"-replace'x','{x^x_x}'"*5|iex

Try it online!

Uses string multiplication to repeatedly -replace xes with the sub- and super-scripts, then output.

Saved 9 bytes thanks to Joey.


"'x'"+"-replace'x','{x^x_x}'"*5|iex is a bit easier, no?
Joey

@Joey Oh, that's a clever way of doing it. Thanks!
AdmBorkBork


2

JavaScript (ES6), 45 42 37 bytes

f=n=>n>4?'x':[...'{^_}'].join(f(-~n))

Edit: Saved 3 2 bytes thanks to @Arnauld. Specifying 5 still costs me 2 bytes; this 41 40 35-byte version takes a parameter instead:

f=n=>n?[...'{^_}'].join(f(n-1)):'x'



2

Japt, 21 20 18 bytes

5Æ="\{^_}"¬qUª'xÃÌ

Test it


Explanation

5Æ             Ã

Generate an array of length 5 and map over it.

"\{^_}"¬

Split a string to an array of characters

qUª'x

Rejoin (q) to a string using the current value of U or (ª) "x".

=

Assign the result of that to U.

Ì

Get the last element in the array.


Alternatives, 18 bytes

Same as above but reducing the array after it's been created.

5o r@"\{^_}"¬qX}'x

Test it

The recursive option.

>4©'xª"\{^_}"¬qßUÄ

Test it


1

Java (OpenJDK 8), 179 167 bytes

@Neil port

interface Y{static void main(String[]a){System.out.println(t.apply(1));}java.util.function.Function<Integer,String>t=N->N>0?Y.t.apply(N-1).replace("x","{x^x_x}"):"x";}

Try it online!


I think you it is shorter to write t as a real functio instead of a lambda
Roman Gräf

If you use an entire program, t.apply(1) should be t.apply(new Integer(a[0])) instead. But why not just post a method? String t(int n){return n>0?t(n-1).replace("x","{x^x_x}"):"x";} And if the requirement of the challenge would be a full program (which isn't), using a Java 7 recursive method would be shorter than a lambda: interface Y{static void main(String[]a){System.out.print(t(new Integer(a[0])));}static String t(int n){return n>0?t(n-1).replace("x","{x^x_x}"):"x";}}
Kevin Cruijssen

0

Wolfram Language (Mathematica) - 40 characters

Summarizing 3 best answers here:

40 bytes:

Nest["{"<>#<>"_"<>#<>"^"<>#<>"}"&,"x",5]

41 bytes:

Nest[StringReplace["x"->"{x^x_x}"],"x",5]

44 bytes:

Last@SubstitutionSystem["x"->"{x^x_x}","x",5]

3
It is not recommended to answer your own challenge, without leaving others a couple of days first.
Mr. Xcoder

1
Does your first code snippet not require 41 bytes?
Jonathan Frech

@Mr.Xcoder apologies, the editor form suggested as an option to post my own answer. Should I delete my answer?
Vitaliy Kaurov

@VitaliyKaurov I think you should, other users will probably receive this badly.
Mr. Xcoder


Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.