Accelerating the process of compiling subwords using the letters found in different words

The purpose of this code is to generate a list of arrays containing words based on their length, and each word includes an array of subwords that can be spelled using the characters from the word itself. I am in the process of optimizing the code to handle 81,000 words more efficiently. Currently, the program works but takes several hours to complete. I am seeking ways to improve the performance and speed up the processing time.

Below is a sample from the words.txt file:

do
dog
eat
go
god
goo
good
tea

The expected output in subwords.json format for the above text file is shown below:

[
    [],
    [],
    [
        {
            "word": "do",
            "subwords": [
                [],
                [],
                []
            ]
        },
        {
            "word": "go",
            "subwords": [
                [],
                [],
                []
            ]
        }
    ],
    [
        {
            "word": "dog",
            "subwords": [
                [],
                [],
                [
                    "do",
                    "go"
                ],
                [
                    "god"
                ]
            ]
        },
        {
            "word": "eat",
            "subwords": [
                [],
                [],
                [],
                [
                    "tea"
                ]
            ]
        },
        {
            "word": "god",
            "subwords": [
                [],
                [],
                [
                    "do",
                    "go"
                ],
                [
                    "dog"
                ]
            ]
        },
        {
            "word": "goo",
            "subwords": [
                [],
                [],
                [
                    "go"
                ],
                []
            ]
        },
        {
            "word": "tea",
            "subwords": [
                [],
                [],
                [],
                [
                    "eat"
                ]
            ]
        }
    ]
]

Here is the snippet of code responsible for reading words.txt and generating the subwords.json output:

Code snippet goes here...

I have been focusing on improving the isSubword function for better efficiency without success so far. While the current version does work over time, I am determined to enhance its speed significantly. Any suggestions or guidance on this would be highly appreciated!

Answer №1

To enhance the efficiency of the isSubword function, consider implementing a while loop instead of for loops. By breaking down the word and subword into arrays of characters and iterating through them within a while loop, you can quickly determine if the subword is contained in the word. The loop will terminate as soon as it encounters a character that is not part of the word, as demonstrated by the console log.

function isSubword(word, subword) {
  const wordArray = word.split("");
  const subwordArray = subword.split("");
  let isSubword = true;
  let i = 0;
  while(i < subwordArray.length && isSubword){
    const matchIndex = wordArray.findIndex(l => l === subwordArray[i] );
    console.log(subwordArray[i]);
    if(matchIndex < 0){
      isSubword = false;
    } else {
      wordArray.splice(matchIndex, 1);
      i += 1;
    }
  }
  return isSubword;
}

console.log(isSubword('test', 'set'));
console.log(isSubword('test', 'if'));
console.log(isSubword('test', 'tt'));
console.log(isSubword('test', 'ttt'));

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

Creating a multiplication table using a multidimensional array in mathematics

I'm attempting to create a multiplication table from 1 to 10 using a `for` loop and store it in a multidimensional array, but I'm encountering issues. Every time I run the script, I receive the following error message: Notice: Undefined offset ...

Techniques for navigating unidentified JSON structures using JavaScript

Currently, I am faced with the challenge of parsing the given data: { 'unknown-value': { name: 'AB', id: 'BLUE' }, 'unknown-value': { name: 'AC', id: 'PURPLE' } } My objec ...

having trouble emphasizing details using php mysql

I am currently working on a small project where I need to highlight specific words from a description on a webpage. The user can input keywords dynamically into the database for this purpose. When displaying data on the webpage, both the description and k ...

Disabling or Concealing the Timer in angularJS: A Step-by-Step Guide

In my project, I have integrated a Timer and Countdown Timer that counts down from 59 seconds to 0 seconds in reverse order using AngularJS. However, I am facing two issues that need to be resolved. Can anyone provide assistance? Issue 1: The problem lies ...

Vue, the versatile filtering tool for data tables in HTML

I am currently using Vue to populate an HTML table with data retrieved from an axios call. The table layout is perfect, but I am interested in finding a way (without converting the entire structure to datatables) to enable filtering on each column header. ...

How about we switch the text color to a lovely shade of green?

In the given HTML code snippet, I have the following line: $('#myform #progress').html('<img src="images/ajax-complete.gif" /> Successful.') I simply want to change the text color of Successful to green when it is shown. How can ...

Error: The ng-click directive is encountering a parsing syntax error. The token 'Object' is unexpected and is causing the error, it is expected to be enclosed in

When a user clicks on a point on a Google map, I am conducting reverse geocoding in the following manner: geocoder.geocode({'location': latlng}, function(results, status) { if (status === google.maps.GeocoderStatus.OK) { ...

Switching out the month name with its corresponding numerical representation

I recently transformed the date format from "24 Feb 2014" to "Feb-24-2014" using this code snippet: var dateStart = date; var arr = dateStart.split(' '); console.log(arr[1]+"-"+arr[0]+"-"+arr[2]); Now I'm trying to figure out h ...

How can I delete a pathway in paper.js?

Is it possible to create a new path using the canvas globalCompositeOperation set to 'destination-out'? If so, how would I go about doing this? I have observed that Item has a blendMode property which can be found at . However, experimenting wit ...

How can the "not selected" option be disabled in a Vue Select component?

I have implemented a select box in the following manner: JS: Vue.component("v-select", VueSelect.VueSelect); new Vue({ el: "#app", data: { options: [ { countryCode: "AU", countryName: "Australia" }, { countryCode: "CA", countryName: " ...

What is the process for transferring an array into an arraylist?

I am struggling to create an array or object (with multiple fields) and send it to an array list. Any assistance would be greatly appreciated. I have spent hours scouring through countless videos on YouTube containing the words object and array list, but h ...

Is your Ajax response suddenly failing to work after the initial attempt?

Describing my predicament: The code snippet below is what I have been using to insert a custom-designed div into my webpage. Initially, the div is successfully added; however, it stops working after the first instance. $('#addanother').click(fu ...

group of references to instances in a different class

I need to develop a class called DataBase that will have functionalities like managing menus, adding users, editing user information, deleting users, and so on. The users will belong to the User class. The initial structure is as follows: class base { ...

What is the best way to create this server backend route?

I'm currently working on a fullstack project that requires a specific sequence of events to take place: When a user submits an event: A request is sent to the backend server The server then initiates a function for processing This function should ru ...

Pass a JavaScript variable to a PHP script using AJAX when a button is clicked, with a dynamically set href attribute

This is the current situation: There is a checkbox on each row of a table that represents some information An initially disabled button becomes enabled when any checkbox is checked The button is enclosed by an <a></a> tag as shown: <a>&l ...

Problem encountered when trying to generate a geometrical figure using inputs for a specified row, column, and designated character to populate the shape

I need to take an integer input for the number of rows and columns, followed by a String input for the character. Let's say the user inputs 5 for rows, 2 for columns, and "@" as the character, then the expected output should be: @@ @@ @@ @@ @@ I ...

Encountered an issue with reading the property childnotes of null during data retrieval using ajax in PHP

Hello, I am encountering an error while trying to fetch data using ajax. The error message is "Cannot read property 'childNodes' of null". Can anyone help me identify what might be wrong with my code? I have created a form to search for data with ...

State not properly updating in the most recent version of Next.js

"use client"; import { useState , useEffect } from "react"; import React from 'react' function form() { const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [disable, ...

What is the best way to utilize useEffect in this scenario in order to promptly update the state? Alternatively, is there a

Has anyone encountered the issue of the updated state "filledBoxes" not showing up when using console.log in code until one turn later? I've been trying to figure out how to incorporate 'useEffect' but keep getting errors when trying to use ...

What improvements can be made to streamline this code and make it more concise with fewer lines?

Is there a way to shorten this code using a loop or something similar? It would be really helpful if someone could assist me in making the code more concise so that I can easily add additional nth-child elements like nth-child:4, 5. $(document).ready(fun ...