The Challenge

Given an algebraic expression (eg 2ab, change it so it follows standard convention rules.

The Rules

  • Letters should be in alphabetical order. ie 2ab is allowed but not 2ba.
  • Numbers should always go first. ie 2ab is allowed but ab2 is not.
  • Exponentiation will be given as a^b to mean a to the power of b.
  • These rules must be applied to every sub-expression. ie 2ab + ba3 becomes 2ab + 3ab, 2vd * vd5 becomes 2dv * 5dv. This must work for at least addition, subtraction, multiplication, division, modulus and exponentiation.
  • Exponentiation is assumed to belong to the variable immediately preceding it and must stay with the variable it is assigned to. ie 2ba^2 becomes 2a^2b. This means that all variables to the right of ^ are part of the exponentiation.

Sample Input/Output

Input can be given with any amount of white space, which must be ignored. Output can use either one space or none. For example, 2ab +3ba could become 2ab + 3ab or 2ab+3ab

Input -> Output
2ba -> 2ab
4gb + 5vh * gh7 -> 4bg + 5hv * 7gh
2ba^2 -> 2a^2b
5xk^2ba -> 5k^2abx

(The last couple of outputs don't make sense mathematically because of order of operations, but you don't have to worry about that.)


Standard code golf, shortest answer in bytes wins. Answer can be a program which takes input, or a function (can be anonymous).

  • \$\begingroup\$ Do we have to deal with expressions like 2a2b or 2aba? \$\endgroup\$ Aug 8 '16 at 8:54
  • 1
    \$\begingroup\$ @MartinEnder No. \$\endgroup\$
    – Mathime
    Aug 8 '16 at 9:00
  • \$\begingroup\$ “This must work for at least addition, subtraction, multiplication, division, modulus and exponentiation.” You should add test cases for these, then. (Although I advise you just simplify the challenge.) \$\endgroup\$
    – Lynn
    Aug 8 '16 at 9:35
  • 2
    \$\begingroup\$ You should maybe write an EBNF-like description of the possible input strings. Will there be parentheses? Spaces halfway through a monomial? \$\endgroup\$
    – Lynn
    Aug 8 '16 at 9:37
  • \$\begingroup\$ Can you provide an example of an expression with multiple exponents? I am not sure what the output will look like. \$\endgroup\$
    – xsot
    Aug 8 '16 at 10:47

Ruby, 112 + 1 (p flag) = 113 bytes

Run as ruby -pe with the code surrounded by single quotes. Full program, even if it looks like just a recursive function at the beginning.

f=->s{s.scan(/(\w)(\^.+)?/).map{|a,b|[a,b&&?^,b&&f[b]]}.sort_by &:first};gsub(/[\w^]+/){f[$&]*""};gsub(/\s+/,"")

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