Skip to content

Instantly share code, notes, and snippets.

@iantrich
Last active December 5, 2024 05:53
Show Gist options
  • Select an option

  • Save iantrich/de3cb473920048f89ed00f29e69962f0 to your computer and use it in GitHub Desktop.

Select an option

Save iantrich/de3cb473920048f89ed00f29e69962f0 to your computer and use it in GitHub Desktop.
quick mathSolver
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
String input = "Here is $$$someVar=4,other=5:other+someVar*other$$$, and here is $$$someVar=4,b=5:someVar+someVar*6$$$, and lastly with no variables is $$$1+2$$$.";
// Regex pattern to match substrings surrounded by $$$
String regex = "\\$\\$\\$(.*?)\\$\\$\\$";
// Compile the pattern
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
// List to hold the extracted substrings
List<String> extractedEquations = new ArrayList<>();
// Find matches
while (matcher.find()) {
extractedEquations.add(matcher.group(1)); // Group 1 is the content between $$$
}
// Print the raw equations
System.out.println("Extracted Equations: " + extractedEquations);
// Iterate through the raw equations to find variables
for (String rawEquation : extractedEquations) {
List<String> variables = new LinkedList<String>(Arrays.asList(rawEquation.split("[,:]")));
System.out.println("Equation pieces found " + variables.size());
String equation = variables.remove(variables.size() - 1); // The last element in the list will be your equation
System.out.println("The equation is: " + equation);
// Iterate through the variables, split on '=' and find/replace in your equation
for (String variable : variables) {
List<String> declaration = new LinkedList<String>(Arrays.asList(variable.split("=")));
System.out.println("The variable " + declaration.get(0) + " is equal to " + declaration.get(1));
// TODO you'll want to match whole variable names between operators as they could be partially matching and then replaced leaving you with an unusable or wrong equation. e.g. $$$var=1,var2=2:var+variable2$$$, if not handled properly would result in "1+1iable2" instead of "1+2"
equation = equation.replaceAll(declaration.get(0), declaration.get(1));
}
System.out.println("The equation after replacing variables: " + equation);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment