Advertisement
anonymous1184

eq.ahk

Apr 30th, 2021
426
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #Warn All, OutputDebug
  2. SetBatchLines -1
  3.  
  4. equation := "3 + x * 1 = 2 + y"
  5. r := parseEq(equation)
  6. OutputDebug % equation "`n" r[1] " = " r[2] "`n`n"
  7.  
  8. equation := "3 + x * 1 = 3 * 3 + 2 - y * 2 - 8 "
  9. r := parseEq(equation)
  10. OutputDebug % equation "`n" r[1] " = " r[2] "`n`n"
  11.  
  12. equation := "3 + x * 1 = 5 - 4 + 3y"
  13. r := parseEq(equation)
  14. OutputDebug % equation "`n" r[1] " = " r[2] "`n`n"
  15.  
  16. equation := "3 + x * 1 = 10 * 5 - 4 - 8 + y/2"
  17. r := parseEq(equation)
  18. OutputDebug % equation "`n" r[1] " = " r[2] "`n`n"
  19.  
  20. parseEq(equation)
  21. {
  22.     ; Remove spaces
  23.     equation := StrReplace(equation, " ")
  24.  
  25.     ; Split by equality
  26.     equation := StrSplit(equation, "=")
  27.     eq1 := equation[1], eq2 := equation[2]
  28.  
  29.     ; Get precedent operations (mult/div)
  30.     precedent := [], p := 1
  31.     while p := RegExMatch(eq2, "(-?\w+[*|\/]-?\w+)", match, p)
  32.     {
  33.         precedent.Push(match1)
  34.         p += StrLen(match)
  35.     }
  36.  
  37.     ; Replace in the equation
  38.     for i,op in precedent
  39.     {
  40.         parts := StrSplit(op, ["/", "*"])
  41.         fn := InStr(op, "/") ? "div" : "mult"
  42.         res := fn.Call(parts[1], parts[2])
  43.         if res ; If we have a result, means no variable
  44.         {
  45.             if !InStr(res, "-")
  46.                 res := "+" res
  47.             ; We need to remove. If we do now, the lops misbehaves
  48.             precedent[i] := "" ; Emptying, then delete the empties.
  49.         }
  50.         eq2 := StrReplace(eq2, op, res)
  51.     }
  52.  
  53.     ; Remove the empty ones
  54.     for i,val in precedent
  55.         if !val
  56.             precedent.Delete(i)
  57.  
  58.     ; Get parts for eq2
  59.     parts2 := [], p := 1
  60.     while p := RegExMatch(eq2, "([+|-]?\w+)", match, p)
  61.         parts2.Push(match1)
  62.         , p += StrLen(match)
  63.  
  64.     ; Arithmetical inversion
  65.     for i,part in parts2
  66.     {
  67.         if (part ~= "i)[a-z]") ; Skip variables
  68.             continue
  69.         rem := part
  70.         part := StrReplace(part, "+") * -1
  71.         if !InStr(part, "-")
  72.             part := "+" part
  73.         eq1 .= part
  74.         eq2 := StrReplace(eq2, rem,,, 1)
  75.     }
  76.  
  77.     ; Restore precedent operations
  78.     for i,op in precedent
  79.         eq2 .= op
  80.  
  81.     ; Return each equation
  82.     return [eq1, eq2]
  83. }
  84.  
  85. div(a, b)
  86. {
  87.     return a / b
  88. }
  89.  
  90. mult(a, b)
  91. {
  92.     return a * b
  93. }
  94.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement