What steps should I follow to create a string validator that works with Deterministic Finite Automata?

I'm currently working with a DFA that requires a specific regular expression to validate a given string, which is (bab | bbb) (a* b*) (a* | b*) (ba)* (aba) (bab | aba)* bb (a | b)* (bab | aba) (a | b*)

My approach involves defining transitions to determine the validity of an inputted string:

class DFA_Exp1 {
    constructor() {
      // Transitions are defined within an object
      this.transitions = {
        0: { a: "invalid", b: 1 },
        1: { a: 2, b: 2 },
        2: { a: "invalid", b: 3 },
        ...
      };
  
      this.acceptingState = 17;
    }

    validateInput(input) {
        let currentState = 0; // Start from initial state
    
        for (let i = 0; i < input.length; i++) {
          const symbol = input[i];
    
          if (!this.transitions[currentState]) {
            return "invalid";
          }
    
          currentState = this.transitions[currentState][symbol];
    
          if (currentState === "invalid" || currentState === undefined) {
            return "invalid";
          }
        }

        if (currentState === this.acceptingState) {
            return "valid";
        }
        
        return "invalid";
        
    }  
}

I've noticed that my current implementation does not seem to work as expected, as the currentState always remains at 0 and strings are constantly flagged as invalid.

I'm wondering if there might be a more effective way to validate strings or if there's an issue with my validateInput method?

(I'm still quite new to JavaScript and automata theory)

Answer №1

If you need to validate a string using regex, the following code can be helpful:

const text = "bab";
const pattern = /^(bab | bbb) (a* b*) (a* | b*) (ba)* (aba) (bab | aba)* bb (a | b)* (bab | aba) (a | b)*$/;
pattern.exec(text);

I chose to use the syntax with /s for defining the regex, although it may seem confusing initially. Alternatively, you can also opt for the constructor method which achieves the same result but is more explicit:

const pattern = new RegExp("^(bab | bbb) (a* b*) (a* | b*) (ba)* (aba) (bab | aba)* bb (a | b)* (bab | aba) (a | b)*$");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Shuffle a Document Fragment in a random order before adding it to the DOM using JavaScript

My JavaScript code is generating a text area and button dynamically. I have successfully implemented it so that when a value is entered into the text area and the button is clicked, a random number of SPAN tags are created. Each character from the input va ...

Angular Material Design auto-complete textbox with assertive selection

Presently, I am utilizing Angular Material Design and everything is functioning as expected. However, I am now looking to implement autocomplete (Angular Material Design) in a way that forces the user to always choose an option without the ability to manua ...

Regular Expression - Locate all numerical values within text formatted with HTML

I am attempting to locate all the numbers within an HTML document. However, I want to ensure that I exclude numbers that are part of a word, such as "o365", "high5", and similar instances. Here is my current approach, but it does not successfully avoid w ...

Has the zip creation tool in the Google Doodle on April 24th been coded entirely in JavaScript?

Was the Gideon Sundback Google doodle created using JavaScript? I attempted to follow along in Firebug, but I couldn't quite grasp its implementation details. Any ideas on how it was possibly implemented? Any insights on the potential techniques use ...

Comparison of Static Site Generation (SSG) with Server-Side Rendering and Client-Side Rendering

The lack of concrete information surrounding the inner workings of Client-Side Rendering (CSR), Server-Side Rendering (SSR), and Static Site Generation (SSG) is truly perplexing to me. Despite numerous articles that vaguely touch on these concepts, I have ...

Display Issue: No Uploadify Alert Appears After File Upload

I currently have the following code for using uploadify: <link href="/uploader/uploadify.css" type="text/css" rel="stylesheet" /> <script type="text/javascript" src="/uploader/jquery-1.5.1.js"></script> <script type="text/javascript" ...

Steps to deactivate a button upon clicking in vue.js

I need assistance with my voting application. I am looking to implement a feature that disables the voting button after it has been clicked. Can someone provide guidance on how to achieve this? template <v-btn v-for="choice in data.choices" @c ...

Search for an item and add it repeatedly in a loop

I am facing an issue where I need to dynamically create HTML elements, but when attempting to add some elements inside a container in a loop, it does not seem to work. Why is this happening? var newHtml = '<div id="' + question.id + '"&g ...

Mastering the art of managing promises within nested loops

Embarking on my Promise journey, I find myself faced with a scenario where a list of objects within another list of objects needs to be updated based on responses from an external API. I've attempted to simulate the scenario below. The code snippet f ...

Unable to modify images and nicknames that have been selected from the steamapi

Having trouble syncing images and nicknames? Try using this: https://www.npmjs.com/package/steamapi New to promises and stuck at a point in your code? Here is the snippet of your code: const SteamAPI = require('steamapi'); const steam = n ...

Is it possible to use uglifyjs to merge multiple files into a single minified file?

I attempted to compress multiple javascript files into one using the uglifyjs tool, but encountered an issue. I ran $node uglifyjs.js to execute the file. Below is the content of the uglify.js file: var fs = require('fs'); var uglifyjs = re ...

Modifying the information displayed in a navigation panel or division using JavaScript

I am working on a navigation system that looks like this: <nav class="subnav"> <ul> <li><a href="a.html">This link leads to content A.</a></li> <li><a href="a.html">This link goes to content B.</a> ...

Accelerating the processing speed of Angular's $compile function

I'm currently putting together a template against a fresh scope: var scope = _.assign($rootScope.$new(true), { foo: 1, bar: 2 }) var element = angular.element('<my-element foo="foo" bar="bar"></my-element>') $compile(element ...

Struggling with ensuring that Angular-JS pauses and waits for an asynchronous call to complete before moving on

Understanding the use of promises in Angular for handling async operations is crucial, but I'm struggling to implement it effectively in this scenario. function fetchLineGraphData(promises){ var dataPoints = []; for (var i = 0; i < promise ...

Tips for displaying Modal Bootstrap at the bottom of the screen

Is there a way to configure Bootstrap so that the modal appears at the bottom of the browser? https://jsfiddle.net/9fg7jsu3/ <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Modal test</button& ...

"Using jQuery to toggle the visibility of multiple divs individually when

I am facing an issue with dynamically generated divs in asp.net. My goal is to display the contents of each div by clicking on its header. I attempted to achieve this using the following code: $(function () { var myHead = $(".toggle-container ...

Retrieving the output of JavaScript code in C#

How can I retrieve the value from a window.prompt() alert box in my C# Code Behind file? I know it's a simple line of JavaScript, but I want to execute it and get the result within my Code Behind. Whether it's done through a <script> tag in ...

Looking for assistance with transferring a data attribute to a form redirection

I'm seeking assistance with a coding dilemma I've encountered. To provide some background, I have a list of items on my website, each featuring a 'Book Now' button that redirects users to different pages. Recently, I incorporated a mod ...

Vue.js malfunctioning: Icons failing to display

I have integrated the Element UI library into my project and have been utilizing the date range picker component. Below is a snippet of my current file setup: import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css ...

various stunning galleries accessible from a single page of thumbnail images

I'm trying to create a unique gallery experience on my website. I have a set of 6 images, each featuring a different house. What I want is for each image, when clicked, to open up a fancybox gallery showcasing 4 more detailed photos of the same house. ...