find the repeated sequences of characters within the text

Trying to grasp a javascript string variable source;

Is there an efficient technique to identify all REPEATED substrings of length around 20 characters (even if they overlap or include substrings of slightly different lengths)?

An approach that could be considered is:

var len=20;
var sourceLen=source.length;
for (var i=0; i<sourceLen; i++){
    for (var j=i+1; j<sourceLen; j++){
        if (source.substring(i,i+len)==source.substring(j,j+len)){
            console.log(source.substring(i,i+len));
        }
    }
}

However, as the string size increases, the computation time also escalates significantly. There's been pondering about adjusting the steps of value exchanging (j+=5; instead of j++), but encountered certain constraints.

Another idea has been to explore using .indexOf to achieve similar outcomes with just one for-loop.

Are there any smarter strategies available to extract a list of duplicated strings of approximately 20 characters within the given string?

Answer №1

I was contemplating the use of .indexOf in order to achieve similar results with a single for-loop.

indexOf actually internally loops through the string. It's uncertain if they have integrated a more efficient string search algorithm; it might be worth experimenting with.

Is there a more clever approach to extract a list of duplicate strings that are exactly 20 characters long from the given string?

One could utilize a set containing all substrings for quick lookup.

function findDuplicates(input, length, callback) {
    var subStrings = {};
    for (var i=0; l=input.length-length; i<l; i++) {
        var sub = input.slice(i, length);
        if (sub in subStrings) // or even better: subStrings[sub]===true
            callback(sub);
        else
            subStrings[sub] = true;
    }
}
findDuplicates("…", 20, console.log.bind(console));

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

Tips for effectively dividing a component's code into smaller sub-components

Within my component MyComp, there exists an extensive code that I wish to divide into 3 separate components. In envisioning the structure of MyComp, I am seeking general advice and a brief example in response: import React, { Component, Fragment } from & ...

"Declare the Status, Refresh the Page, and Specify the Web

After refreshing the page, I am facing an issue where the text corresponding to the current URL is not being displayed. My application consists of a Main component that renders a MiniDrawer component containing a NavLink, followed by routing with the Route ...

What is the best way to retrieve form values on the server in nextJs?

I'm facing an issue with passing form data to my API endpoint in nextJS. I have set up the form using Formik and Yup for validation. Oddly, when I check the console on the client side, I can see the user input values just fine, but on the server side, ...

Maximizing Input Field Utility in React JS

I have a challenge with retrieving values from the input field and passing it to the useEffect. I specifically want the search to be triggered only after pressing the onSearch function. The issue is that I can only capture the value using the onChange func ...

losing track of the requested parameters while working asynchronously with Firestore documents

Today is my first time experimenting with firestore and express. Here is the code snippet I am using: app.post('/api/create', (req, res) => { (async () => { try { console.log(req.body); //the above consle.lo ...

Is there a more efficient way to optimize my coding for this Cellular Automata project?

As a beginner in programming, I wanted to delve into the world of cellular automata and decided to create my own using JavaScript. The project involves a simple binary (black and white) 2D CA where each cell updates its color based on the colors of its 8 ...

Understanding the mechanism of callback function in NodeJS within the context of routes and controllers

Trying to grasp the concept of callbacks and puzzled by the recurring issue TypeError: callback is not a function Here's my router setup: // getPriceRouter.js router.post('/getPrice', function(req, res) { priceController.getPrice(req, ...

Revamping ng-model in AngularJS

Here is my scenario: cols = [{field="product.productId"},{field="product.productPrice"}]; data = {products:[{product:{productId:1,productPrice:10}, {product:{productId:2, productPrice:15}}]} This is what I want to achieve: <div ng-repeat="product in ...

How to style text in CSS with a numbered underline beneath

Is there a way to apply underlining to text and include a small number underneath the underline in a similar style shown in this image, by utilizing css, html, or javascript? ...

I am facing difficulty in retrieving a unique dynamic div id using the useRef ReactJS hook, as it keeps returning the same id repeatedly

When using the useRef Reactjs hook, I encountered an issue where it returned the same id repeatedly instead of generating a dynamic div id. I need this functionality to map buttons and div ids in order to create a flexible accordion. The goal is to displ ...

The system considers the resource as a script, yet it was transmitted with the MIME type of text

I am encountering an issue when trying to integrate AngularJS/JavaScript into my HTML document. Each time I try to load my index.html file, the following error message appears: Resource interpreted as Script but transferred with MIME type text/html: "http ...

Vue.js is not properly synchronizing props in a child component when the parent component is updating the property

When it comes to communication between components, my structure looks something like this: <div id=chat-box> <div class="wrapper"> <div> <chat-header></chat-header> <message-container :chat="chat"></message ...

What is the best way to generate a fresh set of data from a search parameter?

I have received data from an API call that needs to be filtered. I am utilizing Redux instead of local state for this task. Below are the actions I have defined: import ActionTypes from '../constants/ActionTypes'; export const passengersDataAc ...

Creating a list in React and adding a delay using setTimeout() method

I'm a beginner when it comes to working with React and I've been attempting to display a list of posts using a JSON array. My goal is to have the list render after a certain number of seconds, but for some reason, the list isn't rendering us ...

Using Pandas to Replace String Column Values based on Different Conditions (Equal, Contains, Case-sensitive)

Reviewing the following dataframe. ID COUNTRY GENDER AGE V1 V2 V3 V4 V5 1 1 1 53 APPLE apple bosck APPLE123 xApple111t 2 2 2 51 BEKO beko SIMSUNG SamsungO123 ttBeko111t 3 3 1 24 SAMSUNG ...

Dealing with a checkbox click event in Vuejs when there is no parent element involvement

In the table below, you can see checkboxes displayed as images: example image of a table with checkboxes Here is an example code snippet: <tbody> <tr @click="goDetail"> <th scope="row><input type="checkbox" /></th> <t ...

The delivery person is not receiving a reply after making the delivery

When using Express/Node and Postgres with the 'pg' package, the following code snippet is used: const createEvent = (request, response) => { console.log(request.body); const { type, location, current_attendees ...

Tips for adding a new value to an array of objects in React

As I navigate my way through the world of React as a newcomer, I've encountered a challenge that I need some advice on. I am attempting to add a new key and value to an array of objects, but I'm struggling to accomplish this task. Can anyone prov ...

Angular 2 doesn't reflect changes in component variables in the view until mouseover happens

Since updating from angular2-alpha to the latest version, I've noticed that when a boolean value changes in my *ngIf directive, it doesn't reflect in the view until certain actions are taken. Here is the specific component code: declare var CKE ...

Vanishing HTML upon initial entry to the site using Gatsby and Material UI exclusively in live deployment

I run a blog using Gatsby that includes Material UI components to fetch markdown files through GraphQL. During development, everything operates smoothly. However, in production (after running gatsby build && gatsby serve), the HTML doesn't di ...