Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package regul;
- import java.util.*;
- import java.util.regex.*;
- public class Algorithm {
- private ArrayList <Rule> base = new ArrayList<>();
- public Algorithm (String allRules) {
- // Removing all whitespaces
- String allRulesFmt = allRules.replaceAll("\s", "");
- // Splitting each rule
- String[] splitRules = allRulesFmt.split(";");
- // Regex to validate rules
- Pattern ruleRegex = Pattern.compile("^([A-Za-z0-9#]*)->\\.?([A-Za-z0-9#]*)$");
- for (var rule : splitRules) {
- // Checking if the rule is valid
- Matcher matcher = ruleRegex.matcher(rule);
- if (matcher.matches()) {
- // Checking if the rule is terminating
- boolean terminating = rule.contains(".");
- // Getting left and right part
- String left = matcher.group(1);
- String right = matcher.group(2);
- // Adding the rule to the base
- base.add(new Rule(Pattern.compile(left), right, terminating));
- // If the rule is invalid
- } else {
- // Invalidate the entire set
- base = null;
- return;
- }
- }
- }
- public String eval(String begin, int cnt) {
- // Creating res variable to populate later
- String res = begin;
- for (var i = 0; i < cnt;) {
- // Variable to check if any of the rules was applied in the cycle
- boolean didWork = false;
- // Looping through each rule
- for (var rule : base) {
- // If rule adds a character
- if (rule.left.toString().equals("")) {
- // Add it to the result
- res += rule.right;
- // If the rule is terminating
- if (rule.end) {
- // Return the result
- return res;
- }
- // Increment the counter and mark the done work
- i++;
- didWork = true;
- // Else if the rule can be applied to the string
- } else if (rule.left.matcher(res).results().findAny().isPresent()) {
- // Apply the rule
- Matcher matcher = rule.left.matcher(res);
- res = matcher.replaceAll(rule.right);
- // If the rule is terminating
- if (rule.end) {
- // Return the result
- return res;
- }
- // Increment the counter and mark the done work
- i++;
- didWork = true;
- }
- }
- // Checking if any of the rules was applied to the string
- if (!didWork) {
- return res;
- }
- }
- return "undefined";
- }
- public boolean isGood() {
- return base != null;
- }
- private class Rule {
- Pattern left;
- String right;
- boolean end;
- Rule (Pattern sl, String sr, boolean end) {
- this.left = sl;
- this.right = sr;
- this.end = end;
- }
- @Override
- public String toString() {
- return left + " ->" + (end?".":"") + " " + right;
- }
- }
- // .... methods
- // ......
- // ......
- @Override
- public String toString() {
- StringBuilder res;
- if (base == null) res = new StringBuilder("Error Algorithm");
- else {
- res = new StringBuilder("Algorithm = [");
- for (Rule rule : base) {
- res.append(" \n ").append(rule.toString());
- }
- res.append("\n]");
- }
- return res.toString();
- }
- }
Add Comment
Please, Sign In to add comment