19
\$\begingroup\$

CGCC hasn't always had MathJax. Back in the dark ages, it would have been necessary to write \$x^2\$ as (the horror!). In this challenge, you will be given some math which may include superscripts, and you should convert it to MathJax.

Input:

Input will consist of one or more letters a to z, some with superscripts. Answers may choose to handle only upper or lower case, or both.

Examples of inputs would be x, , xy², x²y², or x²yz. There will never be duplicates of a letter (so xx or x²zx won't be given), but you cannot assume the superscripts or letters are in any particular order. The first character in the input will never be a superscript.

Superscripts consist of the characters ¹, ², ³, , , , , , , and . These can be joined into multi-digit superscripts, like x²¹ (\$x^{21}\$). You can assume or ¹ are never given as superscripts, and there will not be leading s.

Output:

Output should consist of a MathJax representation of the input. This must start and finish with \$.

Characters without superscripts can be written as themselves; xyz would simply become \$xyz\$. Characters with superscripts should be followed by ^, then the superscript written with normal digits and wrapped in {}. For example, x²¹z⁴⁸⁸ would become \$x^{21}z^{488}\$. Optionally, single digit superscripts can be written without the {}. For example, could be either \$x^{2}\$ or \$x^2\$.

Test cases:

x           \$x\$
xyz         \$xyz\$
x²          \$x^{2}\$ OR \$x^2\$
x²¹         \$x^{21}\$
x²yz²       \$x^{2}yz^{2}\$ OR \$x^2yz^2\$
xy¹¹z       \$xy^{11}z\$
x⁴          \$x^{4}\$ OR \$x^4\$
x⁶⁰         \$x^{60}\$

Other:

This is , shortest answer (in bytes) per language wins!

\$\endgroup\$
2
  • 2
    \$\begingroup\$ x⁶⁰ \$x^{40}\$ ?? how does 60 turn into 40? \$\endgroup\$
    – lyxal
    Apr 21 at 4:11
  • 11
    \$\begingroup\$ @Lyxal With lots of carelessness :p \$\endgroup\$ Apr 21 at 4:12

17 Answers 17

6
\$\begingroup\$

JavaScript, 55 bytes

e=>`\\$${e.normalize`NFKD`.replace(/\d+/g,`^{$&}`)}\\$`

Try it online!

\$\endgroup\$
6
\$\begingroup\$

Husk, 43 41 40 bytes

`JD;"¦$"ṁ?Iȯ:'^`J"{}"ṁos€"¹²³⁴⁵⁶⁷⁸⁹"Λ√ġ√

Try it online!

The superscripts are 1 byte each since they're in Husk's codepage.

I wanted to replace +₁+₁ with S+`+"¦$" but it didn't work for some reason.. :(

-2 bytes borrowing the indexing idea from hyper-neutrino.

-1 byte from Leo.

Explanation

`JD;"¦$"ṁ?Iȯ`:'}+"^{"ṁos€"¹..⁹"Λ√ġ√
                              ġ√ group on alphabets
     ṁ                           map and concatenate with:
      ?                            if:
                            Λ√      the group is alphabetical
       I                             leave as is
        ȯ`:'}+"^{"ṁos€"¹..⁹"        otherwise:
                  ṁȯ                  map and concat each char to:
                     €"¹..⁹"           index in ¹..⁹(0 if not present)
                    s                  cast to string
             +"^{"                    prepend "^{"
         `:'}                         append '{'
`JD;"¦$"                            surround the final string with "\$"
                     
\$\endgroup\$
5
\$\begingroup\$

Factor, 148 92 77 70 bytes

[ nfkd R/ \d+/ [ "^{""}"surround ] re-replace-with "\\$%s\\$"sprintf ]

It doesn't work on TIO because TIO is missing nfkd which is perfectly extant in a proper copy of 0.98. So have a screenshot of running the quotation in the listener.

enter image description here

Explanation:

It's a quotation (anonymous function) that takes a string from the data stack as input and leaves a string on the data stack as output.

  • nfkd Convert a string to normalization form KD. (Turn "²" into "2", for example.)

  • R/ \d+/ A regular expression that matches numbers.

  • [ "^{""}"surround ] re-replace-with Replace numbers with themselves surrounded by ^{...}.

  • "\\$%s\\$"sprintf Surround the result with \\$.

\$\endgroup\$
1
  • \$\begingroup\$ Ooh, nfkd does almost half of the job :P \$\endgroup\$
    – Bubbler
    Apr 21 at 6:39
4
\$\begingroup\$

Brachylog, 65 59 bytes

~c{{∧"⁰¹²³⁴⁵⁶⁷⁸⁹"},?XdX&|{~h.↰₂i}ᵐtᵐcṫ,"}^{"↻↻}ᵐ{,"\$"↔}ⁱ²c

Try it online!

:/

\$\endgroup\$
3
\$\begingroup\$

JavaScript (Node.js), 92 89 bytes given that no constant(\$2x^3\$)

x=>`\\$${[...x].map(c=>c=='¹'?1:escape(c).slice(-1)).join``.replace(/\d+/g,'^{$&}')}\\$`

Try it online!

JavaScript (Node.js), 99 94 bytes

x=>`\\$${x.replace(/[~-⁹]+/g,s=>`^{${[...s].map(c=>c=='¹'?1:escape(c+c)[5]).join``}}`)}\\$`

Try it online!

76 71 bytes if allowed

x=>`\\$${x.replace(/[~-⁹]/g,c=>`{}^${c=='¹'?1:escape(c+c)[5]}`)}\\$`

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Would \W work instead of [~-⁹]? \$\endgroup\$
    – Arnauld
    Apr 21 at 12:12
  • \$\begingroup\$ @Arnauld Assuming existance of numbers so no \W, though question doesn't \$\endgroup\$
    – l4m2
    Apr 21 at 19:21
3
\$\begingroup\$

Ruby, 67 61 bytes

->s{'\$'+s.unicode_normalize(:nfkd).gsub(/\d+/,'^{\0}')+'\$'}

Try it online!

unicode_normalize(:nfkd) seems quite long, but turns out to be 4 bytes shorter than tr('⁰¹²³⁴-⁹','0-9').

\$\endgroup\$
1
  • \$\begingroup\$ -1 byte: ->s{['\$']*2*s.unicode_normalize(:nfkd).gsub(/\d+/,'^{\0}')} \$\endgroup\$
    – G B
    Apr 21 at 12:20
3
\$\begingroup\$

Jelly, 38 bytes

ØJiⱮ_81»48Ọ⁾^{;;”}
O>Ø⁷Œgṁ@µ¹Çƭ€⁾\$,ṁ3

Try it online!

-4 bytes thanks to Jonathan Allan ("subtract 81, max with 48" is shorter than "logical OR 129, subtract 81") (prepend \$ and mold like 3 is shorter than prepend \$ + append \$) (2-byte built-in for 128 saves a byte)

Unfortunately I can't generate a test suite for this because tie will keep cycling, which causes various issues.

Might add explanation later after golfing (if I do either). TL;DR, groups by superscripts and non-superscripts, the applies the last link to every other element using tie-each, and the last link indexes into jelly's codepage, which contains ^1 through ^9, uses or to fix the lack of ^0 (absent items have index 0 since jelly is 1-indexed), subtract the offset, turn back to chr, and then apply formatting

\$\endgroup\$
3
  • \$\begingroup\$ You can save a couple of bytes by maxing with 42 after subtracting 81 (rather than ORing with 129 first). You can save a couple more by prepending the \$ and then moulding like three to get one on the end too (using output smashing of a full-program). TIO \$\endgroup\$ Apr 21 at 17:02
  • \$\begingroup\$ @JonathanAllan oh that's clever. also good use of mold there! \$\endgroup\$
    – hyper-neutrino
    Apr 21 at 17:03
  • 1
    \$\begingroup\$ Oh one of the four byte saves is using the built-in for 128. \$\endgroup\$ Apr 21 at 17:04
3
\$\begingroup\$

Raku, 35 bytes

{'\$'~S:g/\d+/^\{$/}/~'\$'}o~*.NFKD

Try it online!

This expression is the composition of two functions with the o operator. The right-hand function (the first to be applied) is ~*.NFKD, which calls the NFKD method on its argument, then stringifies it, which turns superscript numbers into regular numbers. The left-hand function (between the brackets) constructs the final string by prepending and appending \$ and using a regex to replace sequences of consecutive digits with ^{digits}.

\$\endgroup\$
2
\$\begingroup\$

Python 3, 169 bytes

def k(s):
 g="¹²³⁴⁵⁶⁷⁸⁹⁰";h="\$"
 for y,x in enumerate(s):
  if s[y]in g:h+='^{'+x;continue
  if(x not in g)and(s[y-1]in g):h+='}'
  h+=x
 return h+'\$'

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ This doesn't with multiple consecutive characters or with superscripts at the end: TIO \$\endgroup\$
    – ovs
    Apr 21 at 6:14
  • \$\begingroup\$ This puts superscripts in the result as well. \$\endgroup\$
    – Sid
    Apr 21 at 6:57
2
\$\begingroup\$

Red, 170 bytes

func[a][s: charset extract t:"⁰0¹1²2³3⁴4⁵5⁶6⁷7⁸8⁹9"2
parse a[any[any[not s skip]ahead s insert"^^{"any[change
set c s(t/:c)]insert"}"]]rejoin["\$"a"\$"]]

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Python 3, 245 241 bytes

def m(a):
	b='⁰¹²³⁴⁵⁶⁷⁸⁹';r=c=0;o='\\$'
	for l in a:
		if l in b:
			n=str(b.index(l))
			if not r:o+='^{'+n;r=1
			elif r:o+=n
			if c==len(a)-1:o+='}'
		elif l not in b and r:o+='}'+l;r=0
		else:o+=l
		c+=1
	return o+'\\$'

Try it online! -4 bytes thanks to pxeger.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome to Code Golf, and nice first post! I'd recommend checking out our Tips for Golfing in Python page to see how you might be able to shrink this more \$\endgroup\$
    – pxeger
    Apr 21 at 7:21
  • \$\begingroup\$ @pxeger thanks, that decreased it by 4 bytes \$\endgroup\$
    – Sid
    Apr 21 at 7:30
2
\$\begingroup\$

Retina 0.8.2, 36 bytes

T`⁰¹²³⁴-⁹`d
\d+
{$&}
^|$
\$

Try it online! Link includes test cases. Explanation:

T`⁰¹²³⁴-⁹`d

Convert the superscripts to digits. (The ¹²³ cost 2 bytes each and the ⁰⁴⁹ cost three bytes each.)

\d+
{$&}

Wrap the superscripts in {}s.

^|$
\$

Wrap the entire string in MathJax tags.

\$\endgroup\$
2
\$\begingroup\$

Charcoal, 29 bytes

\$F⁺S\$¿›ιz⊞υVι«∧υ⪫{}⪫υωι≔⟦⟧υ

Try it online! Link is to verbose version of code. Explanation:

\$

Print the leading MathJax tag.

F⁺S\$

Append the trailing MathJax tag to the input string. This ensures that a subscript is not the last character in the loop.

¿›ιz

If the current character is greater than a z, then...

⊞υVι

... evaluate it as a Charcoal digit and push the result to the predefined empty list.

«

Otherwise,

∧υ⪫{}⪫υω

If there is a superscript to print, then join the digits together and wrap them in {}s.

ι

Output the next character.

≔⟦⟧υ

Clear any superscript.

\$\endgroup\$
2
\$\begingroup\$

PHP, 75 73 bytes

fn($a)=>preg_replace('/\d+/','^{$0}',normalizer_normalize("\\$$a\\$",8));

https://3v4l.org/mJZKd

Works with PHP 7.4+ with the intl extension, doesn't work on TIO.

8 is the value of the Normalizer::FORM_KD constant, so this converts superscript characters to digits using NFKD.

\$\endgroup\$
2
\$\begingroup\$

Zsh --extendedglob, 121 116 67 bytes

Saved a lot by enabling extendedglob for the (#m) and ## glob specs.

<<<${1//(#m)[^a-z]##/^\{${MATCH//(#m)?/$[c=#MATCH,c-185?c&15:1]}\}}

Try it online (has old comments) Try it online!

${1//$find/$repl}  # replace all instances of $find with $repl
[^a-z]##           # The glob [^a-z]## is equivalent to the regex [^a-z]+
(#m)[^a-z]##       # Set $MATCH to the value matched by [^a-z]]##
(#m)?              # "?" matches any single character
$[$e1,...,$en]     # $[arithmetic substitution], substitutes the result of $en
c=#MATCH           # Set c to the codepoint of the first character of $MATCH
c&15               # ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ⁰ => #c & 15 => 9 1 2 3 4 5 6 7 8 9 0
c-185?c&15:1       # If $MATCH is ¹ (codepoint 185), output 1, else codepoint & 15
<<<$str            # prints $str to stdout
\$\endgroup\$
1
\$\begingroup\$

JavaScript (Node.js), 60 bytes

s=>`\\$${s.replace(/\W+/g,n=>`^{${n.normalize`NFKD`}}`)}\\$`

Try it online!

\$\endgroup\$
0
\$\begingroup\$

05AB1E, 34 bytes

"⁰¹²³⁴⁵⁶⁷⁸⁹"S9Ý€"^{ÿ}":„\$.ø…}^{õ:

Try it online!

Explained:

"..."S                        # Push [⁰...⁹]
      9Ý                      # Push [0...9]
        €"^{ÿ}"               # Surround each element of [0...9] with ^{ }
               :              # Replace each element of [⁰...⁹] with its counterpart in [^{0}...^{9}]
                   .ø         # Surround input with...
                „\$           # \$ \$
                          :   # Replace...
                     …}^{     # instances of  "}^{"
                         õ    # with an empty string
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.